Tuesday, July 21, 2020

PostSharp Logging

Yet another pattern we manually (and badly) code is logging. Everyone wants to do it differently. It shouldn't be like that. PostSharp makes consistent logging a breeze. I'm going to add console logging to the program I wrote for my last blog post.

There are several ways to do this. I like the idea of setting up logging at the solution level in the postsharp.config file. Add this under the <Project> node.


  <Multicast>
    <When Condition="{has-plugin('PostSharp.Patterns.Diagnostics')}">
      <LogAttribute xmlns="clr-namespace:PostSharp.Patterns.Diagnostics;assembly:PostSharp.Patterns.Diagnostics" />
    </When>
  </Multicast>


Use NuGet to install PostSharp.Patterns.Diagnostics into your project.

Now find your startup class. For a console project, this is Main in Program.cs by default. Add a reference to PostSharp.Patterns.Diagnostics and instantiate the logging backend. For console logging this is

LoggingServices.DefaultBackend = new PostSharp.Patterns.Diagnostics.Backends.Console.ConsoleLoggingBackend();

So Main looks more like this...

        static void Main(string[] args)
        {
            LoggingServices.DefaultBackend = new PostSharp.Patterns.Diagnostics.Backends.Console.ConsoleLoggingBackend();

            Document document = new Document() { ID = 1, Number = "A23" };
.
.
.
        }


Refer to the excellent PostSharp documentation for the packages and syntax required for other logging backends.

Now run the project and look at the output. Pretty sweet, eh? Of course, it's highly customizable.



You can adjust the verbosity at any time. For example, if I want to stop seeing information messages once the Document has been instantiated I could insert this line after the Document is instantiated.

Document document = new Document() { ID = 1, Number = "A23" };
LoggingServices.DefaultBackend.CurrentContextLocalConfiguration.Verbosity.SetMinimalLevel(LogLevel.Warning);





No comments:

Post a Comment