如何为多个文件配置NLog(Servicestack)

时间:2015-05-06 04:01:13

标签: c# servicestack nlog

我需要为每个运行的线程保存一个日志文件。

所以我想要不同的日志文件,下面的代码保存了一个日志,但是我需要创建不同的日志,如何调用方法来说明我要保存哪个文件?

LogManager.LogFactory = new NLogFactory();
var log = LogManager.GetLogger(typeof(Program));
log.Info("********************* TASK REPLICATOR STARTED *********************");

所以我需要配置类似的东西:

  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" throwExceptions="true">
    <targets>
      <target name="logging" xsi:type="File" fileName="${basedir}/logs/${level}.log" archiveFileName="${basedir}/logs/archives/${level}.{###}.log" archiveAboveSize="1048576" archiveNumbering="Sequence" maxArchiveFiles="20" concurrentWrites="true" layout="${longdate}|${callsite}|${level}|${message}" />
      <target name="exception" xsi:type="File" fileName="${basedir}/logs/${level}.log" archiveFileName="${basedir}/logs/archives/${level}.{###}.log" archiveAboveSize="1048576" archiveNumbering="Sequence" maxArchiveFiles="20" concurrentWrites="true" layout="${longdate}|${message}|${exception:format=tostring}" />
      <!-- THIS LINE BELOW DOES WHAT I NEED? -->
      <target name="mynewlogfile" xsi:type="File" fileName="${basedir}/logs/mynewlogfile.log" archiveFileName="${basedir}/logs/archives/TransactionTypes.{###}.log" archiveAboveSize="1048576" archiveNumbering="Sequence" maxArchiveFiles="20" concurrentWrites="true" layout="${longdate}|${callsite}|mynewlogfile|${message}" />
    </targets>
    <rules>
      <logger name="*" minlevel="Debug" maxlevel="Warn" writeTo="logging" />
      <logger name="*" minlevel="Error" maxlevel="Fatal" writeTo="exception" />
    </rules>
  </nlog>

1 个答案:

答案 0 :(得分:4)

您应该能够在文件名布局中简单地使用${threadid}(或者如果您将线程命名为${threadname})。

这将自动将日志条目分成每个线程的一个文件。

<target name="mynewlogfile" xsi:type="File" 
        fileName="${basedir}/logs/mynewlogfile-thread-${threadid}.log" 
        ...
        layout="${longdate}|${callsite}|mynewlogfile|${message}" />