How to store log in database using log4net

One of the best ways to store log in the database using log4net coz it is easy to use and its world wide popularity. For storing log in the database all task are manage by log4net internally.

At first you need to create a table for Storing log in the SqlServer database

The table should be like as

CREATE TABLE [dbo].[Log] (

[Id] [int] IDENTITY (1, 1) NOT NULL,

[Date] [datetime] NOT NULL,

[Thread] [varchar] (255) NOT NULL,

[Level] [varchar] (50) NOT NULL,

[Logger] [varchar] (255) NOT NULL,

[Message] [varchar] (4000) NOT NULL,

[Exception] [varchar] (2000) NULL

)

1. Download log4net from http://logging.apache.org/log4net/download.html

2. Open visual studio and create an application.

3. Add to the project a reference to the \bin\net\2.0\release\log4net.dll assembly in the log4net distribution.

4. Now put this web.config/app.config file in configuration tag.

<configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/> </configSections> <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=servername; uid=Lion; pwd=Lionman; database=databasename" /> <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> 

In the connection string tag you need to change server name and database. You also can decide how to define the security part of the connection string.

There are two way to define the security part

· Use integrated Security

· State the username and the password in the connection string.

In both cases you need to make sure that the user has access to the, SQL server, the database and the databasetable that Log4Net is going to use.

If you use integrated security then the connection string should be like as

<connectionString value=”Data Source=servername;initial Catalog=databasename; Integrated Security=True;”/>

5. To use log4net put this as a local class variable:    private static readonly log4net.ILog log =log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

6. And do this to write messages in the log file.   log.Debug(”this text will be in log file”);

For Example,

using System;
using System.Collections.Generic;
using System.Text; using log4net;
using log4net.Config; using log4net.Core;
using log4net.Repository.Hierarchy;
using log4net.Appender;

namespace LogPractice
{
    class Program
    {
        private static readonly log4net.ILog log =log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            log.Debug("log Debug");
            log.Info("log Info");
            log.Warn("log Warn");
            log.Error("log Error");
            log.Fatal("log Fatal");
        }
    }
}

Now run the code then you can see the log stored in the database table.

