Using Log4Net in a C# web application

1 minute read

I came to Log4Net because I really loved Log4j , but I must say the documentation on this project is simply crappy, and half of the links in the project page are broken (conveniently , to all the examples…) .

After I’ve lost countless hairs on this should-have-been trivial thing , here’s what I’ve got:

(Note: I’ve tried to add the configuration to web.config , and later to just another App.config file with it , but to no avail - Log4Net ignored it . If you managed , please tell me how!)

  1. Create a configuration file (Lets call it My_Log4Net.config).
    This is a very basic configuration:</p>
    version="1.0" encoding="utf-8" ?>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
          <level value="ALL" />
          <appender-ref ref="LogFileAppender" />      

        <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
          <param name="File" value="BCThresholdUpdater.log" />
          <param name="AppendToFile" value="true" />
          <layout type="log4net.Layout.PatternLayout">
            <param name="Header" value="" />
            <param name="Footer" value="" />
            <param name="ConversionPattern" value="%d [%t] %-5p %m%n" />
    </configuration> </div> </div> </li>
  2. Add the reference to the configuration file in the assembly file:
    Add this line to the  AssemblyInfo.cs file:</p>
    [assembly: log4net.Config.XmlConfigurator(ConfigFile = "My_Log4Net.config", Watch = true)]
  3. All you have to do now is use the logger in your file . I usually use it like this:
    private static readonly ILog Logger = LogManager.GetLogger(typeof({NAME_OF_CURRENT_CLASS}));
  4. </ol> </div> Log away :)