Logging in .NET with AOP using PostSharp

Here is a simple application that logs to console. Logging is programmed with Aspect Oriented Programming paradigm as an aspect using PostSharp. As a logger library I use log4net.


Sample solution can be downloaded from here https://github.com/mchudinov/LoggingPostSharp. It is compatible with Visual Studio 2012, MonoDevelop 5, and Xamarin Studio 5.

1. Add PostSharp to the solution
The easiest way to add PostSharp to a solution is to do it in Visual Studio. Another way is to add the PostSharp NuGet package and configure project file manually.

Open solution context menu (right click mouse button) and use [Add PostSharp to project].


This will add all the necessary packages and references to the project and enable new building targets for PostSharp.

Here are the changes PostSharp makes in the solution.

  • PostSharp package is added to packages.config

  • Reference to PostSharp library is added to the solution file

  • And new build targets are added at the end of the project file.

Here is the whole csproj file from my simple console application with PostSharp

All these changes can be made manually without PostSharp Extension.

2. Ceate Log aspect and use it
I use OnMethodBoundaryAspect class that controls any other method execution on boundaries: entry to the method, success exit and exception. This is called advices in the aspect oriented programming terminology.

Here is my simple class-aspect that logs data on entry, exit and exception. Method DisplayObjectInfo prints arguments to any other method that uses Log aspect.

OnException advice puts the whole adviced method into try-catch block.
Note this line
args.FlowBehavior = FlowBehavior.Continue;
in OnException advice. This will continue execution after the exception is caught OUT of method boundary. If you need that execution continues right after the exception is thrown then try-catch block must be written explicitly (not by the aspect).

Using this aspect is trivial:

3. Add log4net as it is described in this post Logging in .NET Mono on Linux and Windows

4. Compile and run application
Note that “After” is written to the log. It means that execution continues after the exception is thrown and without explicit try-catch block. It means that
args.FlowBehavior = FlowBehavior.Continue; option works.


5. Mono on Linux
Applications that uses PostSharp version 4 can not be build on Linux with Mono version 3 (.NET 4.5). Compiler complains about absence of Microsoft.Common.CurrentVersion.targets file. But Mono application that was compiled on Windows runs on Linux just fine!
Here is console output from the same application on my lovely Mint 17 running Mono 3.2.8


  • Marcello

    Logging this way can fail if you forget the attribute while writing the method signature. Log through command decorator logs ‘by-design’. My two cents.