【发布时间】:2020-02-11 12:01:17
【问题描述】:
我已经提到了这个 Update NLog target filename at runtime 和许多其他链接,但在我的情况下似乎没有一个有效。 我使用
初始化记录器private Logger logger = LogManager.GetCurrentClassLogger();
所有日志消息都排队,然后使用计时器清空。
this.messageQueue = new ConcurrentQueue<NotificationMessagePacket>();
this.timer = new System.Timers.Timer(1000);
this.timer.Elapsed += (o, e) =>
{
if (!isWriting)
{
lock (_lockObject)
{
isWriting = true;
NotificationMessagePacket packet;
while (this.messageQueue.TryDequeue(out packet) && packet != null)
{
try
{
if (!string.IsNullOrWhiteSpace(packet.DetailMessage))
this.Infolog(packet);
}
catch (Exception ex)
{
ObjectUtils.EventLogWriteError("NotificationMessagePacket emptying error : " + ex.ToString(),
EventLogEntryType.Warning);
}
}
}
isWriting = false;
}
};
this.timer.Start();
我正在尝试使用以下代码重置目标的文件名:
LoggingConfiguration configuration = LogManager.Configuration;
var wrapper = (AsyncTargetWrapper)configuration.FindTargetByName("log");
var target = (FileTarget)wrapper.WrappedTarget;
string path = Path.Combine(basePath, "Test", "Log", string.Concat(DateTime.Now.ToString("dd"), "_", DateTime.Now.ToString("MMMM"), "_", DateTime.Now.Year + @"\AppLogs.txt"));
if (!string.IsNullOrEmpty(message.ProcessId))
path = Path.Combine(basePath, "Test", "Log", string.Concat(DateTime.Now.ToString("dd"), "_", DateTime.Now.ToString("MMMM"), "_", DateTime.Now.Year + @"\" + message.ProcessId + ".txt"));
target.FileName = path;
target.ConcurrentWrites = false;
LogManager.Configuration = configuration;
LogManager.ReconfigExistingLoggers();
但有时,日志消息不会写入适当的文件。
【问题讨论】:
-
我会推荐使用 GDC,看到这个答案:stackoverflow.com/a/53145100/201303
-
您可能需要的不仅仅是 GDC,请参阅(长)答案。希望它能解决您的问题!
-
嗨 Julian,感谢解决方案有效