Specify directory for Serilog rolling file path

13.6k views Asked by At

Consider this app.config appSetting entry:

<add key="serilog:write-to:RollingFile.pathFormat"
 value="ServerServiceApp-{Date}.log" />

This is done at app startup:

Log.Logger = new LoggerConfiguration()
    .ReadFrom.AppSettings()
    .Enrich.WithThreadId()
    .CreateLogger();

This is in a Windows service app. The log file ends up here:

C:\Windows\SysWOW64

Clearly, we’d rather have the log file end up in the same directory that houses this service’s .exe (customers don’t want us writing stuff to SysWOW64). But how?

We need the ReadFrom.AppSettings in there so that the customer can supply serilog settings in the app.config, as necessary.

Is there some way to change the directory used for the log file after the ReadFrom.AppSettings has been done?

Would be awesome if we could say something like:

<add key="serilog:write-to:RollingFile.pathFormat"
 value="{ApDomainBaseDirectory}\ServerServiceApp-{Date}.log" />

(And where is {Date}, which can be put in the file path, documented?)

2

There are 2 answers

3
Nicholas Blumhardt On BEST ANSWER

The best place for services to write their logs is %PROGRAMDATA% which, by default, is in C:\ProgramData\.

Try:

<add key="serilog:write-to:RollingFile.pathFormat"
     value="%PROGRAMDATA%\ServerService\Logs\log-{Date}.txt" />

(Program Files is usually considered to be read-only, and writing stuff here will lead to oddities being left behind unexpectedly during uninstall.)

2
Andrei Bîcu On

Just put this before the creation of LoggerConfiguration:

Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;

Then File.path will be constructed based on the project root path.