Joach
Joach

Reputation: 23

Problems configuring Serilog from appSettings.json

I have a question relating the configuration of Serilog by appSettings.json. My project is a console application, based on .Net Core 3.0. I tried to setup Serilog in order to write log information to the console and to a log file.

When I configure everything within my code itself - everything works like expected.

But when I try to import the Serilog configuration settings from an appsettings.json file, I have the problem, that my ConsoleSink works fine, but my FileSink not.

Here is, what I wrote into my appsettings.json:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "File",
        "Args": { "pathFormat": "Xlog.txt" }
      },
      { "Name": "Console" }
    ]
  }
}

And this is the associated code:

  IConfiguration configSerilog = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", true, true)
                .Build();


            log = new LoggerConfiguration()
                 .ReadFrom.Configuration(configSerilog)
                 .CreateLogger();


            log.Information("Initializing Serilog....");

My 'test-log-message' get's displayed in my console window, but I didn't get a logfile.

As I mentioned, it works, when I configure the Serilog in my code itself, rather than by the appsettings. So, I do have the appropriate access rights to create a file.

Any ideas or hints?

Upvotes: 2

Views: 8627

Answers (1)

ElasticCode
ElasticCode

Reputation: 7875

Make sure that file proprieties for appsettings.json, property "Copy to Output Directory" is "Copy always" or "Copy if Newer".

And update youe configration as below (pathFormat in Args shoud be path)

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "File",
        "Args": { "path": "Xlog.txt" }
      },
      { "Name": "Console" }
    ]
  }
}

Upvotes: 6

Related Questions