使用 PublishSingleFile 选项集配置 NLOG

Configuring NLOG with PublishSingleFile option set

我现在处于困境,我无法满意地解决这个问题。

问题是由于在 ASP.NET Core 3.0 的 Program.cs 文件中使用 NLOG 引起的 应用程序在使用标志 PublishSingleFile 发布应用程序时 Visual Studio 2019 年带有 SelfContained 应用程序的发布选项对话框。

参见:Publishing a single file in NET Core 3.0

如果启用此选项,发布过程将创建一个包含 所有必需的文件,包括 NLOG 程序集。
我部署这个独立的可执行文件 以及站点根目录中的 appsettings.json 和 nlog.config 等配置文件 以及内容文件夹 wwwroot.

启动应用程序的请求到达时出现问题。 此时,我在 main 方法的第一行立即崩溃。 启用 stdout.log 文件后,我可以看到原因。

Unhandled exception. System.IO.FileNotFoundException: Failed to load NLog LoggingConfiguration. Searched the following locations:

  • C:\Windows\TEMP.net\MyAPIjsrg2n.1ad\nlog.config

File name: 'nlog.config' at NLog.LogFactory.LoadConfiguration(String configFile, Boolean optional) at NLog.LogFactory.LoadConfiguration(String configFile) at NLog.LogManager.LoadConfiguration(String configFile) at NLog.Web.NLogBuilder.ConfigureNLog(String configFileName) at MyAPI.Program.Main(String[] args)

似乎整个 exe 运行 来自与站点根文件夹不同的目录。

当然会发生这种情况,因为我的主要方法中的第一行试图初始化 NLOG 程序集。

要完成这个问题,这是我 program.cs 文件中的代码

public class Program
{
    public static void Main(string[] args)
    {
        var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        try
        {
            logger.Info("----------------------------");
            logger.Info("MyAPI Application Start");
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception ex)
        {
            logger.Error(ex, "MyAPI stopped on Exception");
            throw;
        }
        finally
        {
            LogManager.Shutdown();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Warning);
            })
            .UseNLog()
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

所以,感谢所有听我解释的人,这就是问题。

当使用 PublishSingleFile 标志发布应用程序时,这些是在主方法(以及启动代码)中配置 NLOG 的方法吗?

我忘了补充一点,如果我在没有这个设置的情况下发布,一切正常,因此这个问题不是一个问题,但是我想知道是否 有一个解决方法。

如果您想在单个 exe 文件中 NLog.config included/embedded,请尝试在 csproj 文件中指定:

<Content Include="nlog.config">
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
  <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>

如果您想要 NLog.config 放置 externally/outside 单个 exe 文件。然后尝试显式指定进程目录:

var processPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
var nlogConfigPath = Path.Combine(processPath, "nlog.config");
var logger = NLogBuilder.ConfigureNLog(nlogConfigPath).GetCurrentClassLogger();