Musings on code and life

How to log nHibernate using log4net

1) Use nuget to install log4net

2) Configure log4net to log to the Visual Studio Output window in Web.config


<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

<log4net>
  <appender name="SqlFile" type="log4net.Appender.RollingFileAppender">
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
    <file value="C:\Temp\Logs\" />
    <datePattern value="'VoiceSql_'yyyy-MM-dd'.log'" />
    <staticLogFileName value="false" />
    <appendToFile value="true" />
    <rollingStyle value="Date" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="=============================================%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    </layout>
  </appender>
  <appender name="Trace" type="log4net.Appender.TraceAppender" >
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
    </layout>
  </appender>
  <root>
    <level value="ALL" />
    <appender-ref ref="Trace" />
  </root>
  <logger name="NHibernate.SQL" additivity="false">
    <level value="DEBUG" />
    <appender-ref ref="SqlFile" />
  </logger>
</log4net>

3) Turn on nHibernate loging in Web.config


<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
4) Turn on log4net in Global.asax.cs Application_Start

protected void Application_Start()
{
    log4net.Config.XmlConfigurator.Configure();
    log4net.LogManager.GetLogger(GetType()).Info("Application Started");
}