سؤال

I have a simple app:

public class Program
{
    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

    public static void Main(string[] args)
    {
        while (true)
        {
            Logger.Info(DateTime.Now.ToString());
            Thread.Sleep(5000);
        }
    }
}

And configuration:

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <targets>
    <target name="logfile" xsi:type="File" fileName="C:\Logs\log.txt" keepFileOpen="true" />
  </targets>
  <rules>
    <logger name="*" minlevel="Trace" writeTo="logfile" />
  </rules>
</nlog>

But NLog does not seem to lock log.txt (desipte keepFileOpen property being set to true) - I can delete it. Even worse - the log file is not recreated after it has been deleted. So if user accidentally deletes the file - there will be no logging until the application is restarted (or in more general case until new log file name takes place).

Is there any way to make NLog lock log files or at least recreate them after they have been deleted?

هل كانت مفيدة؟

المحلول

Use enableFileDelete setting to make NLog lock file:

<target name="logfile" xsi:type="File" 
        fileName="C:\Logs\log.txt" 
        keepFileOpen="true" 
        enableFileDelete="false" />
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top