'NLog creates several log files instead of one
I try to plug NLog to my project, and do it for the first time, code looks like this:
static class Program
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
private static void Main(string[] args)
{
logger.Trace("Enter Main");
MyClass.DoWork();
logger.Trace("Exit Main");
}
class MyClass
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
public static void DoWork()
{
logger.Trace("Enter DoWork");
var mgc = new MyGreatClass();
var task = mgc.RunAsync(...);
logger.Trace("Exit DoWork");
}
}
class MyGreatClass
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
async Task<bool> RunAsync()
{
logger.Trace("Log something");
await DoSomethig();
}
}
And Nlog.config file looks like this:
<targets>
<target name="file" xsi:type="File" fileName="${basedir}/logdata${date:format=HH-mm-ss}.log"
layout="${date:format=HH\:mm\:ss}|${message}" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="file" />
</rules>
But while logging it creates 3 different log files, how to make Nlog to create and log in one file only? Is it good practice to create many log files while running one application?
Solution 1:[1]
This is happening because of the target filename in your Nlog.config file. Every time a log message is being generated, it's creating a new log file using:
fileName="${basedir}/logdata${date:format=HH-mm-ss}.log"
The date:format... portion is a call to DateTime.Now. My code was doing the same thing. Once I set a variable of DateTime.Now at the beginning of my code, I then passed that variable into the Nlog.config setup as the name and only one log file was created.
DateTime localDate = DateTime.Now;
string currentDateString = localDate.ToString("yyyyMMdd-hhmmss");
fileTarget.FileName = baseDirectory + @"\logs\" + currentDateString + "-LOGS.txt";
Solution 2:[2]
NLog will render a new filename every second when using this layout:
fileName="${basedir}/logdata${date:format=HH-mm-ss}.log"
Instead consider doing this:
fileName="${basedir}/logdata${processinfo:StartTime:format=HH-mm-ss:cached=true}.log"
Then NLog will use the process-startup-timestamp, that will not change every second.
See also: https://github.com/NLog/NLog/wiki/ProcessInfo-Layout-Renderer
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeremy Caney |
| Solution 2 | Rolf Kristensen |
