Visual Studio 'Produce Single File' 发布 - Serilog

Visual Studio 'Produce Single File' publish - Serilog

我有一个使用 Serilog 的 .net5.0 控制台应用程序...

Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(config)
                .CreateLogger();

在开发中一切正常。当我使用“生成单个文件”进行发布时,该应用程序可以运行,但日志记录不起作用。 我正在登录文件和控制台...我都没有看到。

如果我不使用单个文件发布,日志记录工作正常。

起初我认为这是读取 appsettings.json 的问题,但一些简单的 Console.Writeline 确认正在读取 appsettings 文件正常(至少从应用程序本身,我可以确认任何Serilog 读取它的方式好吗?)

由于 NET5 bundles/extracts 与 3.x 的方式相比,使用 Serilog 的 NET5 单文件应用程序存在一些问题。

首先,per the documentation Serilog.Settings.Configuration 库(我的粗体和代码块):

Currently, auto-discovery of configuration assemblies is not supported in bundled mode. Use Using section for workaround.

这意味着您的 appsettings.json 文件需要如下所示(假设您使用的是控制台和文件接收器):

{
  "Serilog": {
    "Using":  [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "WriteTo": [
      { "Name": "Console" },
      { "Name": "File", "Args": { "path": "Logs/log.txt" } }
    ],
    // remaining config
  }
}

现在,根据您使用的 Serilog.Settings.Configuration 版本,您可能 也需要此解决方法:

Log.Logger = new LoggerConfiguration()
                  .ReadFrom.Configuration(config, "Serilog", ConfigurationAssemblySource.AlwaysScanDllFiles)
                  .CreateLogger();

相反,您还可以通过如下修改项目文件来恢复到 netcore3's bundling behavior

<PropertyGroup>
 <IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
</PropertyGroup>