You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core MVC中NLog EventProperties自定义布局渲染器失效求助

问题排查与解决

1. 检查ASP.NET Core中间件注册

确保在Program.cs中正确完成NLog的主机集成,这是获取请求上下文(URL、Action等)的核心前提:

var builder = WebApplication.CreateBuilder(args);

// 清除默认日志提供器,注册NLog
builder.Logging.ClearProviders();
builder.Host.UseNLog();

// 其他服务注册逻辑...

var app = builder.Build();

// 可选:若需管道级别的日志集成,添加此中间件
app.UseNLog();

// 其他中间件配置...

如果缺少builder.Host.UseNLog(),NLog无法访问当前请求的HttpContext,会导致${aspnet-request-url}、${aspnet-mvc-action}等Web相关渲染器无输出。

2. 简化EventProperties布局配置

你自定义布局中${event-properties}的参数冗余,会干扰NLog解析属性值,修改为简洁有效格式:

<!-- 原冗余配置 -->
ActionResult: ${event-properties:item=ActionResult:culture=String:format=String:objectpath=String}
InputParameters: ${event-properties:item=InputParameters:jsonEncode=true}

<!-- 修改后 -->
ActionResult: ${event-properties:item=ActionResult:whenEmpty=未设置}
InputParameters: ${event-properties:item=InputParameters:jsonEncode=true:whenEmpty=无参数}

3. 关联HttpContext到手动创建的LogEventInfo

手动创建的LogEventInfo默认不会绑定当前请求的HttpContext,可通过两种方式解决:

方式一:使用依赖注入的ILogger

在控制器中注入ILogger<YourController>,它会自动关联HttpContext,同时通过BeginScope添加自定义属性:

private readonly ILogger<YourController> _logger;

public YourController(ILogger<YourController> logger)
{
    _logger = logger;
}

public IActionResult Create()
{
    using (_logger.BeginScope(new Dictionary<string, object>
    {
        ["InputParameters"] = jsonFile,
        ["ActionResult"] = "Party successfully created."
    }))
    {
        _logger.LogDebug("Action Successfully Executed");
    }
}

方式二:手动绑定HttpContext

若坚持使用LogManager,可手动将当前HttpContext绑定到日志事件:

Logger logger = LogManager.GetCurrentClassLogger();
var httpContext = HttpContext; // 控制器中可直接获取当前上下文
LogEventInfo theEvent = new LogEventInfo(NLog.LogLevel.Debug, null, "Action Successfully Executed");
theEvent.Properties["InputParameters"] = jsonFile;
theEvent.Properties["ActionResult"] = "Party successfully created.";
// 绑定HttpContext到日志事件
NLog.Web.NLogBuilder.ConfigureNLogWeb().GetService<NLog.Web.INLogWebHelper>()?.SetHttpContext(theEvent, httpContext);
logger.Log(theEvent);

4. 检查版本兼容性

确保NLog.Web.AspNetCore版本与你的ASP.NET Core版本匹配:

  • .NET 6/7/8:使用NLog.Web.AspNetCore 5.2+
  • .NET Core 3.1:使用NLog.Web.AspNetCore 4.9+
    可通过NuGet包管理器查看并更新版本。

5. 查看NLog内部日志定位问题

你的配置已开启内部日志:

internalLogLevel="Info"
internalLogFile="${aspnet-webrootpath}/logs/logsinternal-nlog-AspNetCore.txt"

打开该日志文件,查找是否有布局渲染器错误提示(如属性找不到、HttpContext为空等),可快速定位问题根源。


内容的提问来源于stack exchange,提问作者siddhesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 02:28:15