Walkthrough: Customizing Logging

When adding logging to your codebase, you may need to set up logging options differently for different areas or layers in your application. For example, exceptions in the service that cleans up old data in the database can be logged with a "Warning" level, while exceptions in the customer-facing web service must be logged with the "Error" level.

PostSharp enables you to organize your logging options using Logging Profiles. Logging profiles are stored in the solution-wide configuration file, and each profile specifies what information you want to be included in the log output. You apply a given logging profile by providing its name as an argument for the LogAttribute attribute's constructor. Let's take a look at how you can create your own logging profile and use it in your code.

Note Note

This procedure requires PostSharp Tools for Visual Studio to be installed on your machine. You can however achieve the same results by editing the code and the project manually.

To create a custom logging profile:

  1. Let's add customized logging to our Save method.

    public void Save(string firstName, string lastName, string streetAddress, string city) 
        var customerRepository = new CustomerRepository(); 
        customerRepository.Save(firstName, lastName, streetAddress, city); 
  2. Put the caret on the Save method name and expand the Smart Tag. From the list select "Add logging".

    Detailed Tracing 1
  3. The first page of the wizard is the logging profile selection dialogue. In this dialogue you can select one of the predefined profiles, edit an existing profile or create a new one. For this example click on the "New logging profile..." link to create a new logging profile.

    Logging Profiles 1
  4. Provide a name for your newly created logging profile in the opened profile customization dialogue.

    Logging Profiles 2
  5. Choose when to write a new message to the log. You can select from one of these options: when entering and exiting the method, only when entering the method, only when exception is thrown inside the method.

  6. Choose what information to include in each log message. The available options are: parameter values, names, and types, and return value of the method.

  7. Finally, select the logging level to use for the exception log messages.

  8. When you're done with customizing your new logging profile, click Save button.

    Logging Profiles 3
  9. Back in the profile selection dialogue select your profile and click Next.

    Logging Profiles 4
  10. The next page of the wizard gives you the opportunity to choose the logging back-end that you want to use. For this example select "System.Diagnostics.Trace" and click Next.

    Detailed Tracing 3
  11. The summary page gives you the opportunity to review the selections that you have made. If you notice that the configuration is not what you wanted you can click the Previous button and adjust your selections. If the configuration meets your needs click Next.

    Logging Profiles 5
  12. The progress page shows a progress bar and summary of what actions PostSharp is taking to add the selected logging configuration to your codebase. It's at this point that PostSharp and the logging pattern library will be downloaded from NuGet and added as references to your codebase.

    Detailed Tracing 5
  13. Once the download, installation and configuration of PostSharp and the logging pattern library has finished you can close the wizard and look at the changes that were made to your codebase.

    Detailed Tracing 6
  14. First of all, the code window with SolutionName.pssln file will be shown. This file stores all your custom logging profiles and other solution-level information.

    <?xml version="1.0" encoding="utf-8"?>
    <Project xmlns="http://schemas.postsharp.org/1.0/configuration" xmlns:d="clr-namespace:PostSharp.Patterns.Diagnostics;assembly:PostSharp.Patterns.Diagnostics" xmlns:p="http://schemas.postsharp.org/1.0/configuration">
      <Property Name="LoggingEnabled" Value="{has-plugin('PostSharp.Patterns.Diagnostics')}" Deferred="true" />
      <d:LoggingProfiles p:Condition="{$LoggingEnabled}">
        <d:LoggingProfile Name="New profile" OnEntryOptions="IncludeParameterValue | IncludeReturnValue | IncludeThisArgument" OnExceptionLevel="None" OnSuccessLevel="None" />
  15. You'll also notice that the code you added the logging to has changed slightly. PostSharp has added a LogAttribute attribute to the method and the attribute has the name of your logging profile specified as an argument.

    [Log( "New profile" )]
    public void Save(string firstName, string lastName, string streetAddress, string city) 
        var customerRepository = new CustomerRepository(); 
        customerRepository.Save(firstName, lastName, streetAddress, city); 
    Note Note

    This example has added a single attribute to one method. If you plan on adding this logging to many different locations in your codebase you will want to read about using the MulticastAttribute: Adding Aspects to Multiple Declarations.

  16. If you were to run this method the trace logging that you added would output a log message according to the options you've specified in your logging profile.

    Detailed Tracing 7

Now that you have logging added to the Save method you are able to change the method's name as well as add and remove parameters with the confidence that your log entries will be kept in sync with each of those changes. In combination with attribute multicasting (the article Adding Aspects to Multiple Declarations), adding logging to your codebase and maintaining it becomes a very easy task.

See Also