简体   繁体   中英

Serilog destructure policy specific to a sink

I am having difficulty getting a Serilog destructure policy working for only a specific sink.

Scenario

I have two sinks: 1. Console 2. File

When logging a DataTable, I need that object to be serialized in a pretty printed table for the (1) Console sink but not for the (2) File sink.

For example,

var table = new DataTable("MyDataSet");
table.Columns.Add("TextColumn");
table.Columns.Add("NumericColumn", typeof(int));
table.Rows.Add("Item0", 0);
table.Rows.Add("Item1", 1);

logger.Information("Test {@Data}", table);

The expected output should be

[10:23:22 INF] Test 
┌────────────┬───────────────┐
│ TextColumn │ NumericColumn │
├────────────┼───────────────┤
│ Item0      │ 0             │
│ Item1      │ 1             │
└────────────┴───────────────┘

Problem

I have the solution working with a custom IDestructuringPolicy (named ConsoleTablePolicy ) to perform the formatting however it applies for all sinks - not just the Console sink.

Current Configuration

Works, but applied for all sinks - the File sink also gets the pretty printed table. This is not what I need.

var logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .WriteTo.Console()
    .WriteTo.File(@"C:\TEMP\log.txt")
    .Destructure.With(new ConsoleTablePolicy())
     .CreateLogger();

Expected Configuration

When adding the Console sink and the custom destructure policy to a sublogger, the destructure policy is never called.

var logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .WriteTo.Logger(c => c.WriteTo.Console().Destructure.With(new ConsoleTablePolicy()))
    .WriteTo.File(@"C:\TEMP\log.txt")
    .CreateLogger();

How to I make this configuration work?

Note that this scenario has been simplified for my needs.

Destructuring applies on the writing thread before it gets submitted to the sinks.

To do what you're doing, you can have an Enricher adjust properties before a given sink.

To avoid successors seeing the mutations the Enricher applies you can either:

  • place the enricher before the sink that needs it and have that be the last sink
  • place an enricher that removes the property after the sink that used the enrichment in the first instance

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