TraceContext 1.1.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 and Polyglot Notebooks. 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 Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 is compatible.  netcoreapp2.2 is compatible.  netcoreapp3.0 is compatible.  netcoreapp3.1 is compatible. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
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 605 5/31/2020