4

Hello i am trying to log some messages in a file and others in another file using Serilog.

I have tried the following configuration:

Log.Logger = new LoggerConfiguration()
                    .WriteTo.Map("type", "audit", (name, x) => x.File(auditLogPath))
                    .WriteTo.Map("type", "normal", (nm, wt) => wt.File(logpath).WriteTo.Console())
                    .CreateLogger();

Now i am expecting that when i Push a key-value pair with the key being audit to the log context , my data to get logged in the first pattern audit:

using(LogContext.PushProperty("type","audit")
{
    Log.Information("something");
} 

Why does my data get in the second pattern? Its getting logged to console and put in the other file and i do not get why.

Update

From the answer below i understood there is no need to define multiple loggers, but dispatch based on the key:

Log.Logger = new LoggerConfiguration()
                  .WriteTo.Map("type", string.Empty, (nm, wt) => {
                      if (nm == "audit") {
                        wt.File(auditLogPath);  //i want to write here !
                        return;
                      }
                      wt.File(logpath).WriteTo.Console()                                                                                
                   })
             .CreateLogger();

However when i try to use it to log in the first scenario audit like below, all logs get placed in the other scenario (logpath+ Console)

using(LogContext.PushProperty("type","audit"))
{
    Log.Information("something");
}
4

1 回答 1

5

You misunderstood what the second parameter of Map is. It's not a filter... It's just a default value for your keyPropertyName, in case it's not present in the log event.

The decision to select the sink based on the value of the type property has to be done by you in the body of the Map configuration.

e.g.

Log.Logger = new LoggerConfiguration()
    .WriteTo.Map("type", string.Empty, (type, wt) =>
    {
        if (type.Equals("audit"))
        {
            wt.File(auditLogPath);
        }
        else if (type.Equals("normal"))
        {
            wt.File(logPath)
                .WriteTo.Console();
        }
    })
    .Enrich.FromLogContext()
    .CreateLogger();

Also notice that without enabling enrichment via LogContext the properties you're pushing wouldn't be visible to Map, so you need the .Enrich.FromLogContext() above.

于 2020-07-07T15:33:09.287 回答