nlog根据记录器优先级更改行为

时间:2018-10-15 15:07:03

标签: nlog

我要记录某种布局:

Message: {the message}  
Properties: {key}: {value} | {key}: {value} | ...

我的主要是:

static void Main(string[] args)
    {
        Loggers.TxtLogger.LogInfo();
        Loggers.TxtLogger.LogInfo("My custom message");
        Loggers.TxtLogger.LogInfo(new { id = 1, issue = "my custom issue" });


        Console.ReadKey();
    }

我的Loggers类是:

public static class Loggers
{
    public static ILogger TxtLogger { get; private set; }

    static Loggers()
    {
        TxtLogger = LogManager.GetLogger("TxtLogger");
    }


    public static void LogInfo(this ILogger @this, object message = null)
    {
        @this.Info()
            .Property("Property1Key", "Property1Value")
            .Property("Property2Key", "Property2value")
            .Message(message == null ? "" : "{@message}", message)
            .Write();

    }

    public static void LogError(this ILogger @this, Exception e, object message = null)
    {
        @this.Error()
           .Exception(e)
           .Property("Property1Key", "Property1Value")
           .Property("Property2Key", "Property2value")
           .Message(message == null ? "" : "{@message}", message)
           .Write();
    }
}

我的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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      throwConfigExceptions="true"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

    <variable name="logFile" value="./logs/${shortdate}/${logger}.log" />

    <variable name="colon" value="${literal:text=\:}"/>
    <variable name="quotationMark" value="${literal:text=&quot;}"/>
    <variable name="messageIfNotEmpty" value="${when:when=length('${message}')>0:inner=Message${colon} ${message}${newline}}"/>
    <variable name="properties" value="Properties${colon} ${all-event-properties:format=[key]\: [value]:separator= | }${newline}"/>

    <variable name="layout2" value="${messageIfNotEmpty}${properties}"/>

    <targets>
        <target name="ConsoleLog" xsi:type="Console" layout="${layout2}"/>
        <target name="TxtLog" xsi:type="File" fileName="${logFile}" layout="${layout2}"/>
    </targets>

    <rules>
        <logger name="*" writeTo="ConsoleLog" final="true"/>
        <logger name="*" writeTo="TxtLog" />
    </rules>

</nlog>

有了这个设置,我得到了想要的结果:

Properties: Property1Key: Property1Value | Property2Key: Property2value  

Message: "My custom message"  
Properties: Property1Key: Property1Value | Property2Key: Property2value 

Message: {"id":1, "issue":"my custom issue"}  
Properties: Property1Key: Property1Value | Property2Key: Property2value 

但是当我尝试将其也记录到.txt文件时(我从 ConsoleLog 记录器中删除了_final="true"_属性),我得到了以下结果:

Properties: Property1Key: Property1Value | Property2Key: Property2value

Message: "My custom message"  
Properties: message: My custom message | Property1Key: Property1Value | Property2Key: Property2value  

Message: {"id":1, "issue":"my custom issue"}  
Properties: message: { id = 1, issue = my custom issue } | Property1Key: Property1Value | Property2Key: Property2value  

现在有一个解决方法,那就是如果我将_object message = null_方法中的_LogInfo_参数更改为_string message_,并且使用_newtonsoft json serializer_来序列化对象,但是我想要使用NLog序列化器。
有什么想法吗?

  

更新

在NLog.Config中,我进行了更改:
<variable name="layout2" value="${messageIfNotEmpty}${properties}"/>

<variable name="layout2" value="${properties}${messageIfNotEmpty}"/>
(将消息变量放在属性变量之后)
和:
<rules> <logger name="*" writeTo="ConsoleLog" final="true"/> <logger name="*" writeTo="TxtLog" /> </rules>

<rules> <logger name="*" writeTo="ConsoleLog"/> <logger name="*" writeTo="TxtLog" /> </rules>
(已删除final=true属性)

所以现在我的控制台结果是:

Properties: Property1Key: Property1Value | Property2Key: Property2value

Properties: Property1Key: Property1Value | Property2Key: Property2value
Message: "My custom message"

Properties: Property1Key: Property1Value | Property2Key: Property2value
Message: {"id":1, "issue":"my custom issue"}  

这是期望的结果(属性后带有消息),
但是在txt文件中我得到了结果:

Properties: Property1Key: Property1Value | Property2Key: Property2value

Properties: message: My custom message | Property1Key: Property1Value | Property2Key: Property2value
Message: "My custom message"

Properties: message: { id = 1, issue = my custom issue } | Property1Key: Property1Value | Property2Key: Property2value
Message: {"id":1, "issue":"my custom issue"}  

这显然不是期望的结果。

现在,我再次更改NLog.Config:

<rules>
    <logger name="*" writeTo="ConsoleLog"/>
    <logger name="*" writeTo="TxtLog" />
</rules>  

至:

<rules>
    <logger name="*" writeTo="TxtLog" />
    <logger name="*" writeTo="ConsoleLog"/>
</rules>  

(我将TxtLog放在首位)
现在结果得到了认可,
控制台:效果不理想(消息打印两次)
TXT:理想的结果
最后,如果我改变了:

<variable name="layout2" value="${properties}${messageIfNotEmpty}"/>  

返回至:

<variable name="layout2" value="${messageIfNotEmpty}${properties}"/>  

(将消息变量放在属性之前),
无论记录器的顺序如何,我都无法获得预期的结果。

1 个答案:

答案 0 :(得分:0)

NLog ver中存在错误。 4.5.10,但是您可以通过将代码更改为此来解决:

public static class Loggers
{
    public static ILogger TxtLogger { get; private set; }

    static Loggers()
    {
        TxtLogger = LogManager.GetLogger("TxtLogger");
    }


    public static void LogInfo(this ILogger @this, object message = null)
    {
        @this.Info()
            .Message("{0}", message ?? (object)string.Empty)
            .Property("Property1Key", "Property1Value")
            .Property("Property2Key", "Property2value")
            .Write();
    }

    public static void LogError(this ILogger @this, Exception e, object message = null)
    {
        @this.Error()
           .Message("{0}", message ?? (object)string.Empty)
           .Exception(e)
           .Property("Property1Key", "Property1Value")
           .Property("Property2Key", "Property2value")
           .Write();
    }
}

另请参阅https://github.com/NLog/NLog/pull/2963