Reputation: 407
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?
Upvotes: 6
Views: 15928
Reputation: 7865
You can mix and match XML and code-based configuration, but each sink must be configured either using XML or in code-sinks added in code can't be modified via app settings.
So if you need to use App.config
file you will need to move all configuration to it as below
<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="logs\log.txt" />
<add key="serilog:write-to:File.shared" value="true" />
<add key="serilog:write-to:File.rollOnFileSizeLimit" value="true" />
<add key="serilog:write-to:File.fileSizeLimitBytes" value="2000" />
</appSettings>
And creating logger instance using below code
_logger = new LoggerConfiguration()
.ReadFrom.AppSettings()
.CreateLogger();
Upvotes: 2
Reputation: 27848
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.
Upvotes: 7