Getting Started

Nicholas Blumhardt edited this page Jul 8, 2016 · 12 revisions

Installing from NuGet

The core logging package is Serilog. The supported platforms are .NET 4.5, Windows 8 (WinRT) and Windows Phone 8.

PM> Install-Package Serilog

Browse the Serilog tag on NuGet to see the available sinks, extensions and related third-party packages.

Setup

Types are in the Serilog namespace.

using Serilog;

An ILogger is created using LoggerConfiguration.

var log = new LoggerConfiguration()
    .WriteTo.ColoredConsole()
    .CreateLogger();

This is typically done once at application start-up, and the logger saved for later use by application classes. Multiple loggers can be created and used independently if required.

log.Information("Hello, Serilog!");

Serilog's global, statically accessible logger, is set via Log.Logger and can be invoked using the static methods on the Log class.

Log.Logger = log;
Log.Information("The global logger has been configured");

Configuring and using the Log class is an optional convenience that makes it easier for libraries to adopt Serilog. Serilog does not require any static/process-wide state within the logging pipeline itself, so using ILogger directly is fine.

Example application

The complete example below shows logging in a simple console application, with events sent to the console as well as a date-stamped rolling log file.

1. Create a new Console Application project

2. Install the core Serilog package and the literate console sink

In Visual Studio, open the Package Manager Console and type:

Install-Package Serilog
Install-Package Serilog.Sinks.Literate
Install-Package Serilog.Sinks.RollingFile

3. Add the following code to Program.cs

using System;
using Serilog;

namespace SerilogExample
{
    class Program
    {
        static void Main()
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.LiterateConsole()
                .WriteTo.RollingFile("logs\\myapp-{Date}.txt")
                .CreateLogger();

            Log.Information("Hello, world!");

            int a = 10, b = 0;
            try
            {
                Log.Debug("Dividing {A} by {B}", a, b);
                Console.WriteLine(a / b);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Something went wrong");
            }

            Log.CloseAndFlush();
            Console.ReadKey();
        }
    }
}

4. Run the program

Serilog Getting Started Example