问题描述
如何使用C#中的变量动态更改FileName?我的想法是创建一个像Log_<UserId_From_DB>_${date:format=yyyy-MM-dd}.log
这样的日志文件.有什么想法吗?
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?
推荐答案
另一种选择是使用全局诊断上下文-$(GDC):
在C#中设置值
GlobalDiagnosticsContext.Set("UserId_From_DB","42");
在配置(nlog.config)中:
In the config (nlog.config):
<target type="file" filename="Log_${gdc:item=UserId_From_DB}_${date:format=yyyy-MM-dd}.log" ..>
请避免在运行时修改NLog变量(请参见下面的先前答案).它们应被视为只读,因为它们不是线程安全的.如果重新加载LoggingConfiguration,NLog变量也将受到影响.
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.
使用NLog变量的先前答案:
在C#中设置值
LogManager.Configuration.Variables["UserId_From_DB"] = "42";
在配置(nlog.config)中:
In the config (nlog.config):
<target type="file" filename="Log_${var:UserId_From_DB}_${date:format=yyyy-MM-dd}.log" ..>
如果再次设置该值,文件名将自动更改.
If the value is set again, the filename will automatically changed.
这篇关于NLog使用NLog.config动态更改文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!