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

ASP.Net Core 6中NLog输出目录不一致,如何修正logger1路径?

解决ASP.NET Core中NLog启动前日志路径不一致问题

问题核心

你在WebApplicationBuilder创建前初始化的logger1,因为ASP.NET宿主环境未启动,NLog的${aspnet-appbasepath}无法获取正确的项目根路径,只能使用执行目录(bin/Debug/net6.0);而后续通过依赖注入的ILogger<T>,因为NLog和ASP.NET完成集成,能拿到正确的项目根路径,所以日志路径正常。

下面提供两种可靠的解决方法:

解决方案1:先创建Builder获取根路径再初始化NLog

这种方法完全对齐ASP.NET的ContentRootPath,无论开发还是生产环境都能保证路径正确:

public static void Main(string[] args)
{
    // 先创建Builder获取正确的项目根路径
    WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
    string contentRoot = builder.Environment.ContentRootPath;

    // 初始化NLog时手动指定logDirectory变量
    var logger1 = NLog.LogManager.Setup()
        .LoadConfigurationFromAppSettings()
        .ConfigureNLog(cfg => 
        {
            cfg.Variables["logDirectory"] = Path.Combine(contentRoot, "Data", "Logs");
        })
        .GetCurrentClassLogger();
    
    logger1.Info("Hello World");

    // 继续完成应用配置
    builder.Logging.ClearProviders();
    builder.Host.UseNLog();

    // ... 其他业务配置代码

    WebApplication app = builder.Build();

    // ... 中间件等后续配置
}

解决方案2:手动设置ASP.NET应用基路径渲染器

如果不想提前创建Builder,可以直接给NLog的AspNetAppBasePathLayoutRenderer指定根路径,让${aspnet-appbasepath}生效:

// 记得引用NLog.Web.AspNetCore包,并添加命名空间
using NLog.Web.LayoutRenderers;

public static void Main(string[] args)
{
    // 获取项目根路径(VS运行时默认为项目目录,和Builder的ContentRootPath一致)
    string contentRoot = Directory.GetCurrentDirectory();

    // 手动设置${aspnet-appbasepath}的默认值
    AspNetAppBasePathLayoutRenderer.DefaultAppBasePath = contentRoot;

    // 初始化NLog,此时${aspnet-appbasepath}会使用我们设置的路径
    var logger1 = NLog.LogManager.Setup()
        .LoadConfigurationFromAppSettings()
        .GetCurrentClassLogger();
    
    logger1.Info("Hello World");

    WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

    builder.Logging.ClearProviders();
    builder.Host.UseNLog();

    // ... 其他配置代码

    WebApplication app = builder.Build();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 05:05:14