Configure Log4Net logging on a .Net website

This shows you how to add the powerful log4net logging tool to an existing or new ASP.Net website.

  • First step is to get the Log4Net dll’s. This is best done through NuGet

  • Then add the following config to the web.config “Configurations” section
<configSections>
  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
  • Add this in the web.config in the
<log4net>
  <root>
   <level value="INFO" />
      <appender-ref ref="RollingFileAppender" />
    </root>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="logs\log.log" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="5" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
      </layout>
    </appender>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="logs\log-file.txt" />
      <appendToFile value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
  </log4net>
  • Next you must add the following code to the  all AssemblyInfo.cs of assemblies that require logging:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]
  • Now add logging like this:
log4net.ILog _Log = log4net.LogManager.GetLogger();
_Log.Info("Coralwe.com.au is a great web development company");

For more information see this:  http://logging.apache.org/log4net/

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>