User Activity logging in ASP.NET MVC app using Action Filter and log4net

In this post, I will demonstrate how to use an action filter to log user tracking information in an ASP.NET MVC app. The below action filter will take logged user name, controller name, action name, timestamp information and the value of route data id. These user tracking information will be logged using log4net logging framework.

 

  1. public class UserTrackerLogAttribute : ActionFilterAttribute, IActionFilter
  2. {        
  3.     public override void OnActionExecuted(ActionExecutedContext filterContext)
  4.     {
  5.         var actionDescriptor= filterContext.ActionDescriptor;
  6.         string controllerName = actionDescriptor.ControllerDescriptor.ControllerName;
  7.         string actionName = actionDescriptor.ActionName;
  8.         string userName = filterContext.HttpContext.User.Identity.Name.ToString();
  9.         DateTime timeStamp = filterContext.HttpContext.Timestamp;
  10.         string routeId=string.Empty;
  11.         if (filterContext.RouteData.Values["id"] != null)
  12.         {
  13.             routeId = filterContext.RouteData.Values["id"].ToString();
  14.         }
  15.         StringBuilder message = new StringBuilder();
  16.         message.Append("UserName=");
  17.         message.Append(userName + "|");
  18.         message.Append("Controller=");
  19.         message.Append(controllerName+"|");
  20.         message.Append("Action=");
  21.         message.Append(actionName + "|");
  22.         message.Append("TimeStamp=");
  23.         message.Append(timeStamp.ToString() + "|");
  24.         if (!string.IsNullOrEmpty(routeId))
  25.         {
  26.             message.Append("RouteId=");
  27.             message.Append(routeId);
  28.         }
  29.         var log=ServiceLocator.Current.GetInstance<ILoggingService>();
  30.         log.Log(message.ToString());
  31.         base.OnActionExecuted(filterContext);
  32.     }
  33. }

 

The LoggingService class is given below

  1. public class LoggingService : ILoggingService
  2.     {
  3.         private static readonly ILog log = LogManager.GetLogger
  4.             (MethodBase.GetCurrentMethod().DeclaringType);
  5.         public void Log(string message)
  6.         {
  7.             log.Info(message);
  8.         }
  9.     }
  10.     public interface ILoggingService
  11.     {
  12.         void Log(string message);
  13.     }

 

The LoggingService class is using log4net framework for logging. You can add reference to log4net using NuGet.

The following command on NuGet console will install log4net into your ASP.NET MVC app.

PM> install-package Log4Net

The below configuration information in web.config will configure log4net for using with Sql Server

Let me add a log4net section to the <configSections> of web.config

  1. <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>

The below is the log4net section in the web.config file

  1. <log4net>
  2.     <root>
  3.       <level value="ALL"/>
  4.       <appender-ref ref="ADONetAppender"/>
  5.     </root>
  6.     <appender name="ADONetAppender" type="log4net.Appender.AdoNetAppender">
  7.       <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  8.       <connectionString value="data source=.\SQLEXPRESS;Database=MyFinance;Trusted_Connection=true;" />
  9.       <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
  10.       <parameter>
  11.         <parameterName value="@log_date" />
  12.         <dbType value="DateTime" />
  13.         <layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
  14.       </parameter>
  15.       <parameter>
  16.         <parameterName value="@thread" />
  17.         <dbType value="String" />
  18.         <size value="255" />
  19.         <layout type="log4net.Layout.PatternLayout" value="%thread" />
  20.       </parameter>
  21.       <parameter>
  22.         <parameterName value="@log_level" />
  23.         <dbType value="String" />
  24.         <size value="50" />
  25.         <layout type="log4net.Layout.PatternLayout" value="%level" />
  26.       </parameter>
  27.       <parameter>
  28.         <parameterName value="@logger" />
  29.         <dbType value="String" />
  30.         <size value="255" />
  31.         <layout type="log4net.Layout.PatternLayout" value="%logger" />
  32.       </parameter>
  33.       <parameter>
  34.         <parameterName value="@message" />
  35.         <dbType value="String" />
  36.         <size value="4000" />
  37.         <layout type="log4net.Layout.PatternLayout" value="%message" />
  38.       </parameter>
  39.     </appender>
  40.   </log4net>

 

Configure log4net

The below code in the Application_Start() of Global.asax.cs will configure the log4net

  1. log4net.Config.XmlConfigurator.Configure();

 

The below Sql script is used for creating table in Sql Server for logging information

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]

2 Comments

  • I have problems integrating log4net with ASP.NET 4. Searching on Internet indicates that log4net hasn't released version that are compatible with latest versions of .NET. Would you tell which versions of .NET you used? Have you tried latest version of .NET?

  • @Mohan Reddy - I have worked log4Net with ASP.NET 4/ ASP.NET MVC 3 without any problem. I have installed the log4net using NuGet

Comments have been disabled for this content.