31 thoughts on “How to store log in database using log4net

  1. Just want to mention that Log4Net has the possibility to reload configuration dynamically when the config is changed, typical used if you change the log level when the application is running.

    To activate this you need to use the XmlConfigurator.ConfigureAndWatch instead of XmlConfigurator.Configure()

    The ConfigureAndWatch can be invoked using several methods my personal favorite is using an assembly-level attribute:
    [assembly: log4net.Config.XmlConfigurator(Watch=true)]

    Best regards
    Georg Jansen
    http://www.l4ndash.com – Log analysis and monitoring made easy

  2. Hi friend,

    I used Log4net as above said.It is very good.
    But i faced one problem is data which we entered in to database is not commited immediatly.after closing app/dadaserver it is coming.
    plase help on this waiting for your reply.

    Thanks regards
    satya

  3. Hello,

    I’m facing with the same problem.. data which we entered in to database is not commited immediatly.after closing app/dadaserver it is coming.
    Why happens this? How can data be commited without shutting down the server? I’m using C#, not VB.

    Thanks

  4. Great article. How do i get the identity of the log i have just inserted.

    For eg. i want to display the id to user so that they can contact support team in case of exception.

    So once i call Log.Fatal it should return me the id. Can i override Fatal method?

    • Mac,

      You’ve probably already moved on from your question here, but given that I just had to figure out this problem (found this thread for another purpose), I thought I’d share our solution.

      The short answer to your question about over-riding the method is yes, you can. I will shamelessly plug the article from which I stole the basis for Log4Net overriding here:

      http://www.devx.com/dotnet/Article/32096/1954

      Timur Fanshteyn did a fantastic job describing this process, and made it easy for even a C# hack like myself to implement with relatively fast success.

      That said, I’m not sure that you can, or should, override the method in a manner that returns anything other than void. I’m not sure why I think that (I might have read something about that, or I might just be overly paranoid about altering the method signature), but we came up with a different solution from the one that you’re looking to implement (though we did consider your solution as well).

      The solution is based around the assumption that the reason you need to have the identity value is because you want to use that to let the customer give you a “handle” to the specific error that they received (through your help desk, or other mechanism). The key there is “error.” The assumption is that you will raise an exception for the condition that you want the customer to see your unique identifier value. We had long discussions about whether or not it would be valuable to be able to capture the unique ID for an INFO message, or a non-exception containing log message, and determined that we couldn’t think of a use case where that would be valuable.

      Given that, we chose to subclass the exception class, and assign the exception a unique ID rather than assigning the logged event a “displayable” unique ID. This has a couple of benefits.

      Subclassing the exception class has benefits on its own, outside of just capturing the unique ID. The ability to customize the message presentation to the customer, the ability to assign additional attributes to the exception (perhaps a list of parameters that caused the exceptional condition, etc), and the ability to trap all exceptions EXCEPT those that you know that you’ve already processed (by checking to see if the caught exception is an instance of your application specific exception class; if it is, you’ve handled it already, if not, you have to do some handling) are among them.

      In addition, if you assign the unique ID to the exception rather than to the log event, you can write the exception along with the unique ID to both the database and a log file. This may not sound like the best of ideas, but if you’ve ever run out of space for your exception log table, you’ll appreciate being able to capture the exceptions and the unique ID’s along with them in the file (because remember, according to the Log4N folks, the over-ridden methods in any of the logging classes cannot be permitted to throw exceptions; you may not KNOW that you’re out of database space until your DBA figures it out independent of your application).

      I’m sure that there are disadvantages to this thought process as well (I’m betting that someone will figure out a scenario where they will want to display the unique ID of a non-exception-containing log message, for example), but for us, this implementation solved a host of problems.

  5. Hi, I`m trying to store my logs in my database(SQL Server 2005), I tried to use this code but nothing happened, Do I need to do anything else??
    Maybe write another code in another class…
    thanks..

  6. Hi,

    I am using sqlserver2008 and i hav done all the steps mentioned above but the log is not updating in the database i am not getting any error msg

  7. Also I have another question. I have a project. There are three types of users.Users,Administrator etc. I want to separete their own log. I created UserLogTable and AdminLog also I want to also create an order table which is keep orderLog. How can I do this?

    • Hi, i set buffersize value r2 =1 but no luck i configure exactly that is explained before any ideas? using sql server

  8. To get this working in the App.Config you need to correct a small error which is to correct the case as shown below. Note that Log4net has an upper case L after Log4NetConfigurationSectionHandler,Log4net when it appears that it should be a lower case l.
    INCORRECT (Note upper case L after the comma, change this to a lower case) :

    CORRECT (lower case l after the comma, this work for me.):

  9. You need run this line of code: log4net.Config.XmlConfigurator.Configure(); in Application_Start of your Global.asax when using Ado.net with Asp.net. It’s true in my case, I have waste long time because log4net doesn’t running until I add this code.

  10. 1. Change all relevant references in web.config to [case sensitive] “AdoNetAppender” and 2. set bufferSize value=”1″ if you want immediate update to database while testing this. Thanks for this blog.

  11. Hey guys,
    For thos of you having a hard time trying to make this work, in my case, I found my solution issuing this within VS.NET immediate window:

    log4net.LogManager.GetLogger(this.GetType()).Error(“test”);

    It thrown the Sql exception below. I fixed the null issue and it worked like a charm !

    log4net:ERROR [AdoNetAppender] Exception while writing to database
    System.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column ‘event_type_id’, table ‘reduxssp_test.dbo.eventlog’; column does not allow nulls. INSERT fails.
    The statement has been terminated.

    hth!

    Sylvain Audet
    MyDevPartner.com

Leave a reply to Izaac Asimov Cancel reply