NLog / NLog.DiagnosticSource

NLog integration with Microsoft Activity TraceId and SpanId
BSD 3-Clause "New" or "Revised" License
11 stars 3 forks source link

Parsing TraceId to Guid #73

Open sherman89 opened 1 year ago

sherman89 commented 1 year ago

We have a situation where I need to log the unique trace id to the database, but the column type is uniqueidentifier and the value of TraceId is what seems to be GUID without hyphens (ASP.NET Core 6) and saving it like that doesn't work. Unfortunately the database cannot be changed.

Is there a built-in way to Guid.TryParse a string or do I need my own custom layout renderer?

I managed to solve my issue by creating this layout wrapper:

[LayoutRenderer("parseguid")]
[ThreadAgnostic]
public sealed class GuidParserRenderer : WrapperLayoutRendererBase
{

    /// <inheritdoc />
    protected override string Transform(string text)
    {
        return Guid.TryParse(text, out var guid) ? guid.ToString() : Guid.Empty.ToString();
    }
}

Registration:

LogManager.Setup().SetupExtensions(s =>
    s.RegisterLayoutRenderer<GuidParserRenderer>("parseguid")
);

Usage:

<parameter name="@ActivityId" layout="${parseguid:inner=${activity:property=TraceId}}" />

If I do need this custom wrapper, is it implemented correctly? Is it OK to use ThreadAgnostic when wrapping ActivityTraceLayoutRenderer?

Last question: Is TraceId the same as activityId which seems to be deprecated?

Apologies if I missed some obvious piece of documentation somewhere, I tried looking but couldn't find an answer.

Thank you for all of your hard work!

snakefoot commented 1 year ago

Is there a built-in way to Guid.TryParse a string or do I need my own custom layout renderer?

There is not built-in way to reformat string-value into valid Guid.

If I do need this custom wrapper, is it implemented correctly? Is it OK to use ThreadAgnostic when wrapping ActivityTraceLayoutRenderer?

Looks correct, and yes adding [ThreadAgnostic] is correct optimization.

Is TraceId the same as activityId which seems to be deprecated?

Yes System.Diagnostics.CorrelationManager.ActivityId is "obsolete", and has been replaced by System.Diagnostics.Activity.Current

Btw. you are wellcome to create a pull-request for this git-repo, that adds new enum-property TraceGuid, so you have the option out of the box without needing custom layout-renderer.