Reputation: 6581
I am using the Microsoft.Extensions.Logging.ILogger abstraction which provides the BeginScope function, which prepends hierarchical information onto any log between the creation and disposal of the scope.
The default console provider from ms works great and the scopes are useful. I want my Serilog RollingFile sink to contain this information too.
Config code:
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Is(LogEventLevel.Debug)
.Enrich.WithThreadId()
.Enrich.WithProcessId()
.Enrich.WithProcessName()
.Enrich.FromLogContext()
.MinimumLevel.Debug()
.WriteTo.RollingFile(pathFormat: "/opt/iqdata/logs/log-{Date}.txt", restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information, retainedFileCountLimit:30, flushToDiskInterval:TimeSpan.FromSeconds(15), shared:true)
.Enrich.WithProperty("process", "Worker")
.CreateLogger();
var loggerFactory = new LoggerFactory().AddSerilog(Log.Logger).AddConsole(includeScopes: true, minLevel: LogLevel.Debug);
IConfigurationRoot config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "AppSettings.json", optional: false, reloadOnChange: true).Build();
provider = new ServiceCollection()
.AddOptions()
.AddSingleton(loggerFactory)
.BuildServiceProvider();
logger = provider.GetService<ILoggerFactory>().CreateLogger("Worker.Program");
logger.LogDebug("Current directory:{CurrentDirectory}", Directory.GetCurrentDirectory());
So what do I need to do for scope info to be written to the file? Also as a bonus what do I do to Include the Enriched values like ProcessName in the RollingFile sink?
Upvotes: 6
Views: 8241
Reputation: 31842
You can include the scope by setting the rolling file sink's outputTemplate
parameter. The scope property is called {Scope}
.
Using Serilog 2.5, however, you can include both the scope and any additional enriched properties using {Properties}
in the output template, as shown below.
.WriteTo.RollingFile("log-{Date}.txt",
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message} {Properties}{NewLine}{Exception}")
Upvotes: 5