NLog:如何使用函数(纯代码)而不是布局字符串?

NLog: How to use function (plain code) instead of layout string?

通过声明性布局字符串指定消息格式是一种简单的方法,但仅适用于简单的情况。

当我看到条件或嵌套布局时,我想使用纯代码来格式化我的消息。

如何通过明码格式化我的消息?

您始终可以注册自己的自定义布局渲染器,生成您喜欢的任何精美图案:

LayoutRenderer.Register("king", (logEvent) => "King of the World");

只需确保在加载 NLog-config(或创建任何 NLog-Logger 对象,包括静态 Logger-对象)之前注册布局。

然后您可以像往常一样在布局中使用您的自定义布局渲染器(例如 ${king}

另请参阅:https://github.com/NLog/NLog/wiki/How-to-write-a-custom-layout-renderer

另请参阅:https://nlog-project.org/documentation/v4.5.0/html/T_NLog_LogEventInfo.htm(可用 logevent-属性)

您还可以创建自己的自定义布局-class:

class CustomLayout : Layout
{
    protected string GetFormattedMessage(LogEventInfo logEvent)
    {
         // Legacy-style
         return "King of the world";
    }

    protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target)
    {
         // New style supports reusable StringBuilder (reduces allocation)
         target.Append(GetFormattedMessage(logEvent));
    }
}