Search code examples
c#serilog

reading appconfig file for serilog


I have Logger.cs class where I am initializing serilog settings as follows:

_logger = new LoggerConfiguration()
                .ReadFrom.AppSettings()
                .MinimumLevel.Debug()
                .WriteTo.File(_filepath, restrictedToMinimumLevel: LogEventLevel.Debug, shared: true, rollOnFileSizeLimit: true)
                .CreateLogger();

I want to read the size of the file from app.config file. I have the app.config file as below

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="serilog:using:File" value="Serilog.Sinks.File" />
    <add key="serilog:write-to:File.fileSizeLimitBytes" value="2000" />
  </appSettings>
</configuration>

But looks like appsettings is not read at all. because I can see more than 2kb file getting generated. What I have missed here?

How my logger class will read from app.config file, have I missed any settings in assemblyinfo class?


Solution

  • The Serilog configuration via App.config does not "merge" with the configuration that you have defined via C# code... These are additive. Meaning that, in your example, you are configuring two independent sinks, that are both writing to a file.

    However, because you did not specify the file path for the sink in the App.config, it's ignoring that sink and not configuring it, and only the second sink is being configured (in the C# code).

    If you want to use the App.config configuration, then your XML should include a file path, in addition to the fileSizeLimitBytes:

    <configuration>
      <appSettings>
        <add key="serilog:minimum-level" value="Debug"/>
        <add key="serilog:using:File" value="Serilog.Sinks.File" />
        <add key="serilog:write-to:File.path" value="log.txt" />
        <add key="serilog:write-to:File.rollOnFileSizeLimit" value="true" />
        <add key="serilog:write-to:File.fileSizeLimitBytes" value="2000" />
      </appSettings>
    </configuration>
    

    And your C# code would just read the settings from the App.config, without the "extra" sink.

    _logger = new LoggerConfiguration()
        .ReadFrom.AppSettings()
        .CreateLogger();
    

    ps: Notice that I also configured the MinimumLevel via App.config. That's not a requirement, but usually makes sense if are already configuring Serilog sinks via App.config.