- Notifications
You must be signed in to change notification settings - Fork844
Getting Started
The core logging package isSerilog. 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.ConsoleBrowse theSerilog tag on NuGet to see the available sinks, extensions and related third-party packages.
Types are in the Serilog namespace.
usingSerilog;
The rootLogger is created usingLoggerConfiguration.
usingvarlog=newLoggerConfiguration().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 viaLog.Logger and can be invoked using the static methods on theLog class.
Log.Logger=log;Log.Information("The global logger has been configured");
Configuring and using theLog 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 usingLogger/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
2. Install the core Serilog package,Console sink andFile 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 toProgram.cs
usingSystem;usingSerilog;classProgram{staticasyncTaskMain(){Log.Logger=newLoggerConfiguration().MinimumLevel.Debug().WriteTo.Console().WriteTo.File("logs/myapp.txt",rollingInterval:RollingInterval.Day).CreateLogger();Log.Information("Hello, world!");inta=10,b=0;try{Log.Debug("Dividing {A} by {B}",a,b);Console.WriteLine(a/b);}catch(Exceptionex){Log.Error(ex,"Something went wrong");}finally{awaitLog.CloseAndFlushAsync();}}}
4. Run the program
