TraceContext 1.1.0

.NET Core 2.1 .NET Standard 2.0
dotnet add package TraceContext --version 1.1.0
NuGet\Install-Package TraceContext -Version 1.1.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="TraceContext" Version="1.1.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add TraceContext --version 1.1.0
#r "nuget: TraceContext, 1.1.0"
#r directive can be used in F# Interactive, C# scripting and .NET Interactive. Copy this into the interactive tool or source code of the script to reference the package.
// Install TraceContext as a Cake Addin
#addin nuget:?package=TraceContext&version=1.1.0

// Install TraceContext as a Cake Tool
#tool nuget:?package=TraceContext&version=1.1.0

TraceContext

TraceContext class with ability to access, maintain and pass on TraceId guid anywhere in code. Including http requests. Useful for distributed tracing with structured logging.

NuGet version (TraceContext) UnitTest

Installing TraceContext

You should install TraceContext with NuGet:

Install-Package TraceContext

Or via the .NET Core command line interface:

dotnet add package TraceContext

Setup

[в Startup.cs]

1.

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
+   services.AddTraceId(); // You can configure some tracing parameters for traceIdMiddleware via lambda.
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
+   app.UseTraceId(); // enables TraceId middleware in http pipeline.

   // other middlewares
}

If you need to get current TraceId somewhere in the code (including async and multithreading code):


public class MyAwesomeClass
{
     public void MyAwesomeMethod()
     {
          var traceId = TraceContext.Current.TraceId;
     }
}

Useful extension methods:

for ILogger


using (logger.WithTraceContext())
{
    // log messages in using will contain traceId in scopes
}

// it is shorthand for

/// <summary>
/// LoggingScope с текущим TraceId и TraceIdSource.
/// </summary>
/// <param name="logger">Логгер.</param>
/// <returns>Disposable logging scope.</returns>
public static IDisposable WithTraceContext(this ILogger logger)
{
    return logger.BeginScope(new Dictionary<string, object>
    {
        ["TraceId"] = TraceContext.Current.TraceId!,
        ["TraceIdSource"] = TraceContext.Current.TraceIdSource!
    });
}

for IHttpClientBuilder


public static IHttpClientBuilder AddHttpClient(this IServiceCollection services)
{
    return services
        .AddHttpClient<IGithubClient, GitHubClient()
        .AddTracing();
        // this applies TraceIdDelegatingHandler to all requests,
        // that enrich request headers with current traceId and traceId source.
}

Possible configuration:


    /// <summary>
    /// TraceId middleware settings.
    /// </summary>
    public class TraceIdSettings
    {
        /// <summary>
        /// Default HTTP header name for traceId.
        /// </summary>
        private const string DefaultHeader = "X-TRACE-ID";

        /// <summary>
        /// Default HTTP header name for traceId source.
        /// </summary>
        private const string DefaulSourceIdHeader = "X-TRACE-ID-SOURCE";

        /// <summary>
        /// HTTP header name for traceId.
        /// </summary>
        public string Header { get; set; } = DefaultHeader;

        /// <summary>
        /// HTTP header name for traceId source.
        /// </summary>
        public string TraceIdSourceHeader { get; set; } = DefaulSourceIdHeader;

        /// <summary>
        /// Auto generate traceId if it is not present in incoming http request headers.
        /// <para> Default: false.</para>
        /// </summary>
        public bool GenerateIfNotPresent { get; set; }

        /// <summary>
        /// Should return 400 Bad request, if traceId not passed in incoming http request headers, and <see cref="GenerateIfNotPresent"/> was set to false.
        /// <para> Default: false.</para>
        /// </summary>
        public bool ThrowBadRequestIfNotPresent { get; set; }

        /// <summary>
        /// Begin scope for ILogger with current traceId and traceIdSource
        /// </summary>
        public bool UseLoggerScope { get; set; } = true;

        /// <summary>
        /// Log debug if traceId was generated.
        /// </summary>
        public bool LogIfTraceIdGenerated { get; set; }
    }

Contribute

Feel free for creation issues, or PR 😃

License

Copyright © 2020 Shamil Sultanov

The MIT licence.

Product Versions
.NET net5.0 net5.0-windows net6.0 net6.0-android net6.0-ios net6.0-maccatalyst net6.0-macos net6.0-tvos net6.0-windows net7.0 net7.0-android net7.0-ios net7.0-maccatalyst net7.0-macos net7.0-tvos net7.0-windows
.NET Core netcoreapp2.0 netcoreapp2.1 netcoreapp2.2 netcoreapp3.0 netcoreapp3.1
.NET Standard netstandard2.0 netstandard2.1
.NET Framework net461 net462 net463 net47 net471 net472 net48
MonoAndroid monoandroid
MonoMac monomac
MonoTouch monotouch
Tizen tizen40 tizen60
Xamarin.iOS xamarinios
Xamarin.Mac xamarinmac
Xamarin.TVOS xamarintvos
Xamarin.WatchOS xamarinwatchos
Compatible target framework(s)
Additional computed target framework(s)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.1.0 425 5/31/2020