Configuring Log4Net For Web Applications/Services

We all understand why we should use configuration files for log4net. The use of configuration files is specified @ The config settings can either be added to the web.config file or we can create a seperate xml file say log4net.config.
I prefer to use a seperate config file. And the main reason is log4net framework will watch (using FileSystemWatcher) the external configuration file and will reload the config each time the file is modified. For some reason this powerful feature is not available if the settings are kept in web.config.
The other important class to understand is XmlConfigurator. This configurator must be set if a config file is used.
The default way to configure is log4net.Config.XmlConfigurator.Configure();
This makes the log4net look into the app.config or web.config file.
Configuration Attributes… read at the link specified
XmlConfiguratorAttribute The log4net.Config.XmlConfiguratorAttribute Allows the XmlConfigurator to be configured using the following properties:

  • ConfigFile If specified, this is the filename of the configuration file to use with the XmlConfigurator. This file path is relative to the application base directory (AppDomain.CurrentDomain.BaseDirectory). This property cannot be used in conjunction with the ConfigFileExtension property.
  • ConfigFileExtension If specified, this is the extension for the configuration file. The assembly file name is used as the base name with the this extension appended. For example if the assembly is loaded from the a file TestApp.exe and the ConfigFileExtension property is set to log4net then the configuration file name is TestApp.exe.log4net. This is equivalent to setting the ConfigFile property to TestApp.exe.log4net. The path to the configuration file is build by using the application base directory (AppDomain.CurrentDomain.BaseDirectory), the assembly file name and the configuration file extension.  This property cannot be used in conjunction with the ConfigFile property.
  • Watch If this flag is specified and set to true then the framework will watch the configuration file and will reload the config each time the file is modified.

If neither of the ConfigFile or ConfigFileExtension properties are specified, the web configuration file (web.config) will be used as the log4net configuration file. The System.Configuration API is only available if the configuration data is in the application’s config file; The file named MyApp.exe.config or Web.config.
Because the System.Configuration API does not support reloading of the config file the configuration settings cannot be watched using the log4net.Config.XmlConfigurator.ConfigureAndWatch methods. The main advantage of using the System.Configuration APIs to read the configuration data is that it requires less permissions than accessing the configuration file directly. The only way to configure an application using the System.Configuration APIs is to call the log4net.Config.XmlConfigurator.Configure() method or
the log4net.Config.XmlConfigurator.Configure(ILoggerRepository) method.

All that said let’s have a look how to put all this in place.

  1. Create a log4net.config file. This file will contain your logger settings. Please refer the official website for details how to create a valid config file.
  2. Add the following attribute to your AssemblyInfo.cs file
    [assembly: log4net.Config.XmlConfigurator(ConfigFile = “log4net.config”, Watch = true)]
    Alternately you can add the following line of code in the global.asax file in Application_Start Event.
    XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(HttpContext.Current.Request.PhysicalApplicationPath + “log4net.config”));
  3. Create the Logger
    private static readonly ILog log = LogManager.GetLogger(typeof(NameofYourClass));

    Its a good practice of create a seperate logger for each class. Then you can scope where the error occurred.
  4. Start logging.
    log.Error(exception.Message, exception.InnerException);

9 Responses to “Configuring Log4Net For Web Applications/Services”

  1. hetal savaliya Says:

    In my project,If I don’t have Assemblyinfo.cs file,then How Can I use log4net

  2. Anubhav Goyal Says:

    Hi Hetal,
    You can put the log4net settings in your web.config/app.config file. you need to focus on these

    <section name=”log4net” type=”log4net.Config.Log4NetConfigurationSectionHandler, log4net” />

    add/merge the following settings in your configSection. This basically tells ConfigurationManager how to read log4net config.

    Then you need to specify the log4net configuration.
    I recommend you to follow this link. There are a lot of possible values that can go in here. You need to understand an Appender and a logger. Hope this helps

  3. Anubhav Goyal Says:

    Here is a sample log4net configuration
    <appender name=”RollingFile” type=”log4net.Appender.RollingFileAppender”>
    <file value=”logs\logfile.log” />
    <appendToFile value=”true” />
    <maximumFileSize value=”1000KB” />
    <rollingStyle value=”Date” />
    <datePattern value=”yyyyMMdd” />
    <layout type=”log4net.Layout.PatternLayout”>
    <conversionPattern value=”%date [%thread] %-5level %logger [%ndc] – %message%newline” />
    <level value=”INFO” />
    <appender-ref ref=”RollingFile” />
    <logger name=”Sample.ProgramClass”>
    <level value=”INFO” />

    NOTE: it specifies to use the Rolling File appender.
    The logger name is Sample.ProgramClass and log all INFO and above messages.

  4. Syed Jazbi Says:

    I am not able to log in XML file. The following message displayed when I open the XML file:

    Cannot view XML input using XSL style sheet. Please correct the error and then click the Refresh button, or try again later.
    The operation completed successfully. Error processing resource ‘file:///C:/AppLog3.xml’. Line 1, Position 363

    Following is the code in my App.Config file:

    I don’t know what I am doing wrong, I would really appreciate it if you can help me to resolve this issue.


  5. Eman Says:

    Thanks for pointing out that you can use an assembly attribute to watch the configuration file for changes. It worked really well for me.

  6. rem Says:

    Helpfull blog…

  7. Hetal Savaliya Says:

    Thanks all!

  8. Vijay anand Says:

    Thanks. great stuff.

  9. Rahul Patel Says:

    This is a brilliant article. Thanks so much. Its working fine.

    Thanks so much.

Leave a Reply

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

You are commenting using your 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

%d bloggers like this: