2

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.

void.pointer
  • 24,859
  • 31
  • 132
  • 243

1 Answers1

0

Add the Serilog.Exceptions NuGet package to your project.

<PackageReference Include="Serilog.Exceptions" Version="8.4.0" />

Include a call to .Enrich.WithExceptionDetails() in your logger configuration.

var log =  new LoggerConfiguration()
    .MinimumLevel.Is(LogEventLevel.Debug)
    .WriteTo.Console(GetConsoleTemplate())
    .WriteTo.File(GetFileTemplate(), logPath.FullName)
    .Enrich.FromLogContext()
    .Enrich.WithExceptionDetails() // << Newly added.
    .CreateLogger();

Use below marker (instead of {@x}) in the template where you only want the exception message.
The Message specifier is the name of the property you want to appear in the logger output.

{ExceptionDetail['Message']}

In the template where you want the full ToString() representation of the exception you can keep using {@x}.

pfx
  • 20,323
  • 43
  • 37
  • 57