Search code examples
c#asp.net.netasp.net-coreserilog

Serilog SourceContext class name only via appsettings.json only approach


I'm using Serilog ASP.NET Core for my Blazor (Server) project, I configure the logger via appsettings.json and this is how my output template looks like:

"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u4}] ] [{SourceContext}] {Message:lj}{NewLine}{Exception}"

I use builder.Host.UseSerilog() to add it to the app and ILogger to inject it into my components.

What I'd like to have is to display class name only instead of showing full assembly+class name like it does with {SourceContext}.

Is it possible?

I already tried this one: serilog format SourceContext for showing only assembly name

After that the configuration of the logger (appsettings.json) didn't work.

That other question has a code based approach, whereas I prefer a configuration only one via appsettings.json.


Solution

  • You can apply an expression via an ExpressionTemplate.

    Serilogs GitHub page shows a recipe for only logging the type name and no namespace.

    Trim down SourceContext to a type name only:

    Substring(SourceContext, LastIndexOf(SourceContext, '.') + 1)
    

    This expression takes advantage of LastIndexOf() returning -1 when no . character appears in SourceContext, to yield a startIndex of 0 in that case.


    Your appsettings.json configuration has to specify to use an ExpressionTemplate. For the Console logger that looks like below.

    "Serilog": {
      "MinimumLevel": {
        "Default": "Debug",
      },
      "WriteTo": [
        {
          "Name": "Console",
          "Args": {
            "formatter": {
              "type": "Serilog.Templates.ExpressionTemplate, Serilog.Expressions",
              "template": "{@t:HH:mm:ss} - {@l:u} - {Substring(SourceContext, LastIndexOf(SourceContext, '.') + 1)}: {@m}\n{@x}"
            }
          }
        }
      ]
    }
    

    Notice that you'll need to include NuGet packages Serilog.Expressions and Serilog.Settings.Configuration starting from version 3.3.0.

    <PackageReference Include="Serilog.Expressions" Version="3.3.0" />
    <PackageReference Include="Serilog.Settings.Configuration" Version="3.3.0" />