繁体   English   中英

Serilog LogEventPropertyValue 的 Serilog 自定义接收器格式问题

[英]Serilog Custom Sink Formatting Issue with Serilog LogEventPropertyValue

我必须创建自己的自定义水槽,因为目前可用的水槽都不能满足我的需要。

我遇到的问题是,在 Emit 方法中从 logEvent 消息中获取键/值对值时,该值用引号和反斜杠括起来。

我试过将字典中的输出值转换为字符串,然后删除不需要的属性,但对我没有任何作用。

我的自定义接收器中的方法 Class:

    public void Emit(LogEvent logEvent)
    {
        var properties = logEvent.Properties;

        Serilog.Events.LogEventPropertyValue value;
        if (properties.TryGetValue("logEventCategory", out value))
        {
            // Regex.Replace((value.ToString() ?? "").Replace("'", @"\'").Trim(), @"[\r\n]+", " "); // Not working
            var notWorking = value.ToString();
            var formattedValueNotWorking = value.ToString().Replace("\r\n", "\\r\\n");
        }
    }

在此处输入图像描述

似乎忽略了键/值对 Value 的任何格式化尝试:您看到示例字符串值 System 被 \"System\" 包裹 我想要的只是实际字符串,而不是反斜杠或引号缠绕在绳子上。

在此处输入图像描述

创建我自己的接收器是一项非常艰巨的任务,我只想让事情变得简单,花了两天时间试图了解消息格式的更广泛情况,但使用自定义接收器,它变得过于复杂和臃肿的编码,无法满足我的需要。 所有其他标准消息结构属性都呈现正常,例如消息/级别/时间戳等,它只是微调我需要的属性值的呈现,以便将这些值保存到我的数据库中它们自己的列中。

您需要从封闭的ScalarValue中解开字符串:

    // using Serilog.Events;

    public void Emit(LogEvent logEvent)
    {
        var properties = logEvent.Properties;

        Serilog.Events.LogEventPropertyValue value;
        if (properties.TryGetValue("logEventCategory", out value) &&
            value is ScalarValue sv &&
            sv.Value is string rawValue)
        {
            // `rawValue` is what you're looking for

看起来我只需要对字符串替换使用正确的语法:

    public void Emit(LogEvent logEvent)
    {
        var properties = logEvent.Properties;

        Serilog.Events.LogEventPropertyValue value;
        if (properties.TryGetValue("logEventCategory", out value))
        {
            var formattedValueWorking = value.ToString().Replace("\"", "");
            var test = formattedValueWorking;
        }
    }

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM