【问题标题】:NLog console highlight propertiesNLog 控制台高亮属性
【发布时间】:2020-07-21 02:55:51
【问题描述】:

我看过以下video 解释有关 Serilog 的内容。我也想在我的应用程序中使用结构化日志记录(至少是其中的一部分),但我更喜欢使用 NLog (1),因为它已经是我们堆栈的一部分,我们已经习惯了它并且更喜欢使用相同的记录器在我们的项目中,以及 (2) 我已经阅读了比较 here 并且似乎 NLog 的性能更高。

所以我也读到了 NLog support structured logging,并且我已经在测试应用程序中实现了它,没有问题。效果很好。

我在视频中看到并喜欢 Serilog 的是,在写入控制台时,它会突出显示传递给日志记录函数的参数,如下所示:

我想在我目前正在构建的控制台应用程序上使用相同的功能。我已经尝试过Console 目标和ColoredConsole,但没有这种效果。在 NLog 中可以吗?

这是我的目标配置:

<target name="file"
            xsi:type="File"
            archiveEvery="Day"
            archiveFileName="Logs\log.{#}.txt"
            fileName="Logs\log.txt"
            archiveNumbering="DateAndSequence"
            archiveDateFormat="yyyy-MM-dd"
            archiveAboveSize="104857600"
            maxArchiveFiles="30"
            layout="${longdate} | ${uppercase:${level}} | ${logger} | ${threadid} | ${message} ${exception}"
            />

    <target xsi:type="ColoredConsole"
          name="ColorConsole"
          layout="${uppercase:${level}}: ${message} ${exception:innerFormat=Message,StackTrace}"
          header="Memoriez API"
          useDefaultRowHighlightingRules="false"
          >
      <highlight-word foregroundColor="Green" ignoreCase="true" text="info" wholeWords="true" />
      <highlight-word foregroundColor="Red" ignoreCase="true" text="warn" wholeWords="true" />
      <highlight-word backgroundColor="Red" foregroundColor="White" ignoreCase="true" text="error" wholeWords="true" />
      <highlight-row backgroundColor="DarkRed" foregroundColor="Yellow" condition="level == LogLevel.Fatal" />
    </target>

【问题讨论】:

    标签: c# nlog


    【解决方案1】:

    我认为您不能对ColoredConsoleTarget 中的参数进行着色。可能可以使用 WordHighlighting,但您很快就会遇到匹配数字会突出显示所有数字而不仅仅是参数的问题。

    我的猜测是您需要编写一个自定义 ColoredConsoleTarget 以突出显示参数。我刚刚查看了src\NLog\Targets\ColoredConsoleTarget.cs 文件,它只提供RowHighlightingRulesWordHighlightingRules。看起来当应用颜色代码时,LogEventInfo 已呈现为纯字符串。

    我认为您需要编写一个自定义的RenderLogEvent 函数来呈现参数的颜色转义序列。这会有点棘手,因为 WordHighlighting 的 GenerateColorEscapeSequences 会转义在调用它之前生成的任何颜色序列)。

    以下是我的想法:

    1. 使用从ColoredConsoleTarget 复制的代码创建一个新类ColoredParamConsoleTarget。似乎没有虚拟方法可以覆盖现有类。
    2. 创建ColoredRenderLogEvent 方法并解析参数并在参数前后添加颜色序列。
    3. 将对RenderLogEvent 的调用替换为ColoredRenderLogEvent

    【讨论】:

    • 备选方案向ColoredConsoleTarget 添加一个名为IncludeEventProperties 的新选项,该选项将LogEventInfo.Properties 作为页脚附加到带有颜色的输出。欢迎使用 PullRequest 加入 NLog 项目:github.com/NLog/NLog
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-17
    • 2012-09-12
    • 1970-01-01
    • 2020-02-01
    • 2013-12-11
    相关资源
    最近更新 更多