abx78 abx78 - 1 year ago 86
C# Question

How to set the rolling file name to be unique by process ID

I am trying to have unique name on the log for each one of the processes running at the same time on a machine. I tried to set the pathFormat in the app.config to something similar to

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

That didn't work.

Any idea? I can't find anything in the documentation.

Being able to write the output from multiple sources would make unnecessary having a log for each process. Since (for now) I am stuck with 1.5, I am providing a specific path while configuring the Rolling file.

new LoggerConfiguration()

I just need to provide Machine Name and Thread Id to get a unique log file name.

Answer Source

At the moment, the RollingFile sink that comes with Serilog only supports the {date} tag for dynamic rolling the file.

Thus, if you need a different (dynamic) strategy to roll (like thread id, etc), you'll have write your own sink (you can fork the default one and make your changes).

For machine name though, which usually doesn't change frequently, you could get away with using the environment variable COMPUTERNAME and let Serilog expand it for you.


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

Of course, the environment variable will be expanded at the time you initialize your Serilog config, so if the machine name changes whilst your app is running, you'll still be rolling the file with the old name, until you restart your app (or at least until your app reinitializes Serilog).

ps: Not sure if helps, but Serilog v2.0 introduces a way of sharing the same log file across processes:

.WriteTo.RollingFile("log-{Date}.txt", shared: true)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download