-
Notifications
You must be signed in to change notification settings - Fork 863
Getting Started
The core logging package for all platforms is Serilog. Sinks (output destinations) are packaged separately.
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.
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.
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
dotnet new console -n SerilogDemo
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.File3. Add the following code to Program.cs
using System;
using Serilog;
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
dotnet run
