basquang™ on clouds

August 26, 2011

Logging: Using Log4Net in ASP.NET MVC 3

Filed under: Logging,MVC — basquang @ 9:08 AM

This article will describe how to configure logging with Log4Net in ASP.NET MVC 3 application.

Firstly, Create a new ASP.NET MVC 3 Internet Application.

From visual studio Tools –> Library Package Manager –> Manage NuGet Packages… In Manage NuGet Packages… windows, search Log4Net then install log4net package to your project.

image

1. Logging to SQL Server database.

1.1  you need create a table as script bellow to store your logging to SQL Server database.

CREATE TABLE [dbo].[Log](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Date] [datetime] NOT NULL,
	[Thread] [varchar](255) NOT NULL,
	[Level] [varchar](20) NOT NULL,
	[Logger] [varchar](255) NOT NULL,
	[Message] [varchar](4000) NOT NULL
) ON [PRIMARY]

1.2 Open your web.config configuration file and add following log4net configuration sections

<configSections>
		<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
	</configSections>
	<log4net>
		<appender name="AdoNetAppender_SqlServer" type="log4net.Appender.AdoNetAppender">
			<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
			<connectionString value="Data Source=BASQUANG;Initial Catalog=LoggingDB;Integrated Security=True" />
			<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
			<parameter>
				<parameterName value="@log_date" />
				<dbType value="DateTime" />
				<layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
			</parameter>
			<parameter>
				<parameterName value="@thread" />
				<dbType value="String" />
				<size value="255" />
				<layout type="log4net.Layout.PatternLayout" value="%thread" />
			</parameter>
			<parameter>
				<parameterName value="@log_level" />
				<dbType value="String" />
				<size value="50" />
				<layout type="log4net.Layout.PatternLayout" value="%level" />
			</parameter>
			<parameter>
				<parameterName value="@logger" />
				<dbType value="String" />
				<size value="255" />
				<layout type="log4net.Layout.PatternLayout" value="%logger" />
			</parameter>
			<parameter>
				<parameterName value="@message" />
				<dbType value="String" />
				<size value="4000" />
				<layout type="log4net.Layout.PatternLayout" value="%message" />
			</parameter>
		</appender>		
		<root>
			<level value="All"/>
			<appender-ref ref="AdoNetAppender_SqlServer"/>
		</root>
	</log4net>

Note: Make sure you have already added the correctly version (4.0.0.0) of System.Data.dll to your project

2. Logging to Oracle database

2.1 you need create a table as script bellow to store your logging to Oracle database.

CREATE TABLE "LOG" (
  "DATETIME" TIMESTAMP(3) NULL,
  "THREAD" VARCHAR2(255 BYTE) NULL,
  "LOG_LEVEL" VARCHAR2(255 BYTE) NULL,
  "LOGGER" VARCHAR2(255 BYTE) NULL,
  "MESSAGE" VARCHAR2(4000 BYTE) NULL)
  STORAGE ( 
    NEXT 1048576 ) 
/

2.2 Open your web.config configuration file and add following log4net configuration sections

<configSections>
		<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
	</configSections>
	<log4net>		
		<appender name="AdoNetAppender_Oracle" type="log4net.Appender.AdoNetAppender">
			<connectionType value="System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
			<connectionString value="data source=XE;User ID=LoggingDB;Password=abcd1234-" />
			<commandText value="INSERT INTO Log (Datetime,Thread,Log_Level,Logger,Message) VALUES (:log_date, :thread, :log_level, :logger, :message)" />
			<bufferSize value="128" />
			<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>
		</appender>
		<root>
			<level value="All"/>
			<appender-ref ref="AdoNetAppender_Oracle"/>
		</root>
	</log4net>

Note: Make sure you have already added the correctly version (4.0.0.0) of System.Data.Oracle.dll to your project

3. Add this line of code to  Application_Start on Global.asax.cs file

log4net.Config.XmlConfigurator.Configure(); 

4. Add these lines of code on HomeController to testing your logging configuration

public ActionResult About()
        {
            log4net.ILog log = log4net.LogManager.GetLogger(this.GetType());
            log.Info("Test message for Log4Net"); 
            return View();
        }

5. Test your configuration. Run your website, from home page click on About then looking for a new record added on database table.

Advertisements

10 Comments »

  1. Great example – works like a charm!

    Comment by Rob — February 5, 2012 @ 12:42 AM | Reply

  2. can’t get it to work. did as what you suggested but nothing was written. I do I debug this?
    Your article is very easy to follow. I think the issue may be something else

    Comment by ban — February 8, 2012 @ 11:28 PM | Reply

  3. Followed everything in the instructions but nothing was written in the database.

    Comment by JT — February 23, 2012 @ 12:11 AM | Reply

  4. I take back my last comment. Information did get logged into the database… it was just being cached by the library. Changed bufferSize value accordingly.
    Thank you!

    Comment by JT — February 23, 2012 @ 12:29 AM | Reply

  5. Good one! But wouldn’t be better to write your own Attribute that inherits from HandleError, cause now you’ll always have to instantiate your logger.

    Comment by micclo — March 5, 2012 @ 9:43 PM | Reply

  6. Neat step by step instructions. Just to update, incase u need to write to a physical file then ur tag in the config should look like :

    Comment by Rochelle Ann — May 2, 2012 @ 3:19 PM | Reply

  7. […] DONE Share this:TwitterFacebookLike this:LikeBe the first to like this. […]

    Pingback by ASP.NET mvc 3 logging log4net « dnhome — July 26, 2012 @ 11:29 AM | Reply

  8. Thanks a lot…:) It works very nice…:)Once again thanks.

    Comment by Mac — August 23, 2012 @ 11:44 AM | Reply

  9. Very nice.. its working fine.

    Comment by Rishi — May 20, 2013 @ 10:26 AM | Reply

  10. Your style is very unique in comparison to other folks I’ve read stuff from.
    Many thanks for posting when you’ve got the
    opportunity, Guess I’ll just bookmark this site.

    Comment by kindle download — September 9, 2014 @ 3:56 AM | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: