Logging

Component: NServiceBus
Nuget Package: NServiceBus (Version: 5.x)

Default Logging

NServiceBus has some limited, and opinionated, logging built in.

The default logging behavior is as follows:

This is applicable to both self hosting and using the NServiceBus Host

Console

All Info (and above) messages will be piped to the current console.

Errors will be written with ConsoleColor.Red. Warnings will be written with ConsoleColor.DarkYellow. All other message will be written with ConsoleColor.White.

Trace

All Warn (and above) messages will be written to Trace.WriteLine.

Rolling File

All Info (and above) messages will be written to a rolling log file.

This file will keep 10MB per file and a maximum of 10 log files.

The default logging directory will be HttpContext.Current.Server.MapPath("~/App_Data/") for websites and AppDomain.CurrentDomain.BaseDirectory for all other processes.

The default file name will be nsb_log_yyyy-MM-dd_N.txt, where N is a sequence number for when the log file reaches the max size.

Changing the defaults

With code both the Level and the logging directory can be configured. To do this, use the LogManager class.

var defaultFactory = LogManager.Use<DefaultFactory>();
defaultFactory.Directory("pathToLoggingDirectory");
defaultFactory.Level(LogLevel.Debug);

Logging Levels

The Logging level, or "Threshold", indicates the log levels that will be outputted. So for example a value of Warn would mean all Warn, Error and Fatal message would be outputted.

The supported logging levels are

  • Debug
  • Info
  • Warn
  • Error
  • Fatal

Changing the Logging Level

When logging level is defined in both app.config and code the code wins.

Via config API

var defaultFactory = LogManager.Use<DefaultFactory>();
defaultFactory.Level(LogLevel.Debug);

Via app.config

<configSections>
  <section name="Logging" 
           type="NServiceBus.Config.Logging, NServiceBus.Core" />
</configSections>
<Logging Threshold="Debug" />

Via IProvideConfiguration

public class ProvideConfiguration :
    IProvideConfiguration<Logging>
{
    public Logging GetConfiguration()
    {
        return new Logging
        {
            Threshold = "Info"
        };
    }
}

Custom Logging

For more advanced logging, it is recommended to utilize one of the many mature logging libraries available for .Net.

Moving to custom logging means none of the approaches used in the above Default Logging apply.

When to configure logging

It is important to configure logging before any endpoint configuration is done since logging is configured in the static context of each NServiceBus class. So it should be configured at the startup of the app. For example

  • At the start of the Main of a console app or windows service.
  • At the start of the constructor of the class that implements IConfigureThisEndpoint when using NServiceBus.Host.
  • At the start of the Global.Application_Start in a asp.net application.

Samples

Related Articles


Last modified