gpt4 book ai didi

c# - 在自定义 NLog 目标中检索 HttpContext

转载 作者:行者123 更新时间:2023-12-03 14:51:11 25 4
gpt4 key购买 nike

我可能在这里遗漏了一些基本的东西 - 但是否可以检索 HttpContext.Current在自定义 NLog 事件中?

我试图为每个请求提供一个唯一的 Guid,以便我可以将日志消息与单个事件相关联(即,将单个请求的每个日志事件绑定(bind)在一起)。所以,我想将此Guid 存储在HttpContext.Current.Items 中。 ,然后在 NLog 目标中检索它并将其包含在日志消息中。

这是我想访问的示例目标 HttpContext.Current :

[Target("AzureTableTarget")]
public class AzureTableTarget : TargetWithLayout
{

public AzureTableTarget()
{
_appSettings = IoCResolver.Get<IAppSettings>();
}

protected override void Write(LogEventInfo logEvent)
{
var correlationId = HttpContext.Current; //This is always null

var batchOperation = new TableBatchOperation();
CxLogEventBuilder.Build(_appSettings, logEvent).ForEach(batchOperation.Insert);
_loggingTable.ExecuteBatchAsync(batchOperation);
}
}

最佳答案

现在更容易在 NLog 目标中检索 HTTP 上下文(适用于 ASP.NET 和 ASP.NET Core)

  • 安装 NLog.Web (ASP.NET) 或 NLog.Web.AspNetCore (ASP.NET Core) 包
  • 对于 ASP.NET 核心,请遵循 ASP.NET Core - NLog setup
  • 继承自 AspNetLayoutRendererBase (命名空间 NLog.Web.LayoutRenderers )
  • 调用 var context = HttpContextAccessor.HttpContext; 获取请求

  • 例子:

    [LayoutRenderer("aspnet-sessionid")]
    [ThreadSafe]
    public class AspNetSessionIdLayoutRenderer : AspNetLayoutRendererBase
    {
    protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
    {
    var context = HttpContextAccessor.HttpContext;
    var contextSession = context?.Session();
    if (contextSession == null)
    {
    InternalLogger.Debug("HttpContext Session Lookup returned null");
    return;
    }

    builder.Append(contextSession.SessionID); // ASP.NET Core: contextSession.Id
    }
    }

    PS:目前有很多 ASP.NET (Core) 的预定义渲染器: https://nlog-project.org/config/?tab=layout-renderers&search=aspnet

    关于c# - 在自定义 NLog 目标中检索 HttpContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21972315/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com