问题
Is there any event handler or similar that I can hook into, to run some code every time NLog starts a new Log File?
I have an NLog Config like this:
<target name="logfile" xsi:type="File"
fileName="[stuff]"
layout="[more Stuff]"
maxArchiveFiles="4"
archiveAboveSize="102400" />
And I'd kinda like to add some meta-data at the start of every log file (version number, Machine Name, etc. so that every log file comes complete with some contextual information)
I don't expect to be able to configure this text in NLog itself, but I'm hoping that I can tell NLog to run a certain method everytime it's going to create a new Log File.
Is this a thing?
回答1:
Sounds like you are really looking for the Header-Layout on the FileTarget.
<target name="logfile" xsi:type="File">
<header>--- ${assembly-version} started on ${longdate} ---</header>
</target>
See also https://github.com/NLog/NLog/wiki/File-target
Some combine it with archiveOldFileOnStartup="true"
because the Header is only printed when file is created (ensure application restarts will create new file).
回答2:
You can use FileSystemWatcher.
FileSystemWatcher is watching specific (which you want it) directory, If new file created, handle this event with FileSystemWatcher
For more details : https://docs.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=netframework-4.8
回答3:
Another partial solution to the "What version?" aspect of this problem could come from:
https://github.com/NLog/NLog/wiki/AssemblyVersion-Layout-Renderer
来源:https://stackoverflow.com/questions/60335551/nlog-onnewlogfile-handler