Skip to content

Getting Started

Ruben Bartelink edited this page Oct 21, 2023 · 21 revisions

Installing from NuGet

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

$ dotnet add package Serilog
$ dotnet add package Serilog.Sinks.Console

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;

The root Logger is created using LoggerConfiguration.

using var log = new LoggerConfiguration()
    .WriteTo.Console()
    .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 Logger/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, Console sink and File sink

At a shell prompt in the project directory, type:

$ dotnet add package Serilog
$ dotnet add package Serilog.Sinks.Console
$ dotnet add package Serilog.Sinks.File

3. Add the following code to Program.cs

using System;
using Serilog;

class Program
{
    static async Task Main()
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .WriteTo.Console()
            .WriteTo.File("logs/myapp.txt", rollingInterval: RollingInterval.Day)
            .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");
        }
        finally
        {
            await Log.CloseAndFlushAsync();
        }
    }
}

4. Run the program

Serilog Getting Started Example

Clone this wiki locally
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy