Logging And Tracing With Post Sharp

Introduction

In every project, we use logging concept to handle the exceptions and trace the applications and their flow. This is why, logging and tracing play a very crucial role in application development.

Basically, Logging and Tracing can be implemented in the following ways.

  • We can store it into Database
  • We can store it into file system
  • We can store it into Event viewer
  • We can store it in other ways also.

Problem

Let's suppose we have web application which contains n number of pages, and on each page, we have so many methods. Now, we got a requirement to impement logging and we started implementing logging class to store all the exceptions into database. In order to log the exceptions in our application, we have to call those implemented logging class method on all methods of our application. 

Old Solution

To log the exceptions in our application, we need to do following things in every class of our web application.

  • Create instance for logging class.
  • Call logging method to store the exception.
  • Pass exception instance to log the exact exception details like Message, Stack Trace etc.
  • Wrap a try/catch around each method that requires logging and then add the logging code to the catch block.

So, this is time consuming process and also, we need to test all those methods.

New Solution

To overcome all those above problems, we have to apply Post Sharp concept to logging.

  • Add comprehensive logging to your app without impact on source code.
  • It’s very easy. You'll be done in minutes and Remove as quickly.
  • Multi-Framework Support. Continue to use your favorite framework: log4net, NLog, Enterprise Library, Diagnostics.Trace, Console
  • High Performance

Benefits of using logging with Post Sharp

  • Reduce development cost and time;
  • Build more scalable software;
  • Add functionality more easily after first release;
  • Help new members contribute quicker.
  • It's works on Aspect Oriented Programming(AOP) concept.So it’s simple to implement and remove.

Installation

Step 1

Install Post Sharp (Post Sharp Express is free for logging) Tool for Visual Studio.(https://www.postsharp.net/download)

Step 2

Add Post Sharp to your project from NuGet package. Here, we can select which framework to use log4net, NLog, Enterprise Library, Diagnostics.Trace, Console.

Here, I am installing post sharp with Nlog.

 

Till now, it’s good; right? We have installed Post Sharp tool for Visual Studio and added NuGet packages to our project. Let’s go for implementation now.

Implementation

Here, we add a new class (TraceAttribute.cs) to the below web application. 

  1. using Newtonsoft.Json;  
  2. using NLog;  
  3. using NLog.Targets;  
  4. using PostSharp.Aspects;  
  5. namespace Shopping.WebApp {  
  6.         [Serializable]  
  7.         public class NlogTraceAttribute: OnMethodBoundaryAspect {  
  8.             public static Logger Logger = LogManager.GetCurrentClassLogger();  
  9.             /// <summary>  
  10.             /// On Method Entry  
  11.             /// </summary>  
  12.             /// <param name="args"></param>  
  13.             public override void OnEntry(MethodExecutionArgs args) {  
  14.                 Logger.Info($ "OnEntry : {(args.Method != null ? args.Method.Name : "  
  15.                     ")}");  
  16.                 string className, methodName, arguments;  
  17.                 if (args.Method != null)  
  18.                     if (args.Method.DeclaringType != null) className = $ "{args.Method.DeclaringType.Namespace}.{args.Method.DeclaringType.Name}";  
  19.                 if (args.Method != null) methodName = args.Method.Name;  
  20.                 arguments == args.Arguments;  
  21.                 Logger.Info($ "className: {className}; methodName:{methodName};arguments:{arguments}");  
  22.             }  
  23.             /// <summary>  
  24.             /// On Method success  
  25.             /// </summary>  
  26.             /// <param name="args"></param>  
  27.             public override void OnSuccess(MethodExecutionArgs args) {  
  28.                 Logger.Info($ "OnSuccess : {(args.Method != null ? args.Method.Name : "  
  29.                     ")}");  
  30.                 var returnValue = args.ReturnValue;  
  31.                 Logger.Info($ "ReturnValue : {returnValue}");  
  32.             }  
  33.             /// <summary>  
  34.             /// On Method Exception  
  35.             /// </summary>  
  36.             /// <param name="args"></param>  
  37.             public override void OnException(MethodExecutionArgs args) {  
  38.                 if (args.Exception != null) Logger.Info($ "OnException : {(!string.IsNullOrEmpty(args.Exception.Message) ? args.Exception.Message : "  
  39.                     ")}");  
  40.                 var Message = args.Exception.Message;  
  41.                 var StackTrace = args.Exception.StackTrace;  
  42.                 Logger.Info($ "Application has got exception in method-{args.Method.Name} and message is {Message}");  
  43.                 // or you can send email notification  
  44.             }  
  45.             /// <summary>  
  46.             /// On Method Exit  
  47.             /// </summary>  
  48.             /// <param name="args"></param>  
  49.             public override void OnExit(MethodExecutionArgs args) {}  
  50.         }   

The OnMethodBoundaryAspect aspect results in the target method to be wrapped into a try ... catch ... finally block.

You can implement four advices,

  • OnEntry(MethodExecutionArgs): executed at the beginning of the block;
  • OnSuccess(MethodExecutionArgs): executed only when the method is successful (i.e. does not result in an exception);
  • OnException(MethodExecutionArgs): invoked when the method results in an exception;
  • OnExit(MethodExecutionArgs): always executed after method execution (whether the method resulted in an exception or not).

Parameters

args

Type: PostSharp.Aspects.MethodExecutionArgs

Event arguments specifying which method is being executed and what are its arguments.

That’s it.. Here we use, Nlog to capture all logging and Tracing into file system. You can customize in trace class to do logging and tracing based on our requirements.

How to use

It’s very simple to use/integrate “NlogTraceAttribute” class into methods of project.

Now, I have to log and trace "my Registration" class which has two methods. 

  1. public class Registration {  
  2.     public bool RegisterCustomer(string email, string password, string gender) {}  
  3.     public void IsExistingCustomer(string email) {}  
  4. }  
  5. Yes!!It’ s 1 minute job.I just need to add NlogTrace attribute to all methods.Please look at below class  
  6. public class Registration {  
  7.     [NlogTrace]  
  8.     public bool RegisterCustomer(string email, string password, string gender) {}  
  9.         [NlogTrace]  
  10.     public void IsExistingCustomer(string email) {}  
  11. }   

It’s simple and takes only a litte bit of time and efforts to add and remove trace with source code changes. Even new developers also find it easy to implement for their code.

If we want to enable NlogTrace attribute for all methods on solution in single shot, we can use it as below.

[assembly: NlogTraceAttribute]

Ebook Download
View all
test-2
Read by 1 people
Download Now!
Learn
View all