Using Serilog + Serilog.Expressions, how do I make exceptions log only Message
in the console sink and ToString()
for file sinks? Here is my set up right now:
return new LoggerConfiguration()
.MinimumLevel.Is(LogEventLevel.Debug)
.WriteTo.Console(GetConsoleTemplate(), _levelSwitch.MinimumLevel)
.WriteTo.File(GetFileTemplate(), logPath.FullName)
.Enrich.FromLogContext()
.CreateLogger();
These methods configure the expression template I use. There's a "common" part of the template, which gets specialized depending on the type of sink (console or file).
private static string GetBaseTemplateString()
{
var scope = LogProperty.Scope;
return
$"{{#if {scope} is not null}}{{{scope}}}: {{#end}}" +
"{@m}\n" +
"{@x}";
}
private static ExpressionTemplate GetConsoleTemplate()
{
var template = "[{@l:u3}] " + GetBaseTemplateString();
return new ExpressionTemplate(template, theme: TemplateTheme.Code);
}
private static ExpressionTemplate GetFileTemplate()
{
var template = "[{@t:HH:mm:ss} {@l:u3}] " + GetBaseTemplateString();
return new ExpressionTemplate(template);
}
Right now, {@x}
seems to result in exception.ToString()
but what I really want is exception.Message
for just the console sink. So far I haven't found a way to do this. I did find this answer, which suggests there is a way to do this using Serilog.Expressions, but the solution provided there doesn't work. The template seems to be wrong too.