Is there a way to tell Serilog not to serialize null-valued properties of objects logged using the @ (destructuring) operator? I found a couple of posts on the topic (actually, I found more, but these two seemed more relevant with respect to the question and answers):
(1) Ignore null values when destructuring in Serilog is from 2019 and the only answer suggests there is no way to do it.
(2) Ignore null properties from being written to output? is also from 2019, but it suggests that there may be a way to do it using a custom ILogEventEnricher, but there are no pointers on how to actually do it (it also refers to json formatting ignore null properties,l but I'm not sure if this post refers to formatting objects or using JSON formatter to produce log entries in JSON format).
We are currently using Console sink with the Serilog.Templates.ExpressionTemplate, Serilog.Expressions formatter (we use it in combination with a custom enrichers that escape new lines because Azure does not like new lines in log entries), and the File sink with the default formatter. To ignore null values in the output, we use a custom extension method ToJson(), to serialize the objects as simple string values (and we're using JSON.NET):
public static string? ToJson
(
this object data
)
{
JsonSerializer json = new()
{
// Do not change the following line or it may fail to serialize hierarchical data.
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
NullValueHandling = NullValueHandling.Ignore,
DateFormatString = "yyyy-MM-ddTHH:mm:ss.fffZ",
Formatting = Formatting.None,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
TypeNameHandling = TypeNameHandling.None,
};
StringWriter textWriter = new();
json.Serialize(textWriter, data);
return textWriter.ToString();
}
So, if we have an object like:
{"propA":"valueA","propB":null,"propC":"valueC"}
and we log it as:
logger.LogDebug("Data: {data}", data.ToJson());
the output will be:
Data: {"propA":"valueA","propC":"valueC"}
But if we log is as:
logger.LogDebug("Data: {@data}", data);
the output will be:
Data: {"propA":"valueA","propB":null,"propC":"valueC"}
How do we make logging with the @ (destructuring) operator not serialize properties with null values?
JsonValueFormatterclass makes it easy to create new formatters with whatever behavior is required. Copying the code forRenderedCompactJsonFormatterinto your app as a new class, and modifying its internal behavior, is the way to go, here.RenderCompactJsonFormatterseems (and I may be wrong, but that's how I read it) to apply to JSON output (i.e. the whole log entry, not just an object). Also, as I mentioned, we already use theExpressionTemplateformatter, so how would we add nother formatter on top of the one we're using? Maybe I'm missing something obvious, but there are no details on how to actually achieve this.