How to make Nlog with multiple file target with same cached datetime on filename

StackOverflow https://stackoverflow.com/questions/21568285

  •  07-10-2022
  •  | 
  •  

سؤال

I'm using Nlog 2.0 and I've setup 2 file targets, one for our usual trace log and another for error log. I use fileName="Error_${cached:cached=true:inner=${date:format=yyyyMMdd_HHmmss}}.txt" to give a consistent filename for the log for a single execution of the application.

The problem is that error log is having a different time in the filename than the trace log, since the error started to be logged much later. Right now, I've resorted to sending an empty line on the start of the application to make both log with the same name. Is there a clear approach to this, i.e. single cached datetime for both target?

هل كانت مفيدة؟

المحلول

NLog does not create the log file until the first log is written. It sounds like you would like your log file named based on the start time of your application (or at least have both the trace log and the error log have the same time-based name so you can easily correlate them). If you don't mind a code approach, you could set a time value in the GlobalDiagnosticsContext and then use the GlobalDiagnosticsContext to name your log files. Something like this should work...

In your program, probably in some code that executes at startup, do something like this:

NLog.GlobalDiagnosticsContext.Set("LogFileBase", DateTime.Now.ToString("yyyyMMdd_HHmmss"));

In your NLog.config file, name your file like this:

fileName=${gdc:LogFileBase}.txt

Now the names of your log files will both be based on the start time of the application.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top