简体   繁体   中英

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?

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";

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

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