Search code examples
c#asp.net-coreserilog

Serilog not working from configuration in asp.net core 2.2 API


public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
           .UseSerilog((ctx, config) => { config.ReadFrom.Configuration(ctx.Configuration); })
           .UseStartup<Startup>();
}


public class Startup
{
    public IContainer Container { get; private set; }
    public Startup(IConfiguration configuration)
    {
        Log.Warning("test");
        Configuration = configuration;
    }

}

appsettings.json

{
    "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Default": "Information",
        "Microsoft": "Information",
        "System": "Information"
      }
    },
    "WriteTo": [

      {
        "Name": "RollingFile",
        "Args": {
          "pathFormat": "C:\\test.txt",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.ffff}|{TenantName}|{RequestId}|{SourceContext}|{Level:u3}|{Message:lj}{NewLine}{Exception}",
          "restrictedToMinimumLevel": "Information"
        }
      }
    ]
  },

  "AllowedHosts": "*"
}

I have all the packages installed

  • Serilog,
  • Serilog.AspCore,
  • Serilog.Settings.Configuration,
  • Serilog.Sink.File

Solution

  • Your config is for RollingFile but your package list says Serilog.Sinks.File. These are different. You need to add the Serilog.Sinks.RollingFile package and it should start working.

    If you want to use the File sink (which, as @Kirk mentioned in the comments, is the recommended option now) then you need to change the settings to

    "WriteTo": [
        {
            "Name": "File",
            "Args": {
                "path": "C:\\test.txt",
                "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.ffff}|{TenantName}|{RequestId}|{SourceContext}|{Level:u3}|{Message:lj}{NewLine}{Exception}",
                "restrictedToMinimumLevel": "Information"
            }
        }
    

    NOTE

    The pathFormat should be path for the File sink

    See the Serilog File Sink Documentation