简体   繁体   English

NLog ReconfigExistingLoggers 创建新日志?

[英]NLog ReconfigExistingLoggers creating new log?

I'm using Nlog and I need to change the name of the default log to include information such as a company name.我正在使用 Nlog,我需要更改默认日志的名称以包含公司名称等信息。 I've used this code a long time ago on an a console app and it renamed the file as expected.我很久以前在控制台应用程序上使用过这段代码,它按预期重命名了文件。

I'm now trying to use the same code in a new app and it's creating a new log file instead of just renaming the current one.我现在尝试在新应用程序中使用相同的代码,它正在创建一个新的日志文件,而不是仅仅重命名当前的。 For example, I now have two files ( 2019-10.07.log and 2019-10-07_CompanyName.log ).例如,我现在有两个文件( 2019-10.07.log2019-10-07_CompanyName.log )。 The default log will have few initial log entries and then it the remainder of the logs go into the new one.默认日志将有很少的初始日志条目,然后将剩余的日志 go 放入新日志中。

Looking for any suggestions.寻找任何建议。 I've been searching for fixes but everything points me back to the code I'm already using.我一直在寻找修复程序,但一切都让我回到了我已经在使用的代码。

NLog v4.6.7 NLog v4.6.7

fileNameOnly = "CompanyName";
FileTarget defaultTarget = FindNLogTargetByName("DefaultTarget");
defaultTarget.FileName = logDirectory + string.Format("{0:yyyy-MM-dd}", DateTime.Now) + "_" + fileNameOnly + ".log";

LogManager.ReconfigExistingLoggers();

NLog doesn't support renaming an existing file. NLog 不支持重命名现有文件。 If a new file name is used, all the logs will be appended to the new file.如果使用新文件名,所有日志都将附加到新文件中。

So for the file name you need to use System.IO.File.Move(path, pathnew) and change NLog.因此对于文件名,您需要使用System.IO.File.Move(path, pathnew)并更改 NLog。

Unfortunately it's a bit tricky when doing high volume logging, as NLog will recreate the old log file until the target is changed.不幸的是,在进行大量日志记录时有点棘手,因为 NLog 将重新创建旧的日志文件,直到目标被更改。

NLog can load settings (like Company name) from app.config or appsettings.json. NLog 可以从 app.config 或 appsettings.json 加载设置(如公司名称)。

Just update your NLog.config to reference the setting.只需更新您的 NLog.config 以引用该设置。 Ex.前任。

<target type="file" name="myfile" fileName="${appsetting:CompanyName}${shortdate}.log" />

See also: https://github.com/NLog/NLog/wiki/AppSetting-Layout-Renderer (Net Framework)另请参阅: https://github.com/NLog/NLog/wiki/AppSetting-Layout-Renderer (网络框架)

See also:https://github.com/NLog/NLog/wiki/ConfigSetting-Layout-Renderer (Net Core)另请参阅:https://github.com/NLog/NLog/wiki/ConfigSetting-Layout-Renderer (网络核心)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM