How to read log4net configurations from .config file in Console Application?

You can learn easily by Google, ‘How to use .config file in log4net?’. My project has two different type of logging file. I want to centralize logging location configurable. Following code will help you to read log4net “File Appender” to get “File” tag value (file path).

public static log4net.Appender.IAppender[] GetAllAppenders()
        {
            ArrayList appenders = new ArrayList();
            log4net.Repository.Hierarchy.Hierarchy h =
                (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetLoggerRepository();
            appenders.AddRange(h.Root.Appenders);
            return (log4net.Appender.IAppender[])appenders.ToArray(typeof(log4net.Appender.IAppender));
        }

This function will give you all Appenders defined under log4net tag in .config file.

        public static FileAppender GetFileAppender()
        {
            IAppender[] appenderList = GetAllAppenders();
            FileAppender fileAppender = null;
            foreach (IAppender appender in appenderList)
            {
                if (appender.GetType().FullName == typeof(RollingFileAppender).FullName)
                {
                    fileAppender = (FileAppender)appender;
                    break;
                }
            }
            return fileAppender;
        }

This function will give return File Appender to get all information defined regarding File in RollingFileAppender under log4net tree.

FileAppender apprender = GetFileAppender();
log_path = apprender.File;

This code will give you File Path defined in .config file using log4net tag tree. FileAppender instance has some other useful information which may required in any log as per need.

Best of Luck!
End with Aho!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s