Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serilog : Log to different files

Tags:

c#

serilog

I am logging events of all types to single Json file irrespective of LogLevel. Now I have a requirement to log some custom performance counters to a seperate Json file. How can this be done in Serilog. Should I create different Logger Instance and use that where ever I am going to Log the performance counters? Want to use this with LibLog

like image 747
Shetty Avatar asked Jul 20 '16 12:07

Shetty


People also ask

Where does Serilog write to by default?

By default, serilog will only log to the console.

What is a Serilog sink?

Serilog sink that writes to console with high-performance non-blocking output. Supports plaintext and JSON output but does not support themes and colors. This sink uses a background channel with a single text buffer and async writes to remove all blocking and lock contention to the console output stream.

How does Serilog work in net core?

Serilog is a . NET library that provides diagnostic logging to files, the console, and almost everywhere you would like. Serilog can be used in classic . NET Framework applications and for applications running on the latest and greatest .


2 Answers

We can set it up in the configuration files too. Given below is a sample in the appsettings.json to split the log the rolling files based on levels

{     "Serilog": {     "MinimumLevel": {       "Default": "Debug",       "Override": {         "Default": "Information",         "Microsoft": "Warning",         "Microsoft.Hosting.Lifetime": "Information"       }     },     "WriteTo": [       {         "Name": "Logger",         "Args": {           "configureLogger": {             "Filter": [               {                 "Name": "ByIncludingOnly",                 "Args": {                   "expression": "(@Level = 'Error' or @Level = 'Fatal' or @Level = 'Warning')"                 }               }             ],             "WriteTo": [               {                 "Name": "File",                 "Args": {                   "path": "Logs/ex_.log",                   "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",                   "rollingInterval": "Day",                   "retainedFileCountLimit": 7                 }               }             ]           }         }       },       {         "Name": "Logger",         "Args": {           "configureLogger": {             "Filter": [               {                 "Name": "ByIncludingOnly",                 "Args": {                   "expression": "(@Level = 'Information' or @Level = 'Debug')"                 }               }             ],             "WriteTo": [               {                 "Name": "File",                 "Args": {                   "path": "Logs/cp_.log",                   "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",                   "rollingInterval": "Day",                   "retainedFileCountLimit": 7                 }               }             ]           }         }       }     ],     "Enrich": [       "FromLogContext",       "WithMachineName"     ],     "Properties": {       "Application": "MultipleLogFilesSample"     }   } } 

Then, you will only need to modify the CreateHostBuilder method in Program.cs file to read it from the configuration file

public static IHostBuilder CreateHostBuilder(string[] args) =>         Host.CreateDefaultBuilder(args)             .ConfigureWebHostDefaults(webBuilder =>             {                 webBuilder.UseStartup<Startup>();             })             .UseSerilog((hostingContext, loggerConfig) =>                 loggerConfig.ReadFrom.Configuration(hostingContext.Configuration)             ); 

For more details, refer the post here

like image 21
Amal Dev Avatar answered Sep 18 '22 22:09

Amal Dev


You can do this by first making sure the performance counter events are tagged with either a particular property value (OpenMappedContext() in LibLog) or from a particular type/namespace.

var log = LogProvider.For<MyApp.Performance.SomeCounter>() log.Info(...); 

When configuring Serilog, a sub-logger with filter applied can send just the required events to the second file.

Log.Logger = new LoggerConfiguration()     .WriteTo.Logger(lc => lc         .Filter.ByExcluding(Matching.FromSource("MyApp.Performance"))         .WriteTo.File("first.json", new JsonFormatter()))     .WriteTo.Logger(lc => lc         .Filter.ByIncludingOnly(Matching.FromSource("MyApp.Performance"))         .WriteTo.File("second.json", new JsonFormatter()))     .CreateLogger(); 
like image 107
Nicholas Blumhardt Avatar answered Sep 19 '22 22:09

Nicholas Blumhardt