13

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?)

Glenn Doten
  • 2,603
  • 3
  • 21
  • 22

2 Answers2

10

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.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Andrei Bîcu
  • 101
  • 1
  • 3
7

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.)

Nicholas Blumhardt
  • 30,271
  • 4
  • 90
  • 101
  • 1
    That idea will work perfectly. Didn't realize that environment variables could be put in the path string. – Glenn Doten Jun 15 '15 at 18:56
  • 3
    What if I prefer to locate my log files in a sub-folder of the deploy directory ( = runtime directory ) ? – BaltoStar Jan 25 '20 at 02:19
  • Unfortunately, this does not work for me with .Net 6 on Linux. On Windows `%COMPUTERNAME%` gets nicely substituted. `${HOSTNAME}` results in `'${HOSTNAME}'` on Linux. – R. Schreurs Oct 12 '22 at 09:16