How to use Log4Net utility for logging into database using c#

Rohit Vyas picture Rohit Vyas · Mar 20, 2013 · Viewed 66.7k times · Source

Currently in my project log4net is used to log all the exception, information, warnings etc. to a text file, but now what I want is to log all these details into database table instead of file.
Please help me to do this.

Many thanks in advance.

Configuration:

<log4net>
  <root>
    <level value="DEBUG" />
    <appender-ref ref="ADONetAppender" />
  </root>
  <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
    <bufferSize value="100" />
    <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    <connectionString value="server=xxxx; uid=xxxx; pwd=xxxx; database=xxxx" />
    <commandText value="INSERT INTO log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
    <parameter>
      <parameterName value="@log_date"/>
      <dbType value="DateTime"/>
      <layout type="log4net.Layout.RawTimeStampLayout"/>
    </parameter>
    <parameter>
      <parameterName value="@thread"/>
      <dbType value="String"/>
      <size value="255"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%thread"/>
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@log_level"/>
      <dbType value="String"/>
      <size value="50"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%level"/>
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@logger"/>
      <dbType value="String"/>
      <size value="255"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%logger"/>
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@message"/>
      <dbType value="String"/>
      <size value="4000"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%message"/>
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@exception"/>
      <dbType value="String"/>
      <size value="2000"/>
      <layout type="log4net.Layout.ExceptionLayout"/>
    </parameter>
  </appender>
</log4net>

Code in .cs file:

private log4net.ILog log = log4net.LogManager.GetLogger(typeof(ImportGlobalIPVData));
log.Error("This is Error");

But nothing gets inserted into log table after using above code.

Answer

L-Four picture L-Four · Mar 20, 2013

You can have a look here, I think this is exactly what you need.

Note that if you want to use log4net from a client application and write to a database, you might want to consider to put a service in between. In that case you can easily write your own log4net adapter that calls your LogService (fire and forget) that logs into your database (probably using MSMQ).