Provides basic middleware for syncing a correlation ID across ASP.NET Core APIs.
Installation
First install the package via NuGet: Install-Package CorrelationId
In order to use the 3.0.0 version of this library, the IServiceCollection extension method will need to be called in ConfigureServices. To use the common defaults call AddDefaultCorrelationId
.
public void ConfigureServices(IServiceCollection services)
{
...
services.AddDefaultCorrelationId();
...
}
The middleware then needs to be added in the Configure method, prior to registering any other middleware that you want to have access to the correlation ID. Usually, it can be one of the first items registered.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCorrelationId();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
...
}
Any requests to your application, passing a CorrelationID header, will then use that correlation ID for the remainder of the request. By default, CorrelationId looks for a header named "X-Correlation-ID". This is configurable (see below).
To access the CorrelationId from your application code (for custom logging) you can use the newly added CorrelationContext which carries the CorrelationId for the current request. To gain access to the CorrelationContext from your classes you can add a constructor dependency on ICorrelationContextAccessor which will be injected by the DI framework.
You can then use the ICorrelationContextAccessor to access the CorrelationContext and its current ID.
public class TransientClass
{
private readonly ICorrelationContextAccessor _correlationContext;
public TransientClass(ICorrelationContextAccessor correlationContext)
{
_correlationContext = correlationContext;
}
...
}
Passing on the correlation ID
When your code calls another service you will need to get the correlation ID from the CorrelationContext.CorrelationId property and pass it as a header in your HTTP call. As long as both services are configured with the same header name and both have the Correlation ID middleware enabled, you will see all logging using a matching value between services.
When using the IHttpClientFactory
feature of ASP.NET Core, you may configure automatic correlation ID propagation by registering the correlation ID forwarding handler.
services.AddHttpClient("MyClient") .AddCorrelationIdForwarding();
Custom Correlation ID Provider
A major new feature in this release is the concept of an ICorrelationIdProvider
. This interface defines an abstraction for generating correlation IDs. The library includes two provider implementations which include the previous behaviour.
- The
GuidCorrelationIdProvider
, when registered will generate new GUID-based correlations IDs. - The
TraceIdCorrelationIdProvider
will generate the correlation ID, setting it to the same value as the TraceIdentifier string on the HttpContext.
Only one provider may be registered. Registering multiple providers will cause an InvalidOperationException to be thrown.
To use the WithTraceIdentifierProvider
you can call the TraceIdCorrelationIdProvider
extension on the ICorrelationIdBuilder
within ConfigureServices
.
To register a custom provider, which must implement the ICorrelationIdProvider
interface, use the WithCustomProvider<T>
extension method.
Configuration
If you want to customise the options for the CorrelationId; then you may register the service, passing in an action to operate on the CorrelationIdOptions
.
- RequestHeader - The name of the header from which the Correlation ID is read. The default value is
X-Correlation-ID
. - ResponseHeader - The name of the header to which the Correlation ID is written on the response. The default value is to use the same value as the RequestHeader.
- IncludeInResponse - Controls whether the correlation ID is returned in the response headers. The default value is
true
. - EnforceHeader - Enforce the inclusion of the correlation ID request header. When true and a correlation ID header is not included, the request will fail with a 400 Bad Request response.
- AddToLoggingScope - Add the correlation ID value to the logger scope for all requests. When true the value of the correlation ID will be added to the logger scope payload.
- LoggingScopeKey - The name for the key used when adding the correlation ID to the logger scope. The default value is "CorrelationId".
- IncludeInResponse - Controls whether the correlation ID is returned in the response headers. The default value is
true
. - UpdateTraceIdentifier - Controls whether the ASP.NET Core TraceIdentifier will be set to match the CorrelationId. The default value is
false
. - CorrelationIdGenerator - A
Func<string>
that returns the correlation ID in cases where no correlation ID is retrieved from the request header. It can be used to customise the correlation ID generation. When set, this function will be used instead of the registeredICorrelationIdProvider
.
Example of registration with options:
services.AddDefaultCorrelationId(options =>
{
options.CorrelationIdGenerator = () => "Foo";
options.AddToLoggingScope = true;
options.EnforceHeader = true;
options.IgnoreRequestHeader = false;
options.IncludeInResponse = true;
options.RequestHeader = "My-Custom-Correlation-Id";
options.ResponseHeader = "X-Correlation-Id";
options.UpdateTraceIdentifier = false;
});
See the Release Notes for details of all breaking changes since 2.1.x.
其他文档:
https://www.cnblogs.com/night-w/p/14144112.html