The article explains how to use PostSharp to do logging in existing code.
The article explains how to use PostSharp for doing logging in the existing code.
Using the code
Suppose in your C# .NET application you have a requirement that you want to log the Entry and Exit of every method. One of the ways to do this is by writing log statements at every start and end of the method but that will be a performance nightmare.
Here comes the magic of AOP!
AOP is something that increases the modularity by allowing separation of concern which in this case is Logging.Now you could read about Aspect Oriented Programming over the net but that is not the topic of today.
There are a number of frameworks that are based on AOP like Castle, Encase, Spring .NET amd one of them is PostSharp.
Today we will see how to do Entry/Exit level logging at every method using PostSharp.
You could download free edition of PostSharp from here
Now add a reference of PostSharp.dll to your C# project. Create a attribute something like below
Suppose you have a method Test and you want to log the Entry/Exit of this method.You can decorate the method with the attribute [Logging] as below and it would automatically print the messages on Console.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
[MulticastAttributeUsage(MulticastTargets.Method, AllowMultiple = true)]
public class LoggingAttribute : OnMethodBoundaryAspect
public override void OnEntry(MethodExecutionArgs args)
Console.WriteLine("On Method Enter");
public override void OnExit(MethodExecutionArgs args)
Console.WriteLine("On Method Exit");
[Logging]You could also use OnException method in case of Unhandled Exception in the method.
public void Test()