How to dynamically change the FileName using a variable from C#? My idea is to create a log file like Log_<UserId_From_DB>_${date:format=yyyy-MM-dd}.log
.
Any ideas?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Another option is to use the Global Diagnostic Context - $(GDC):
Set the value in C#
In the config (nlog.config):
Please avoid modifying NLog Variables at runtime (See previous answer below). They should be seen as readonly, because they are not threadsafe. NLog Variables will also be affected if LoggingConfiguration is reloaded.
Previous answer with NLog Variables:
Set the value in C#
In the config (nlog.config):
If the value is set again, the filename will automatically changed.
Assuming you have a log file called mylogfile.log in your nlog.config file
While the posted answer works, it suffers from concurrency issues. That variable is a global variable and you may end up with conflicts.
There is a better solution available. There is a way to pass event properties to NLog.
Link to the relevant NLog documentation.
Let's assume you want to log an error message:
You turn this information into a
LogEventInfo
object:You can then add properties to this event (the string indexes are free to choose):
And then you write to the log:
The interesting thing here is that in your NLog configuration, you can use this custom property in any field that the Nlog documentation refers to as a "Layout" value.
You use
${event-properties:item=MySpecialValue}
in the layout to access the property. For example:Following the posted example, you will get a folder named
SPECIAL
, inside of which is a log file namedmy_SPECIAL_file.log
in which you find the messageSPECIAL This is an error message!
. Just to prove the point that you can use this custom value in many different ways and shapes.I commonly use this to make entity-specific logging (where the filename of the log equals the entity's ID value), which is essentially the same as you want to do here.
As a quick tip, I tend to wrap the NLog Logger in a class of my own:
This is just a simple example to get you started. The cool feature I'm using here is that I've defined the log's filename (in the Nlog.Config target) using the
UserId
value and thus can ensure that each user gets logged to their own unique log file.This way, you can enforce that the user ID is known when you want to log to the "user log" target. As an additional bonus, it also neatly decouples NLog dependencies from your calling code.