2

I'm trying to configure Serilog for my ASP.NET app using appsettings.json and am following the instructions from the GitHub Serilog.Settings.Configuration project readme. I cannot get the Console output format expression working from appsettings.json when I also set a theme. When both are configured directly in code it works just fine.

This is the Serilog section of appsettings.json. Note the full template is more complex, it uses Substring(SourceContext, LastIndexOf(SourceContext, '.') + 1) amonst others, but this is how I am testing for now:

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft.AspNetCore": "Warning",
        "Microsoft.EntityFrameworkCore.Database.Command": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "formatter": {
            "type": "Serilog.Templates.ExpressionTemplate, Serilog.Expressions",
            "template": "[{@t:HH:mm:ss:fff} {@l:u3}]  {SourceContext,48} : {@m}\n{@x}"
          },
          "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console"
        }
      }
    ],
    "Enrich": [ "FromLogContext" ]
  }
}

And this is the resulting output (with theme colors):

[17:13:38 INF] Configure
[17:13:38 INF] Now listening on: https://localhost:5001
[17:13:38 INF] Now listening on: http://localhost:5000
[17:13:38 INF] Application started. Press Ctrl+C to shut down.

Which appears to be the default format (note the msec field in the timestamp and the Source Context field are missing).

When I omit the theme setting from the json, the output looks like this, i.e. with the correct expression template applied (e.g. source context) but without any color:

[17:13:37:498 INF]                            App.Web.Server.Program : Server started
[17:13:37:797 INF]                            App.Web.Server.Startup : ConfigureServices

This is the same format I get when I configure the logger in code, but then I get the theme color too!

I also tried to use this format from the project's samples:

          "WriteTo": [
            {
              "Name": "Console",
              "Args": {
                "outputTemplate": "[{Timestamp:HH:mm:ss} {SourceContext} [{Level}] {Message}{NewLine}{Exception}",
                "theme": "Serilog.Sinks.SystemConsole.Themes.SystemConsoleTheme::Grayscale, Serilog.Sinks.Console"
              }
            }
          ]

This is without the format expression, just the format (and a slight variation on the format itself) and, as expected, results in:

[14:35:11 Microsoft.Hosting.Lifetime [Information] Now listening on: "https://localhost:5001"
[14:35:11 Microsoft.Hosting.Lifetime [Information] Now listening on: "http://localhost:5000"

I tried umpteen variations and combinations without any success. So it seems that using appsettings.json I can either get the expression template working, or the theme working, but not both at the same time.

Again: when configured directly in code it "just works" ...

Suggestion are welcome.

HughM
  • 21
  • 4
  • I have the same problemand I've created a new issue/bug in their project: https://github.com/serilog/serilog-settings-configuration/issues/350 – mpiliszcz Feb 14 '23 at 10:04

1 Answers1

1

I tried as below:

Packages:

enter image description here in appsettings.json:

"Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft.AspNetCore": "Warning",
        "Microsoft.EntityFrameworkCore.Database.Command": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
          "outputTemplate": "Time:{Timestamp: HH:mm:ss.fff} Level:{Level} DetailedInfo:{Message}{NewLine}{Exception}"
        }
      }
    ],
    "Enrich": ["FromLogContext"]
  }

In program.cs:

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .UseSerilog((context, logger) =>
                {
                    logger.ReadFrom.Configuration(context.Configuration);
                    

                });

Result: enter image description here and with

"theme": "Serilog.Sinks.SystemConsole.Themes.SystemConsoleTheme::Grayscale, Serilog.Sinks.Console"

enter image description here

Ruikai Feng
  • 6,823
  • 1
  • 2
  • 11
  • Thanks @RuikaiFeng,, but the way I understand it this is not nescessary for ASP.NET projects (which this is).The readme states: For .NET Core projects build tools produce .deps.json files and this package implements a convention using Microsoft.Extensions.DependencyModel to find any package among dependencies with Serilog anywhere in the name and pulls configuration methods from it, so the Using section in example above can be omitted: – HughM Aug 02 '22 at 15:02
  • Sorry,my fault,I removed Using section and it also could work in my case, I've updated all my settings related,hope it could help – Ruikai Feng Aug 03 '22 at 02:30
  • Thanks Ruikai, that works but ... it uses a **text** template and not an **expression** template (I also mention it in my OP). I'm looking for both the expression (see [https://github.com/serilog/serilog-expressions](https://github.com/serilog/serilog-expressions)) and the theme. I want to use the `Substring(SourceContext, LastIndexOf(SourceContext, '.') + 1)`expression, amongst others, to just log the class name in the `SourceContext`. I'll update the Q to make it clearer. – HughM Aug 03 '22 at 09:35