Introduction
In this article we will quickly add Log4Net into the website so that later on we can decide whether to use Log4Net or NLog to log our custom messages.
Log4Net is a very widely used logger and it is quite likely that you have 3rd party dependencies in your website that already use Log4Net so it can be a good idea to track any messages that it logs.
Log4Net
The steps we need to follow are:
1. Download Log4Net
2. Add a reference to Log4Net
3. Add a table in our database to store the Log4Net logs
4. Modify the web.config file for Log4Net
5. Implement a Log4NetLogger that implements our ILogger interface.
Setting up the database
Run the following script to create the table that Log4Net will log message to:
04 | SET QUOTED_IDENTIFIER ON |
10 | CREATE TABLE [dbo].[Log4Net_Error]( |
11 | [Id] [ int ] IDENTITY(1,1) NOT NULL , |
12 | [ Date ] [datetime] NOT NULL , |
13 | [Thread] [ varchar ](255) NOT NULL , |
14 | [ Level ] [ varchar ](50) NOT NULL , |
15 | [Logger] [ varchar ](255) NOT NULL , |
16 | [Message] [ varchar ](4000) NOT NULL , |
17 | [Exception] [ varchar ](2000) NULL |
Web.config configuration
Add the following to the top of your web.config file:
4 | < section name = "log4net" type = "log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> |
Add the following underneath the configuration element in your web.config file:
02 | < appender name = "AdoNetAppender" type = "log4net.Appender.AdoNetAppender" > |
03 | < bufferSize value = "100" /> |
04 | < connectionType value = "System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> |
05 | < connectionString value = "data source=[Machine]/[Instance];Initial Catalog=[DatabaseName];Integrated Security=True" /> |
06 | < commandText value = "INSERT INTO Log4Net_Error ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" /> |
08 | < parameterName value = "@log_date" /> |
09 | < dbType value = "DateTime" /> |
10 | < layout type = "log4net.Layout.RawTimeStampLayout" /> |
13 | < parameterName value = "@thread" /> |
14 | < dbType value = "String" /> |
16 | < layout type = "log4net.Layout.PatternLayout" > |
17 | < conversionPattern value = "%thread" /> |
21 | < parameterName value = "@log_level" /> |
22 | < dbType value = "String" /> |
24 | < layout type = "log4net.Layout.PatternLayout" > |
25 | < conversionPattern value = "%level" /> |
29 | < parameterName value = "@logger" /> |
30 | < dbType value = "String" /> |
32 | < layout type = "log4net.Layout.PatternLayout" > |
33 | < conversionPattern value = "%logger" /> |
37 | < parameterName value = "@message" /> |
38 | < dbType value = "String" /> |
40 | < layout type = "log4net.Layout.PatternLayout" > |
41 | < conversionPattern value = "%message" /> |
45 | < parameterName value = "@exception" /> |
46 | < dbType value = "String" /> |
48 | < layout type = "log4net.Layout.ExceptionLayout" /> |
54 | < level value = "DEBUG" /> |
55 | < appender-ref ref = "AdoNetAppender" /> |
Implement a Log4NetLogger
Now let’s create a logger class for Log4Net that implements our ILogger interface (discussed in part 3).1. Create a new folder underneath the Services folder. Our folder structure will be like this:
Services -> Logging -> Log4Net
2. Create a new class file in the new folder and name it ‘Log4NetLogger.cs’.
3. Add the following code to the class:
02 | using System.Collections.Generic; |
08 | namespace MvcLoggingDemo.Services.Logging.Log4Net |
10 | public class Log4NetLogger : ILogger |
15 | public Log4NetLogger() |
17 | _logger = LogManager.GetLogger( this .GetType()); |
20 | public void Info( string message) |
22 | _logger.Info(message); |
25 | public void Warn( string message) |
27 | _logger.Warn(message); |
30 | public void Debug( string message) |
32 | _logger.Debug(message); |
35 | public void Error( string message) |
37 | _logger.Error(message); |
40 | public void Error(Exception x) |
42 | Error(LogUtility.BuildExceptionMessage(x)); |
45 | public void Error( string message, Exception x) |
47 | _logger.Error(message, x); |
50 | public void Fatal( string message) |
52 | _logger.Fatal(message); |
55 | public void Fatal(Exception x) |
57 | Fatal(LogUtility.BuildExceptionMessage(x)); |
You will notice that the code above is almost identical to the one we created for NLog. The only difference is the line in the constructor that instantiates the Log4Net logger.
Testing the Log4Net logger
The last step is to write some code that uses our new debugger. Update the Index method of our Activity controller like this:
(You will also need to add a refernce to the namespace, “MvcLoggingDemo.Services.Logging.Log4Net” at the top of your file)
01 | public ActionResult Index() |
03 | IEnumerable list = activityRepository.GetAll(); |
05 | NLogLogger logger = new NLogLogger(); |
06 | logger.Info( "Test message for NLog" ); |
08 | Log4NetLogger logger2 = new Log4NetLogger(); |
09 | logger2.Info( "Test message for Log4Net" ); |
13 | throw new Exception( "A test exception" ); |
17 | Console.WriteLine( "ERROR - An error has occurred" ); |
Now go to the Index page for Activities and inspect the Log4Net_Error table to ensure that the message has been logged.
Conclusion
We now have Elmah, NLog, Log4Net and Health monitoring setup and working on our website. The next few articles will focus on building a log reporting viewer so that we can tie all of these things together so that we can see a consolidated and consistent view of everything that is getting logged on our website.
No comments:
Post a Comment