Dan
Dan

Reputation: 1111

Serilog Change Log Level on Exception

Is there a way with the Serilog/Seq configuration to change the minimum logging level if the log contains an exception? My use case is the Microsoft JSON input formatter, it logs at Debug level but if there is a problem with the input format, it will throw an exception which is caught and logged at Debug level. I want to log anything that has an exception attached no matter the level.

EDIT: Need to clarify, in production we only log our messages at Information level or higher, or Warning if its coming from framework code (System and Microsoft namespaces). Looking for a way I can log if there is an exception regardless of level of the message.

Upvotes: 5

Views: 1788

Answers (1)

Nicholas Blumhardt
Nicholas Blumhardt

Reputation: 31757

This is possible with Serilog, but comes with some major drawbacks, namely, all debug-level events must first be constructed, before the unwanted ones are filtered out. This is probably too much overhead in most cases, and you're better off just changing the level of the events that log exceptions to Information or higher.

To do it, though:

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug() // emit the events
    .Filter.ByIncludingOnly(le => (int)le.Level >= (int)LogEventLevel.Information ||
                                  le.Exception != null)
    .CreateLogger();

Upvotes: 5

Related Questions