PostSharp 5.0 Logging

Installing

  1. Add package PostSharp.Patterns.Diagnostics to any project that requires logging.
  2. Add the [Log] attribute to methods using Multicast, XML or IAspectProvider. See http://doc.postsharp.net/applying-aspects for details.
  3. Add the back-end package to your start-up project:
    • PostSharp.Patterns.Diagnostics.Backends.ApplicationInsights
    • PostSharp.Patterns.Diagnostics.Backends.AspNetLogging
    • PostSharp.Patterns.Diagnostics.Backends.CommonLogging
    • PostSharp.Patterns.Diagnostics.Backends.Console
    • PostSharp.Patterns.Diagnostics.Backends.EnterpriseLibrary
    • PostSharp.Patterns.Diagnostics.Backends.EventSource
    • PostSharp.Patterns.Diagnostics.Backends.Log4Net
    • PostSharp.Patterns.Diagnostics.Backends.NLog
    • PostSharp.Patterns.Diagnostics.Backends.Serilog
    • PostSharp.Patterns.Diagnostics.Backends.Trace
    • PostSharp.Patterns.Diagnostics.Backends.TraceSource
    • PostSharp.Patterns.Diagnostics.Backends.XamarinInsights
  4. Inside your application initialization (e.g. Program.Main in a console app), assign the PostSharp.Patterns.Diagnostics.LoggingServices.BackEnd
    property to an instance of the back-end class. Use IntelliSense to figure out the name of the logging back-end class. The name of this class ends with LoggingBackend.

Configuration Object Model

Example postsharp.config

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.postsharp.org/1.0/configuration">

  <LoggingProfiles xmlns="clr-namespace:PostSharp.Patterns.Diagnostics;assembly:PostSharp.Patterns.Diagnostics">
 
    <LoggingProfile Name="IncludeParameterTypeOnly" IncludeExceptionDetails="True">
      <DefaultOptions>
        <LoggingOptions  IncludeThisValue="False" IncludeParameterType="True" IncludeParameterName="False" IncludeParameterValue="False" IncludeDeclaringTypeName="False"/>
      </DefaultOptions>
      <ExceptionOptions>
        <LoggingOptions IncludeThisValue="False" IncludeParameterType="True" IncludeParameterName="False" IncludeParameterValue="False" IncludeDeclaringTypeName="False"/>
      </ExceptionOptions>
    </LoggingProfile>

  </LoggingProfiles>
</Project>

The following sections document the object configuration object model. The XML maps directly to C#.

LoggingProfile

    /// <summary>
    /// Logging profiles are named configurations of logging aspects. They are typically instantiated in the PostSharp XML project file.
    /// </summary>
    /// <remarks>
    /// <para>
    /// Logging profiles are defined in the PostSharp XML project file,
    /// in the section <c>LoggingProfiles</c> of XML namespace <c>clr-namespace:PostSharp.Patterns.Diagnostics;assembly:PostSharp.Patterns.Diagnostics</c>.
    /// Logging profiles can then be referred to from the <see cref="LogAttribute"/>. There are two system-defined logging profiles: <c>Default</c>
    /// and <c>Exceptions</c></para>
    /// </remarks>
    [PSerializable]
    public class LoggingProfile
    {

        public LoggingProfile()
        {
            // Create a default logging profile.
            this.DefaultOptions = new LoggingOptions();
            this.ExceptionOptions = new LoggingOptions {Level = LogLevel.Warning};
            this.IncludeAwaitedTask = true;
        }

        /// <summary>
        /// Gets or sets options for logging before method execution.
        /// </summary>
        public LoggingOptions DefaultOptions { get; set; }

        /// <summary>
        /// Gets or sets options for logging on method exception.
        /// </summary>
        public LoggingOptions ExceptionOptions { get; set; }

        /// <summary>
        /// Includes details about a logged exception (message, stack trace).
        /// </summary>
        /// <remarks>Some back-ends may ignore this setting and always include exception details.</remarks>
        public bool IncludeExceptionDetails { get; set; }

        /// <summary>
        /// Gets or sets the warning threshold, in milliseconds.
        /// If the execution of a method takes longer than that, its success is logged with <see cref="LogLevel.Warning"/>,
        /// and the time it took is logged.
        /// If the value is 0, this feature is disabled.
        /// </summary>
        public int ExecutionTimeThreshold { get; set; }

        /// <summary>
        /// Indicates that the execution time of a method should be tracked and logged on exit.
        /// </summary>
        public bool IncludeExecutionTime { get; set; }


        public bool IncludeAwaitedTask { get; set; }

        /// <summary>
        /// Indicates that the <see cref="LoggingCategory.IsEnabled"/> is constant, so it could be cached.
        /// </summary>
        /// <summary>
        /// Enabling this property allows the JIT compiler to completely remove logging instructions for categories that are
        /// not enabled. However, the caching back-end must be set before the first logged method is executed.
        /// </summary>
        public bool UseInitOnlyCategories { get; set; }

    }

