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 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.   
  6. namespace Shopping.WebApp  
  7. {  
  8.     [Serializable]  
  9.     public class NlogTraceAttribute: OnMethodBoundaryAspect  
  10.     {  
  11.         public static Logger Logger = LogManager.GetCurrentClassLogger();  
  12.   
  13.         /// <summary>  
  14.         /// On Method Entry  
  15.         /// </summary>  
  16.         /// <param name="args"></param>  
  17.         public override void OnEntry(MethodExecutionArgs args)  
  18.         {  
  19.             Logger.Info($"OnEntry : {(args.Method != null ? args.Method.Name : "")}");  
  20.               
  21.             string className,methodName,arguments;  
  22.             if (args.Method != null)  
  23.                 if (args.Method.DeclaringType != null)  
  24.                     className = $"{args.Method.DeclaringType.Namespace}.{args.Method.DeclaringType.Name}";  
  25.             if (args.Method != null) methodName = args.Method.Name;  
  26.             arguments== args.Arguments;  
  27.   
  28.             Logger.Info($"className: {className}; methodName:{methodName};arguments:{arguments}");  
  29.         }  
  30.   
  31.         /// <summary>  
  32.         /// On Method success  
  33.         /// </summary>  
  34.         /// <param name="args"></param>  
  35.         public override void OnSuccess(MethodExecutionArgs args)  
  36.         {  
  37.             Logger.Info($"OnSuccess : {(args.Method != null ? args.Method.Name : "")}");  
  38.             var returnValue = args.ReturnValue;  
  39.             Logger.Info($"ReturnValue : {returnValue}");              
  40.         }  
  41.   
  42.   
  43.         /// <summary>  
  44.         /// On Method Exception  
  45.         /// </summary>  
  46.         /// <param name="args"></param>  
  47.         public override void OnException(MethodExecutionArgs args)  
  48.         {  
  49.             if (args.Exception != null)  
  50.                 Logger.Info($"OnException : {(!string.IsNullOrEmpty(args.Exception.Message) ? args.Exception.Message : "")}");  
  51.   
  52.   
  53.             var Message = args.Exception.Message;  
  54.             var StackTrace = args.Exception.StackTrace;  
  55.               
  56.             Logger.Info($"Application has got exception in method-{args.Method.Name} and message is {Message}");      
  57.   
  58.     // or you can send email notification         
  59.         }  
  60.   
  61.         /// <summary>  
  62.         /// On Method Exit  
  63.         /// </summary>  
  64.         /// <param name="args"></param>  
  65.         public override void OnExit(MethodExecutionArgs args)  
  66.         {             
  67.         }  
  68.             }   

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. {  
  3.     public bool RegisterCustomer(string email, string password, string gender,string dateofbirth)  
  4.     {  
  5.   
  6.     }  
  7.   
  8.     public void IsExistingCustomer(string email)  
  9.     {  
  10.   
  11.     }  
  12. }   

Yes, it’s a one-minute job. I just need to add NlogTrace attribute to all the methods. Please look at the class given below. 

  1. public class Registration  
  2. {  
  3.     [NlogTrace]  
  4.     public bool RegisterCustomer(string email, string password, string gender,string dateofbirth)  
  5.     {  
  6.   
  7.     }  
  8.   
  9.     [NlogTrace]  
  10.     public void IsExistingCustomer(string email)  
  11.     {  
  12.   
  13.     }  
  14. }   

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]

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now