Serilog 不使用 .NET Core 2.2 写入文件

Serilog not writing to file with .NET Core 2.2

P.S。下面的代码工作正常。问题出在显示器和椅子之间。 @jpgrassi 的回答让我找到了解决问题的正确方向。

我在 program.cs 中有以下内容:

public class Program {
    public static void Main(string[] args) {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseSerilog((ctx, config) => { config.ReadFrom.Configuration(ctx.Configuration); })
            .UseStartup<Startup>();

}

在appsettings.json中:

{
  "Serilog": {

    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Default": "Information",
        "Microsoft": "Information",
        "System": "Information"
      }
    },

    "WriteTo": [
      {
        "Name": "RollingFile",
        "Args": {
          "pathFormat": "log-{Date}.txt",
        }
      }
    ]
  },

  "AllowedHosts": "*"
}

在控制器中,我写了一个日志_logger.LogWarning("foo");,但是文件没有写到任何地方,我看不到任何错误。

我从 Nuget 导入了以下包:Serilog、Serilog.AspNetCore、Serilog.Settings.Configuration、Serilog.Sinks.RollingFile。

我错过了什么?

我假设问题是在 Serilog 配置中缺少 Using 属性,我发布了原始答案。我的项目中总是有它,这是 OP 设置中唯一缺少的东西。但是,在发布答案后,我尝试了不同的配置选项,包括与问题中相同的选项,并且仍在生成日志。阅读更多,我发现 Using 属性 不是必需的。来自 serilog-settings-configuration 包:

(This package implements a convention using DependencyContext to find any package with Serilog anywhere in the name and pulls configuration methods from it, so the Using example above is redundant.) Source: https://github.com/serilog/serilog-settings-configuration

事实证明(请参阅问题评论)真正的问题是日志文件位置和写入权限。在代码方面,一切都已经在工作了。

我会在这里保留原始答案,作为历史问题,但它的内容实际上并没有解决任何问题,因为首先没有任何问题。


原回答:

我认为问题是因为您没有在 appsettings 中指定实际使用 RollingFile 接收器。我刚刚快速创建了一个新应用并且它运行良好:

  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.RollingFile" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "RollingFile",
        "Args": { "pathFormat": "log-{Date}.txt" }
      }
    ],
    "Properties": {
      "Application": "Sample"
    }
  }

使用以下 NuGet 包:

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Serilog.AspNetCore" Version="2.1.1" />
    <PackageReference Include="Serilog.Settings.Configuration" Version="3.0.1" />
    <PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
    <PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.0" />
  </ItemGroup>

这会记录到应用程序根目录中的一个文件中 log-20190304.txt