Set ASP.NET Core FormatterOptions JsonWriterOptions encoder from config

99 Views Asked by At

I use ASP.NET Core json logging from Microsoft.Extensions.Logging. I can configure encoder in code like this:

builder.Logging.AddJsonConsole(config =>
{
    config.JsonWriterOptions = new JsonWriterOptions { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
});

But I don't understand why it doesn't work when I try to do the same thing by using only config:

{
  "Logging": {
    "Console": {
      "FormatterOptions": {
        "JsonWriterOptions": {
          "Encoder": "System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping"
        }
      }
    }
  }
}
1

There are 1 best solutions below

0
On

I believe you cannot set Encoder property this way because the default Bind implementation which binds appsetting.json values to an object doesn't bind static properties or anything else other than plain/collection values. A custom logger provider might be useful in this case.

You can however set other JsonWriterOptions properties and you need to make sure to set FormatterName to json

{
  "Logging": {
    "Console": {
      "FormatterName": "json",
      "FormatterOptions": {
        "JsonWriterOptions": {
          "Indented": true,
          "SkipValidation": true
        }
      }
    }
}