NLog 自动截断消息

本文关键字:消息 NLog | 更新日期: 2023-09-27 18:35:24

我正在将消息记录到最大大小为 1000 个字符的数据库字段中。目前,如果我尝试记录一条大于 1000 个字符的消息(通常包含堆栈跟踪、HTTP 请求内容等异常信息),插入将失败,NLog(应该)默默地忽略它并继续。

我可以在我的 NLog.config 中放入一些东西来声明消息长度应始终被截断,使其不超过 1000 个字符?

如果您能告诉我如何通过将 1000 个字符限制之前的最后几个字符替换为类似"[...截断]"。

不敢相信我不能轻易地通过谷歌搜索找到这个。希望我不必编写自己的渲染器?

NLog 自动截断消息

> NLog 4.6.3 支持这一点:

${message:truncate=1000}

旧版本的 NLog 可以做到这一点:

${trim-whitespace:inner=${message:padding=-1000:fixedLength=true}}
我不知道有什么

内置的方法可以做到这一点。 相反,我会写一个LayoutRenderer(实际上是一个WrapperLayoutRenderer)。 这并不难。

像这样的事情(未经测试)应该这样做:

[LayoutRenderer("truncate")]
[ThreadAgnostic]
public sealed class TruncateLayoutRendererWrapper : WrapperLayoutRendererBase
{
    public TruncateLayoutRendererWrapper()
    {
        this.Truncate = true;
        this.Ellipsis = true;
        this.Limit = 1000;
    }
    [DefaultValue(true)]
    public bool Truncate { get; set; }
    [DefaultValue(true)]
    public bool Ellipsis { get; set; }
    [DefaultValue(1000)]
    public bool Limit { get; set; }
    /// <summary>
    /// Post-processes the rendered message. 
    /// </summary>
    /// <param name="text">The text to be post-processed.</param>
    /// <returns>Trimmed string.</returns>
    protected override string Transform(string text)
    {
        if (!Truncate || Limit <= 0) return text;
        var truncated = text.Substring(0, Ellipsis ? Limit - 3 : Limit);
        if (Ellipsis) truncated += "...";
        return truncated;
    }
}

一种方法是使用消息的正则表达式替换,您可以直接在 nlog.config 中定义。我使用以下内容截断为 500 个字符:

<variable name="truncated_message" value="${replace:replaceWith=...TRUNCATED:regex=true:inner=${message}:searchFor=(?&lt;'=.'{500'}).+}"/>
<target name="filelog" xsi:type="File" fileName="${basedir}/../logs/jobs/${shortdate}.log" layout="${date:format=yyyy-MM-dd HH':mm':ss.fff}|${level:uppercase=true}|${truncated_message}"/>

在 log4net 中,我会在插入语句中指定 left(@msg, 1000) 以确保消息适合数据库列。你可能可以在 nlog 中做类似的事情。

在 sql 服务器中,您可以使用以下片段构造插入到 .. select from-语句中:

case when len(@msg) > 1000 then left(@msg, 988)+' [truncated]' else @msg end