3 回答

TA贡献1772条经验 获得超5个赞
我在 Twitter 上向@davidfowl 提出了同样的问题。他已回复:
不,没有什么开箱即用的。有一个端到端的应用程序洞察力,但它不是很充实。您可能会考虑跨团队使用相同的中间件。如果在 3.0 中有一个工作项来解决这个问题https://github.com/aspnet/Hosting/issues/1350
因此,目前看来,定制中间件是唯一的出路。这可能会随着未来的版本而改变。
更新
我们最终按照@DavidMcEleney 的建议创建了一个自定义中间件。然而,在它之上我们添加了CorrelationId一个AsyncLocal属性。这有助于我们在CorrelationId需要时访问代码中的任何位置。这是代码获取/设置CorrelationId:
using System;
using System.Threading;
public static class CorrelationContext
{
private static readonly AsyncLocal<string> CorrelationId = new AsyncLocal<string>();
public static void SetCorrelationId(string correlationId)
{
if (string.IsNullOrWhiteSpace(correlationId))
{
throw new ArgumentException(nameof(correlationId), "Correlation id cannot be null or empty");
}
if (!string.IsNullOrWhiteSpace(CorrelationId.Value))
{
throw new InvalidOperationException("Correlation id is already set");
}
CorrelationId.Value = correlationId;
}
public static string GetCorrelationId()
{
return CorrelationId.Value;
}
}
用于 CorrelationMiddleware.cs
public class CorrelationMiddleware
{
private readonly RequestDelegate _next;
public CorrelationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
context.Request.Headers.TryGetValue("Correlation-Id-Header", out var correlationIds);
var correlationId = correlationIds.FirstOrDefault() ?? Guid.NewGuid().ToString();
CorrelationContext.SetCorrelationId(correlationId);
using (LogContext.PushProperty("Correlation-Id", correlationId))
{
await _next.Invoke(context);
}
}
}
如果我们CorrelationId稍后需要在代码中的任何地方访问 in,那么我们只需调用:CorrelationContext.GetCorrelationId();

TA贡献1824条经验 获得超8个赞
我一直在使用 Serilog 登录 dotnet core 并一直在使用中间件推送 LogContext 属性-
相关中间件.cs
public class CorrelationMiddleware
{
readonly RequestDelegate _next;
public CorrelationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
context.Request.Headers.TryGetValue(Headers.Correlation, out StringValues correlationId);
using (LogContext.PushProperty("Correlation-Id", correlationId.FirstOrDefault()))
{
await _next.Invoke(context);
}
}
}
在您的 Startup.cs 配置方法中注册它:
app.UseMiddleware<CorrelationLogger>();
然后,在进行出站 http 调用时 - 您可以通过添加向 HttpRequestMessage 添加标头
request.Headers.Add(Headers.Correlation, GetHeader("Correlation-Id"));
在搜索日志时,我们可以通过相关 ID 进行搜索并查看所有 API 之间的完整端到端...
- 3 回答
- 0 关注
- 474 浏览
添加回答
举报