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

OJB*_*JB1 5 c# logging dictionary serilog .net-5

我必须创建自己的自定义水槽,因为当前可用的水槽都无法满足我的需求。

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

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

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

    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");
        }
    }
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

在此输入图像描述

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

Nic*_*rdt 14

您需要从封闭的字符串中解开字符串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
Run Code Online (Sandbox Code Playgroud)


OJB*_*JB1 -3

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

    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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述