serilog / serilog-sinks-file

Write Serilog events to files in text and JSON formats, optionally rolling on time or size
Apache License 2.0
334 stars 117 forks source link

Can I somehow pass formatter args in appsettings.json? #138

Closed xneg closed 4 years ago

xneg commented 4 years ago

In code I can setup formatter like this

Log.Logger = new LoggerConfiguration()
                .WriteTo.Async(config =>
                {
                        var formatter = new ExceptionAsObjectJsonFormatter(renderMessage: true, inlineFields: true);
                        config.Console(formatter);
                })
                .CreateLogger();

Can I do the same thing in appsettings.json? This one does not work:

"Serilog": {
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "D:/logs/{env}.deliverycashier/.log",
          "formatter": "Serilog.Formatting.Elasticsearch.ExceptionAsObjectJsonFormatter, Serilog.Formatting.Elasticsearch",
          "renderMessage": true,
          "inlineFields": true
        } 
      } 
] }
cocowalla commented 4 years ago

Hi!

There are a couple of similar issues over in the Serilog.Settings.Configuration repo.

In a nutshell, it's not possible to pass parameters to constructors at present.

I haven't tried this, but I guess a kind of workaround would be to create your own class that extended the formatter in question and provided the values you want (with a parameterless ctor!)

xneg commented 4 years ago

Ok, thank you. I was thinking about possibility you proposed. But I thought there is some ready solution. Sorry for opening duplicate issue.

cocowalla commented 4 years ago

Not a problem, I'm happy to help 😄

heysaad commented 9 months ago

I think this is possible now. refer https://github.com/serilog/serilog-settings-configuration/issues/225#issuecomment-1760091673

{
  "Name": "File",
  "Args": {
    "path": "log.json",
    "rollingInterval": "Day",
    "retainedFileCountLimit": 7,
    "formatter": {
      "type": "Serilog.Formatting.Json.JsonFormatter, Serilog",
      "renderMessage": true
    }
  }
}