简体   繁体   中英

Serilog machine name enricher for rolling file sink

I'm trying to use a couple of enrichers (machine name and thread ID for now) in conjunction with a rolling file sink and a Loggly sink. Whilst the Loggly events correctly contain the machine name and thread ID properties, I can't see these in the rolling file events.

Here is my xml/code configuration:

<add key="serilog:minimum-level" value="Information" /> 
<add key="serilog:write-to:RollingFile.pathFormat" value="C:\Foo\bar-{Date}.txt" />
<add key="serilog:using" value="Serilog.Sinks.Loggly" />
<add key="serilog:write-to:Loggly.inputKey" value="redacted Loggly key" /> 

new LoggerConfiguration()
    .ReadAppSettings()
    .Enrich.WithMachineName()
    .Enrich.WithThreadId()
    .CreateLogger()

Did anyone manage to do this? Could this behaviour be by design or are these enrichers not supported for rolling file sinks?

The machinename and threadid are added as properties to all log events. They are not in the messageformat so serilog does not convert them to a textual representation. They will however be send to the sinks. The Loggly sink will pick all the properties (including the thread id etc) and convert those to something Loggly understands (as it can accept any kind of data).

If you want the RollingFile sink to also output the machinename etc, you need to adjust te output template. So setting it to for example this:

outputTemplate: "{Timestamp:HH:mm} [{Level}] {MachineName} ({ThreadId}) {Message}{NewLine}{Exception}"

See also https://github.com/serilog/serilog/wiki/Configuration-Basics#enrichers

Since the rolling file sink has no way to output all the properties, you only get the rendered message which by default does not contain those properties.

If you are not seeing properties added by enriches like so

.Enrich.WithProperty("Assembly", assemblyName.Name)

The issue could be with outputTemplated as @Michel suggested. You need to add a outputTemplate for this.

Another way to add output template is to add formatter. First install Serilog.Formatting.Compact . Then you have to specify a formatter. I used the formatter in the appsettings as follows.

"Serilog": {
  "WriteTo": [
    {
      "Name": "Seq",
      "Args": {
        "serverUrl": "http://localhost:5341",
        "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
      }
    }
  ]
},

The JsonFormatter you see is a formatter available our form the nuget. Now all of my enrichers are working WITHOUT any outputTemplate anywhere.

For more details see the following page. https://github.com/serilog/serilog/wiki/Formatting-Output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM