Serilog : Log to different files

≯℡__Kan透↙ 提交于 2020-01-23 04:28:05

问题


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


回答1:


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();



回答2:


If you want to have an independent logging pipeline, just make another instance. This is robbed and adapted from https://github.com/serilog/serilog/wiki/Lifecycle-of-Loggers:

using (var performanceCounters = new LoggerConfiguration()
        .WriteTo.File(@"myapp\log.txt")
        .CreateLogger())
{
    performanceCounters.Information("Performance is really good today ;-)");

    // Your app runs, then disposal of `performanceCounters` flushes any buffers
}


来源:https://stackoverflow.com/questions/38481227/serilog-log-to-different-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!