如何根据目标在单独的文件中记录消息

时间:2018-06-05 11:00:42

标签: c# nlog

在Nlog部分我有两个目标csvlayout

    <nlog throwExceptions="false" xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
            internalLogLevel="off" internalLogFile="c:\logs\nlog-internal.log">
    <targets async="false">
      <target name="MeLog" xsi:type="File" lineEnding="CRLF"
              fileName="c:\logs\tempPro-${level}.csv" concurrentWrites="true" archiveFileName="c:\logs\archive\tempPro-${level}-{#####}.csv" archiveAboveSize="5024000" archiveNumbering="Sequence" maxArchiveFiles="10">
        <layout type="CSVLayout" quoting="Auto" withHeader="true">
          <column name="Logger" layout="${logger}" />
          <column name="Date" layout="${date:format=s}" />
          <column name="Level" layout="${level}" />
          <column name="Message" layout="${message}" />

        </layout>
      </target>
      <target name="ReLog" xsi:type="File" lineEnding="CRLF" fileName="C:\logs\Re-${level}.csv" concurrentWrites="true" archiveFileName="C:\Logs\archive\Re-${level}-{#####}.csv" archiveAboveSize="512000000" archiveNumbering="Sequence" maxArchiveFiles="2">
        <layout type="CSVLayout" quoting="Auto" withHeader="true">
          <column name="Logger" layout="${logger}"/>
          <column name="Date" layout="${date:format=s}"/>
          <column name="Level" layout="${level}"/>
          <column name="Message" layout="${message}"/>        

        </layout>
      </target>
    </targets>
    <rules>
      <logger name="*" minlevel="Trace" writeTo="MeLog" />
<logger name="*" minlevel="Trace" writeTo="ReLog" />
    </rules>
  </nlog>

我想通过文件名动态记录错误。 例如在err1上我想登录meLog和err2我想在relog

public bool testMultiLog()
{
    var config = new LoggingConfiguration();           
    var fileTarget = new FileTarget("ReLog")
    {
        FileName = "C:\\logs\\Re-${level}.csv"//,
        Layout = "${longdate} ${level} ${message}  ${exception}"
    };
    config.AddTarget(fileTarget);           
    config.AddRuleForOneLevel(LogLevel.Error, fileTarget);             
    LogManager.Configuration = config;
    Logger logger = LogManager.GetLogger("Example");
    logger.Trace("trace log message");
    logger.Debug("debug log message");
    logger.Info("info log message");
    logger.Warn("warn log message");
    logger.Error("error log message");
    logger.Fatal("fatal log message");
    return true;
}

但它在两个文件中都会产生相同的错误

1 个答案:

答案 0 :(得分:0)

使用不同的记录器名称,然后使用不同的日志实例,以便您可以选择所需的日志实例

<logger name="FirstLog" minlevel="Trace" writeTo="MeLog" />
<logger name="SecondLog" minlevel="Trace" writeTo="ReLog" />
<logger name="*" minlevel="Trace" writeTo="Log" />

创建不同的日志:

Logger firstLogger = LogManager.GetLogger("FirstLog");
Logger secondLogger = LogManager.GetLogger("SecondLog");

现在firstLoggerMeLogLogsecondLogger登录到ReLogLog目标

但不要忘记定义Log目标