How To Configure Log4Net In A C# Application



TODO:

Have you ever wanted to use log4net in your C# application?

 

SOLUTION:

To do so, you need to do 2 things:

 

Step 1:  Add the following entry to the bottom of your AssemblyInfo.cs file

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

 

Step 2:  Add this entry to your web or app.config file

<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>
 
  <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="c:\YOUR DIRECTORY HERE\your log file name.log" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <datePattern value="yyyyMMdd" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="30MB" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d %-5level %logger{1} : %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="ALL" />
      <appender-ref ref="RollingFileAppender" />
    </root>
  </log4net>

 

NOTES:

If you already have a "configSections" entry, just add the new key to that section