简体   繁体   中英

Serilog Custom Sink Formatting Issue with Serilog LogEventPropertyValue

I'm having to create my own custom sink because none of the ones currently available give me what I need.

Issue I have is when fetching the key/value pair Value from the logEvent message in the Emit Method, the value is wrapped with quotation marks & backslashes.

I've tried converting the out value from the dictionary into a string and then removing the unwanted attributes but nothing is working for me.

Method in my Custom Sink 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");
        }
    }

在此处输入图像描述

It just seems that any attempted formatting of the key/value pair Value is ignored: You see that the example string value System is wrapped with a \"System\" All I want is the actual string, not the backslashes or quotation marks that is wrapped around the string.

在此处输入图像描述

Creating my own sink is a hard enough task and I just want to keep things simple, have spent two days trying to understand the wider picture in message formatting but with custom sinks it gets too complicated and bloated coding for what I need. All the other standard message structure attributes are rendering OK, such as message / level / timestamp etc, it's just fine tuning the rendering of the propertie values I require in order to save these values into their own columns in my DB.

You need to unwrap the string from the enclosing 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

Looks like I just needed to use the correct syntax for string replace:

    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;
        }
    }

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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