A Serilog settings provider that reads from Microsoft.Extensions.Configuration, .NET Core's appsettings.json
file.
Configuration is read from the Serilog
section.
{
"Serilog": {
"Using": ["Serilog.Sinks.Literate"],
"MinimumLevel": "Debug",
"WriteTo": [
{ "Name": "LiterateConsole" },
{ "Name": "File", "Args": { "path": "%TEMP%\\Logs\\serilog-configuration-sample.txt" } }
],
"Enrich": ["FromLogContext", "WithMachineName", "WithThreadId"],
"Properties": {
"Application": "Sample"
}
}
}
This example relies on the Serilog.Sinks.Literate, Serilog.Sinks.File, Serilog.Enrichers.Environment and Serilog.Enrichers.Thread packages also being installed.
After installing this package, use ReadFrom.Configuration()
and pass an IConfiguration
object.
public class Program
{
public static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
logger.Information("Hello, world!");
}
}
The WriteTo
and Enrich
sections support the same syntax, for example the following is valid if no arguments are needed by the sinks:
"WriteTo": ["LiterateConsole", "DiagnosticTrace"]
Or alternatively, the long-form ("Name":
...) sytax from the first example can be used when arguments need to be supplied.
(This package implements a convention using DependencyContext
to find any package with Serilog
anywhere in the name and pulls configuration methods from it, so the Using
example above is redundant.)
To use this package in .NET 4.x applications, add preserveCompilationContext
to buildOptions
in project.json.
"net4.6": {
"buildOptions": {
"preserveCompilationContext": true
}
},
The MinimumLevel
configuration property can be set to a single value as in the sample above, or, levels can be overridden per logging source.
This is useful in ASP.NET Core applications, which will often specify minimum level as:
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
}
If your application enables the environment variable configuration source (AddEnvironmentVariables()
) you can add or override Serilog configuration through the environment.
For example, to set the minimum log level using the Windows command prompt:
set Serilog:MinimumLevel=Debug
dotnet run