My Software Notes

Useful things I discover

Archive for the ‘Logging’ Category

log4net – Quick and Dirty set up

leave a comment »

I do this infrequently enought that I have to keep going back to old projects to see the steps.  So, I’m putting them here to save me the hunting.

  1. Use NuGet to pull in the Log4Net binaries, etc. to your project.
  2. Add to your web.config <configSections> element:
    <section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
  3. Add to your web.config under the root <configuration> element (modify the appender as you wish):
      <log4net threshold="All">
        <appender name="LogFile" type="log4net.Appender.FileAppender" >
          <file value="c:\logs\MyLog.log" />
          <appendToFile value="true" />
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date %-5level %-40logger{2} - %message%newline" />
          </layout>
        </appender>
    
        <root>
          <level value="All" />
          <appender-ref ref="LogFile" />
        </root>
      </log4net>
  4. Add to your AssemblyInfo.cs file:
    [assembly: log4net.Config.XmlConfigurator(Watch = true)]
  5. In the file where you want to use it:
    using log4net;
  6. Example of use:
    var log = LogManager.GetLogger(System.Reflection.MethodBase
        .GetCurrentMethod().DeclaringType);
    log.Error("This is a test log message with an exception", 
        new Exception("Test Exception"));

That should do it.

Examples of config: log4net Config Examples

Advertisements

Written by gsdwriter

January 31, 2013 at 1:07 pm

Posted in .NET, Logging, Tools