OJB1
OJB1

Reputation: 2785

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

enter image description here

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.

enter image description here

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.

Upvotes: 8

Views: 4450

Answers (2)

Nicholas Blumhardt
Nicholas Blumhardt

Reputation: 31767

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

Upvotes: 18

OJB1
OJB1

Reputation: 2785

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

enter image description here

Upvotes: -3

Related Questions