serilog / serilog-formatting-compact

Compact JSON event format for Serilog
Apache License 2.0
154 stars 45 forks source link

Is there a way to tell RenderedCompactJsonFormatter or to not render some placeholders? #68

Open james-hu opened 3 weeks ago

james-hu commented 3 weeks ago

I have this use case:

This is the example code with "$" showing the use case:

_logger.LogDebug("Created a Job {jobId} for {customer}. Details: {$job}", jobId, customerName, jobDetails);

For CompactJsonFormatter and RenderedCompactJsonFormatter, the output does not contain destructured details of jobDetails in the property "job". So that it is not very useful to me.

This is the example code with "@" showing the use case:

_logger.LogDebug("Created a Job {jobId} for {customer}. Details: {@jobDetails}", jobId, customerName, jobDetails);

For both CompactJsonFormatter and RenderedCompactJsonFormatter, the output contains destructured details of jobDetails in the property "job". For RenderedCompactJsonFormatter, the rendered message contains fully destructured details of jobDetails too, so that the same information gets duplicated. Is there a way to tell RenderedCompactJsonFormatter not to render it in the message?

nblumhardt commented 3 weeks ago

This should be closer to what you want:

_logger
    .ForContext(LogEventLevel.Debug, "jobDetails", jobDetails, destructureObjects: true)
    .Debug("Created a Job {jobId} for {customer}. Details: {$job}", jobId, customerName, jobDetails);

Edit: this uses the Serilog ILogger API; should be adaptable to MEL's ILogger with a bit more code.

james-hu commented 3 weeks ago

Yes, this should work, I didn't think of this approach ☺️ Thanks! Based on this approach, I think an extension can be created as a sugar for making the code easier to write.