Reputation: 5980
We use Serilog to produce json logs (i.e. each log entry is a json, not text). The benefit is they can contain objects. I use it for example to log C# exception object like this:
ILogger.Error("Something bad happened. {@exception}", exception);
This will emit all properties of exception
object to the log. (The variable exception
is of type Exception
here.)
Now I am confused why there is no easy analogy how to do this in an enricher. Currently, we add exception to log in enricher this way:
LogEvent.AddPropertyIfAbsent(new LogEventProperty("exception", new ScalarValue(exception));
Of course, the ScalarValue
converts the exception to a string. It looks like a json object inside doublequotes (a "stringified json").
Now, the problem is that when we put this to ELK (a software to monitor the logs and let us search in them), it complains about exception
field having a different type and it says that it should be object as it was before, not string. (This is another topic - I found many repeated questions how to "solve" it in ELK. But apparently, it cannot be "fixed" in ELK, it should be produced always in the same format. So that's why I ask this question.)
I can't see any object-based analogy of ScalarValue
in Serilog. AddPropertyIfAbsent
doesn't accept the object directly, it wants LogEventProperty
with LogEventPropertyValue
. And this abstract class has a few implementations including simple value, array and dictionary, but none of them seem to emit the object the same way as @exception
does. So I am wondering if this very common and basic scenario is not covered by Serilog, or am I just blind?
Upvotes: 1
Views: 4426
Reputation: 32703
Your enricher accepts an ILogEventPropertyFactory
. You can do
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("User", userDetails,
destructureObjects: true));
and that will enrich it with a custom object.
Upvotes: 3