Wednesday, 12 January 2011

Log4net and you

SharePoint Developers often need to add logging capability to their code. Here are the easiest steps that will add log4net to your web part on local SP Development machine

1) Download log4net, extract to some folder on your computer
2) Deploy log4net to your GAC
3) In your SP project, Add reference to log4net
4) Add this line at the end of your Assemblyinfo.cs
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
5) Use log4net in your code
private ILog _log = LogManager.GetLogger(typeof(VisualWebPart1UserControl));
protected void Button1_Click(object sender, EventArgs e)
{
string s = DateTime.Now.ToString();
Button1.Text = s;
_log.InfoFormat("*** Server time: {0}", s);
}
6) Modify web.config of the target Web Application

<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
    <appender name="OutputDebugStringAppender" type="log4net.Appender.OutputDebugStringAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="log-file.txt" />
      <appendToFile value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="INFO" />
      <appender-ref ref="OutputDebugStringAppender" />
      <appender-ref ref="FileAppender" />
    </root>
  </log4net>

</configuration>

7) Use DebugView to view log messages live