Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Minimum Level of Logging in SeriLog using appsettings.json

Tags:

c#

serilog

Is there a way to do this? I would like to change the minimum level of logging by reading the setting off the appsettings.json

My code looks like this

Serilog.Log.Logger = new LoggerConfiguration()
    .Enrich.WithExceptionDetails()
    .MinimumLevel.Verbose()
    .WriteTo.Console()
    .Enrich.WithProperty("Application", applicationName)
    .WriteTo.File(new JsonFormatter(renderMessage: true), "logs/myapp.txt", rollingInterval: RollingInterval.Day)
    .CreateLogger();
like image 624
Sarfaraz Jamal Avatar asked Oct 29 '25 17:10

Sarfaraz Jamal


1 Answers

I was able to accomplish this by using appsettings.json to define serilog settings and also using code to add a WriteTo method (I needed to do this in code because I am passing the renderMessage parameter to the constructor of JsonFormatter.

Here is what my appsettings.json looks like:

"Serilog": {
"Using": [],
"MinimumLevel": {
    "Default": "Verbose"
},
"Enrich": [ "WithExceptionDetails" ],
"WriteTo": [
    {
    "Name": "Console"
    }
],
"Properties": {
    "Application": "Sample Application"
}
},
"LogsFilePath": "logs/myapp.txt",
"LogsRollingInterval": "Day"

And in my code I did this:

IConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json"));

var config = builder.Build();

Serilog.Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(config)
    .WriteTo.File(new JsonFormatter(renderMessage: true),
        config.GetSection("LogsFilePath").Value,
        rollingInterval: (RollingInterval)Enum.Parse(typeof(RollingInterval), config.GetSection("LogsRollingInterval").Value))
    .CreateLogger();
like image 102
Sarfaraz Jamal Avatar answered Nov 01 '25 06:11

Sarfaraz Jamal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!