Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring Serilog RollingFile with appsettings.json

I'm trying to configure Serilog for a .NET Core project. Here's what I have in my appsettings.json:

 "Serilog": 
{
    "MinimumLevel": "Verbose",
    "Enrich": ["FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId"],
    "WriteTo": [
      { "Name": "RollingFile",
        "Args": {
          "pathFormat": "C:/Logfiles/testapp/log-{Date}.json",
          "textFormatter": "JsonFormatter",
          "fileSizeLimitBytes": 2147483648,
          "retainedFileCountLimit": 5
        }
      }
    ]
  }

The problem I see is that JsonFormatter is not picked up, and instead I get entries using the default text formatter. I tried using "formatter": "JsonFormatter", but got the same result.

It all works fine if I configure Serilog in code:

var jsonSink = new RollingFileSink(config["Logger:FilePath"], new JsonFormatter(), 2147483648, 5);

var logger = new Serilog.LoggerConfiguration().WriteTo.Sink(jsonSink);

Here is the relevant section of my project.json:

"Serilog": "2.2.1",
"Serilog.Extensions.Logging": "1.1.0",
"Serilog.Sinks.Literate": "2.0.0",
"Serilog.Sinks.Seq": "2.0.0",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0",
"Microsoft.Extensions.Logging": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.Extensions.Logging.Debug": "1.0.0",
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
"Serilog.Enrichers.Thread": "2.0.0",
"Serilog.Enrichers.Process": "2.0.0",
"Serilog.Sinks.ColoredConsole": "2.0.0",
"Serilog.Settings.Configuration": "2.2.0"
like image 679
Alexander Avatar asked Nov 30 '16 04:11

Alexander


3 Answers

The formatter argument needs to be a fully-qualified type name. Try:

"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
like image 84
Nicholas Blumhardt Avatar answered Nov 10 '22 00:11

Nicholas Blumhardt


The following works:

var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();

        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .WriteTo.RollingFile(Path.Combine(env.ContentRootPath, "C:\\logs\\log-{Date}.txt"),
                            outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}")
            //.ReadFrom.Configuration(Configuration)
            .CreateLogger();

        Log.Logger.Information("test");

The following also works (only showing CreateLogger portion):

Log.Logger = new LoggerConfiguration()
            //.MinimumLevel.Debug()
            //.WriteTo.RollingFile(Path.Combine(env.ContentRootPath, "C:\\logs\\log-{Date}.txt"),
            //                outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}")
            .ReadFrom.Configuration(Configuration)
            .CreateLogger();

The appsettings.json file (relevant section here is Serilog):

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "Serilog": {
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "RollingFile",
        "Args": {
          "pathFormat": "C:\\logs\\log-{Date}.txt",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}"
        }
      }
    ]
  }
}

The NuGet packages in project.json:

  • "Serilog": "2.3.0",
  • "Serilog.Extensions.Logging": "1.3.1",
  • "Serilog.Sinks.RollingFile": "3.2.0",
  • "Serilog.Sinks.File": "3.1.1",
  • "Serilog.Settings.Configuration": "2.2.0"

My target framework is net452.

like image 17
Jeremy Ray Brown Avatar answered Nov 10 '22 01:11

Jeremy Ray Brown


This works fine for me. "RollingFile" is no longer supported, hence "File" and "pathFormat" is just "path"

"Serilog": {
    "Using": [ "Serilog.Sinks.File" ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Debug",
        "System": "Debug"
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "===> {Timestamp:HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "C:\\Temp\\Logs\\log-appstngs.log",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}",
          "rollOnFileSizeLimit": true,
          "fileSizeLimitBytes": 4194304,
          "retainedFileCountLimit": 10,
          "rollingInterval": "Minute"
        }
      }
    ]
  },
like image 13
Mujib Khan Avatar answered Nov 10 '22 02:11

Mujib Khan