Home > OS >  Retarget logs for a specific class
Retarget logs for a specific class

Time:03-17

I have a .NET 3.1 app.

While I'm fine with it logging information to console in general, there is one part (API client) where it generates tons of logs and it is too much for console. How to make it so that for a particular class logs go not to console but to a file?

Create 2 loggers?

CodePudding user response:

Log.Logger = new LoggerConfiguration()
    .WriteTo.File(@"MyFile.txt")
    .WriteTo.Logger(lc => lc
        .Filter.ByExcluding(Matching.FromSource<ApiClient>())
        .WriteTo.Console())
    .CreateLogger();

Now everything will get written to MyFile.txt but any logs from inside ApiClient won't get output to console

CodePudding user response:

Another option, in case Filter gets a little complicated, is WriteTo.Conditional, which has extra support in Serilog.Expressions:

dotnet add package serilog.expressions

Then:

Log.Logger = new LoggerConfiguration()
    .WriteTo.File("MyFile.txt")
    .WriteTo.Conditional(
        "SourceContext <> 'MyNamespace.ApiClient'",
        wt => wt.Console())
    .CreateLogger();
  • Related