LoggingOptions

    [PSerializable]
    public class LoggingOptions
    {

        public LoggingOptions()
        {
            this.IncludeParameterValue = true;
            this.IncludeReturnValue = true;
            this.IncludeDeclaringTypeName = true;
            this.Level = LogLevel.Debug;
        }

        public LogLevel Level { get; set; }

        /// <summary>
        /// Includes parameter type information.
        /// </summary>
        public bool IncludeParameterType { get; set; }

        public bool IncludeGenericParameters { get; set; }

        /// <summary>
        /// Includes parameter name.
        /// </summary>
        public bool IncludeParameterName { get; set; }

        /// <summary>
        /// Includes parameter value, by calling <see cref="object.ToString"/> on the object instance.
        /// </summary>
        public bool IncludeParameterValue { get; set; }

        /// <summary>
        /// Includes the return value.
        /// </summary>
        public bool IncludeReturnValue { get; set; }

        /// <summary>
        /// Includes the value of <c>this</c> argument in an instance method.
        /// </summary>
        public bool IncludeThisValue { get; set; }

        /// <summary>
        /// Includes the declaring type of the method from method name.
        /// </summary>
        public bool IncludeDeclaringTypeName { get; set; }


    }

LogLevel

    /// <summary>
    /// Specifies the severity of a logged message.
    /// </summary>
    public enum LogLevel
    {
        /// <summary>
        /// No message should be logged.
        /// </summary>
        /// <remarks>The value is <c>0</c>.</remarks>
        None = 0,

        /// <summary>
        /// The message should be logged at Trace level (when applicable).
        /// </summary>
        Trace,

        /// <summary>
        /// The message should be logged at Debug level (when applicable).
        /// </summary>
        Debug,

        /// <summary>
        /// The message should be logged at Info level (when applicable).
        /// </summary>
        Info,

        /// <summary>
        /// The message should be logged at Warning level (when applicable).
        /// </summary>
        Warning,

        /// <summary>
        /// The message should be logged at Error level (when applicable).
        /// </summary>
        Error,

        /// <summary>
        /// The message should be logged at Fatal level (when applicable).
        /// </summary>
        Fatal
    }

Customization

Custom Formatters

  1. Derive a class from PostSharp.Patterns.Formatters.Formatter<T>.
  2. Register it using PostSharp.Patterns.Diagnostics.LoggingServices.RegisterFormatter.

Custom Backends

  1. Derive a class from PostSharp.Patterns.Diagnostics.LoggingBackend. You can also derive from an available back-end, for instance Log4NetLoggingBackend.
  2. Derive a class from PostSharp.Patterns.Diagnostics.LogRecordBuilder and override the relevant methods.
  3. Override the CreateRecordBuilder method in your custom LoggingBackend class.
  4. Register your custom LoggingBackend class by setting the PostSharp.Patterns.Diagnostics.LoggingServices.BackEnd property.