Serilog
- Serilog provides diagnostic logging to files, the console, and elsewhere.
- It is easy to set up, has a clean API, and is portable between recent .NET platforms.
- Serilog is built with powerful structured event data in mind.
- Structured logging is a modern approach where logging events are treated as structured data rather than text
Popular Logging Library
Console Sample
- Create console Project
- Add packages
Serilog
Serilog.Sinks.Console
Serilog.Sinks.File
- Add the following code in the start of
program.cs
Log.Logger = new LoggerConfiguration().WriteTo.Console().CreateLogger();
- Messages are logged to console
ASP.NET Sample
- Create new asp.net core project
- Install package
Install-Package Serilog.AspNetCore
- Add the following code in the start of
program.cs
Log.Logger = new LoggerConfiguration().WriteTo.Console().CreateLogger();
- Messages are logged to console
Default Logger
- Configure serilog as the default logger
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog((ctx, lc) => lc.WriteTo.Console());
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(new JsonFormatter())
.CreateLogger();
Logging to File
Install-Package Serilog.Sinks.File
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(new JsonFormatter())
.WriteTo.File("log.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
Logging to Db
Install-Package Serilog.Sinks.MSSqlServer
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(new JsonFormatter())
.WriteTo.File(new JsonFormatter(), "log.txt")
.WriteTo.MSSqlServer("Data Source=localhost;Initial Catalog=Sample;Integrated Security=SSPI",
new MSSqlServerSinkOptions
{
TableName = "Logs",
SchemaName = "dbo",
AutoCreateSqlTable = true
})
.CreateLogger();
Logging Levels
- Levels from priority low to high
- Verbose
- Debug
- Info
- Warning
- Error
Log.Logger = new LoggerConfiguration().MinimumLevel.Warning().WriteTo.Console().CreateLogger();
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(new JsonFormatter())
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
.CreateLogger();
app.UseSerilogRequestLogging();
References: