简体   繁体   中英

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. 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 ). The default log will have few initial log entries and then it the remainder of the logs go into the new one.

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

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. 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.

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 can load settings (like Company name) from app.config or appsettings.json.

Just update your NLog.config to reference the setting. Ex.

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

See also: https://github.com/NLog/NLog/wiki/AppSetting-Layout-Renderer (Net Framework)

See also:https://github.com/NLog/NLog/wiki/ConfigSetting-Layout-Renderer (Net Core)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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