Logging: Using Log4Net in ASP.NET MVC 3

  • Post author:
  • Post category:Blog
  • Post comments:0 Comments
  • Reading time:6 mins read

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.

This Post Has 0 Comments

  1. Rob

    Great example – works like a charm!

  2. ban

    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

  3. JT

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

  4. JT

    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!

  5. micclo

    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.

  6. Rochelle Ann

    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 :

  7. Mac

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

  8. Rishi

    Very nice.. its working fine.

  9. kindle download

    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.

Leave a Reply