serilog-contrib / serilog-sinks-richtextbox

A Serilog sink that writes log events to a WPF RichTextBox control with colors and theme support
Apache License 2.0
108 stars 25 forks source link

Configuration using appsettings.json #19

Closed rs-maja closed 3 years ago

rs-maja commented 3 years ago

Is there a way to configure RichTextBox logging using ReadFrom.Configuration extension? I don't get it to work, because of the required richTextBoxControl parameter. I need to set this control explicitely in code, and then parameters in appsettings file are overriden.

LoggerConfiguration loggerConfiguration = new LoggerConfiguration()
                    .ReadFrom.Configuration(configuration: Configuration, "Serilog")
                    .WriteTo.RichTextBox(
                        richTextBoxControl: eventLogV.Log,
                        outputTemplate: rtbOutputTemplate,
                        restrictedToMinimumLevel: rtbRestrictedMinimumLevel)
                    .Enrich.FromLogContext();

I would like to skip the WriteTo.RichTextBox(...) part above, since I need to manually read out outputTemplate and restrictedToMinimumLevel values from appsettings.json.

augustoproiete commented 3 years ago

No, it's no possible to use the ReadFrom.Configuration. The sink requires a reference to an existing RichTextBox control that it can write to, so the configuration must be done via code.

That said, you can store some parameters like output template and minimum level in a custom section inside of your config file, and then read those values yourself.

e.g.

{
    "serilogRichTextBox": {
        "outputTemplate": "[{Timestamp:HH:mm:ss} {SourceContext} [{Level}] {Message}{NewLine}{Exception}",
        "minimumLevel": "Information"
    }
}
var serilogRichTextBoxConfig = configuration.GetSection("serilogRichTextBox");
var rtbOutputTemplate = serilogRichTextBoxConfig.GetValue<string>("outputTemplate");
var rtbRestrictedMinimumLevel = serilogRichTextBoxConfig.GetValue<LogEventLevel>("minimumLevel");

LoggerConfiguration loggerConfiguration = new LoggerConfiguration()
    .WriteTo.RichTextBox(
        richTextBoxControl: eventLogV.Log,
        outputTemplate: rtbOutputTemplate,
        restrictedToMinimumLevel: rtbRestrictedMinimumLevel)
    .Enrich.FromLogContext();

// ...