Logging in .NET MVC application
What is Logging? & Why Logging?
Logging is an integral part of the software development project but it often disregarded until the program crashes. Logging serves numerous purposes including root cause analysis, bug analysis and even performance reviews for the application.
During application development we consider logically correct and incorrect execution of the code based on the end-user input, sometimes even after testing our code did not respond correctly based on end-user requests. Taking care of this situation we implement our code via exception handling techniques(try-catch block) this block successfully executes all possible types of exception apart from this developer can implement custom exception handling logic. In real-time applications its important to log the exception occurred in your application to further analyze the problem/issue in your code. There are different ways to log the exception we are seeing logging in the database and in the text file.
There are different libraries available for adding a logging mechanism in your application. We are using NLog over here NLog is a very good logging framework to achieve logging in .NET Applications. It is very easy to configure and logging information can be written to Files, database, Event logs, and ASP.NET Trace files.
Implementation of logging in MVC Application:
Step 1: Create a New MVC Application
New->Project->Asp.Net web Application(.Net Framework)->MVC->ProjectName
By following these projects will be created for you.
Step 2: Install NLog
Next task here is to add NLog NuGet Package in your project for that follow the below process
Right-click on project->Manage NuGet Packages-> Search for NLog->Install latest stable version
Step 3: Creating a table to log the exception
As we are using database logging so we need to create the table to store the exception,
CREATE TABLE [dbo].[exceptionDetails]([id] [int] IDENTITY(1,1) NOT NULL,[timestamp] [datetime] NOT NULL,[level] [varchar](100) NOT NULL,[logger] [varchar](500) NOT NULL,[message] [varchar](1500) NOT NULL,[exception] [varchar](1500) NULL,[stacktrace] [varchar](1500) NULL,CONSTRAINT [PK_ExceptionDetails] PRIMARY KEY CLUSTERED([id] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GO
Step 4: Adding the configuration file
We will add a configuration file called Nlog.config which will be used to log the exception in specified sources(here we are using file and database logging) in that file which includes files, database and windows event viewers.
<?xml version=”1.0"?><configuration><configSections><section name=”nlog” type=”NLog.Config.ConfigSectionHandler, NLog” /></configSections><nlog xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance"><targets><target name=”logfile” xsi:type=”File” fileName=”${basedir}/ExceptionLogs/${date:format=yyyy-MM-dd}-api.log” /><target name=”database” type=”Database” connectionString=”Data Source=your sql server;initial catalog=your database name;Integrated Security=True;”><commandText> insert into exceptionDetails ([TimeStamp],[Level],Logger, [Message], Exception, StackTrace) values (@TimeStamp, @Level, @Logger, @Message, @Exception, @StackTrace); </commandText><parameter name=”@TimeStamp” layout=”${date}” /><parameter name=”@Level” layout=”${level}” /><parameter name=”@Logger” layout=”${logger}” /><parameter name=”@Message” layout=”${message}” /><parameter name=”@Exception” layout=”${exception}” /><parameter name=”@StackTrace” layout=”${stacktrace}” /><dbProvider>System.Data.SqlClient</dbProvider></target></targets><rules><logger name=”*” minlevel=”Debug” writeTo=”database” /><logger name=”*” minlevel=”Trace” writeTo=”logfile” /></rules></nlog></configuration>
Step 5: Creating an exception on the controller side
using NLog;using System;using System.Collections.Generic;using System.Linq;using System.Text.RegularExpressions;using System.Web;using System.Web.Mvc;namespace LoggingExample.Controllers{public class HomeController : Controller{private static Logger logger = LogManager.GetCurrentClassLogger();public ActionResult Index(){try{string studentName = “Vaibhav123”;ValidateStudent(studentName);return View();}catch (Exception ex){throw ex;}}private static void ValidateStudent(string studentName){Regex regex = new Regex(“^[a-zA-Z]+$”);if (!regex.IsMatch(studentName))throw new Exception(studentName);}}}
Step 6: Log the exception using Application_Error
Since ASP.NET MVC sits on top of the ASP.NET Runtime, it means that an MVC application can use ASP.NET’s Application_Error event. In this case, an unhandled exception by MVC can be handled by the Application_Error event of ASP.NET.
Add Application_Error in Global.asax as below,
private static readonly Logger logger = LogManager.GetCurrentClassLogger();protected void Application_Error(){var ex = Server.GetLastError();logger.Info(ex.Message.ToString() + Environment.NewLine + DateTime.Now);HttpContext.Current.ClearError();Response.Redirect(“~/Error/Index”, false);}
Result:
After execution of project logs will be stored in the database table as well as in files as shown below,
Thank You, See you in the next article !!
You can reach out to me here,
LinkedIn: https://www.linkedin.com/in/vaibhav-bhapkar
Email: vaibhavbhapkar.medium@gmail.com