如何使Nlog归档一个文件,其中包含日志记录发生的日期

Car*_*ist 26 c# nlog

我们使用Nlog作为我们的日志框架,我找不到按照我想要的方式存档文件的方法.我想在日志记录文件名中记录日志记录的日期.
Ex 2009-10-01 00:00 -> 2009-10-01:23:59应将所有发生的日志记录放入Log.2009-10-01.log.但是今天的所有日志都应该Log.log用于拖尾等等.

我使用的当前NLog.config看起来像这样.

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
  <extensions>
    <add assembly="My.Awesome.LoggingExentions"/>
  </extensions>
    <targets>
        <target name="file1" xsi:type="File"
              fileName="${basedir}/Logs/Log.log"
              layout="${longdate} ${level:uppercase=true:padding=5} ${session} ${storeid} ${msisdn} - ${logger:shortName=true} - ${message} ${exception:format=tostring}"
              archiveEvery="Day"
              archiveFileName="${basedir}/Logs/Log${shortdate}-{#}.log"
              archiveNumbering="Sequence"
              maxArchiveFiles="99999"
              keepFileOpen="true"
            />
    </targets>
  <rules>
      <logger name="*" minlevel="Trace" writeTo="file1" />
  </rules>
</nlog>
Run Code Online (Sandbox Code Playgroud)

但是,这会将日志文件中的日期设置为创建新日志文件的日期.当您想稍后阅读日志时,这会导致挫败感.

似乎我必须在archiveFileName中至少有一个#,我宁愿不这样做.所以,如果你有一个解决方案,我也会两倍感恩=)

Bri*_*ian 47

可能为时已晚,无法帮助您,但我相信您需要做的就是使用具有正确日期格式日期布局渲染器在文件名中包含日期.通过包含日期,您无需指定存档功能.日期更改时,将自动创建新文件.

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
  <extensions>
    <add assembly="My.Awesome.LoggingExentions"/>
  </extensions>
    <targets>
        <target name="file1" xsi:type="File"
                  fileName="${basedir}/Logs/${date:format=yyyy-MM-dd}.log"
                  layout="${longdate} ${level:uppercase=true:padding=5} ${session} ${storeid} ${msisdn} - ${logger:shortName=true} - ${message} ${exception:format=tostring}"
                  keepFileOpen="true"
                />
    </targets>
  <rules>
      <logger name="*" minlevel="Trace" writeTo="file1" />
  </rules>
</nlog>
Run Code Online (Sandbox Code Playgroud)

  • 此外,此解决方案还禁止自动擦除旧存档日志文件的可能性... (2认同)

the*_*ric 7

如果有人仍然需要解决方案 - 最近在NLog中添加了请求的功能:https://github.com/NLog/NLog/pull/241,但Nuget仍然无法使用