NLog 自动截断消息 [英] NLog auto truncate messages

查看:67
本文介绍了NLog 自动截断消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

是否可以在 NLog.config 中添加一些内容来声明应始终截断消息长度,使其不超过 1000 个字符?

如果您能告诉我如何通过将 1000 个字符限制之前的最后几个字符替换为诸如 "[...Truncated]" 之类的内容来优雅地标记被截断的消息,则可以获得加分.

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

解决方案

我不知道有什么内置的方法可以做到这一点.相反,我会编写一个 LayoutRenderer(实际上是一个 WrapperLayoutRenderer).不难.

应该这样做(未经测试):

[LayoutRenderer("truncate")][线程不可知]公共密封类 TruncateLayoutRendererWrapper : WrapperLayoutRendererBase{公共 TruncateLayoutRendererWrapper(){this.Truncate = true;this.Ellipsis = true;this.Limit = 1000;}[默认值(真)]公共 bool 截断 { 获取;放;}[默认值(真)]公共布尔省略号 { 得到;放;}[默认值(1000)]公共布尔限制{得到;放;}///<总结>///对渲染的消息进行后处理.///</总结>///<param name="text">要后处理的文本.</param>///<returns>修剪后的字符串.</returns>受保护的覆盖字符串转换(字符串文本){if (!Truncate || Limit <= 0) return text;var truncated = text.Substring(0, Ellipsis ? Limit - 3 : Limit);如果(省略号)被截断 += "...";返回截断;}}

I'm logging my messages to a database field with a max size of 1000 characters. Currently if I try to log a message (which often contains exception information with stack trace, HTTP request content, etc.) that's larger than 1000 characters, the insert fails and NLog (as it should) silently ignores that and keeps going.

Is there something I can put in my NLog.config to declare that the message length should always be truncated so it's no greater than 1000 characters?

Bonus points if you can tell me how to gracefully mark truncated messages by replacing the last few characters before the 1000 character limit with something like "[...Truncated]".

Can't believe I can't readily find this with some googling. Hopefully I don't have to write my own renderer?

解决方案

I don't know of a built in way to do it. Instead, I would write a LayoutRenderer (actually, a WrapperLayoutRenderer). It's not hard.

Something like this (untested) ought to do it:

[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 自动截断消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