Serilog 未记录来自 Program.cs 的日志

Serilog is not logging logs from Program.cs

提问人:LP13 提问时间:11/7/2023 更新时间:11/7/2023 访问量:41

问:

我已将 .NET 5 应用程序更新到 .NET 6,但遇到了日志记录问题。在 Program.cs 中,该行上方的所有内容都会记录到控制台,而该行以下的任何内容都不会记录到控制台或文本文件中。我怀疑这是因为配置在调用 后生效,并且appsettings.json默认日志级别设置为 。尽管我已经在 appsettings.json 中设置了覆盖,但它似乎不适用于 Program.cs 中的日志。var app = builder.Build();appsettings.jsonBuild()Error"DefaultNameSpace.Program":"Information"

是在项目设置中设置的命名空间。DefaultNameSpace

enter image description here

在。NET 6 时,不再需要写出 Program 类和 Main 方法。Program 类的正确命名空间是什么?

program.cs

// The initial "bootstrap" logger is able to log errors during start-up. It's completely replaced by the
// logger configured in `UseSerilog()` below, once configuration and dependency-injection have both been
// set up successfully.
Log.Logger = new LoggerConfiguration()    
    .WriteTo.Console()
    .CreateBootstrapLogger();

Log.Information("Starting up!");

try
{
    var builder = WebApplication.CreateBuilder(args);
    builder.Host.UseSerilog((context, services, configuration) => configuration
                .ReadFrom.Configuration(context.Configuration));

    builder.WebHost.UseUrls("http://*:40004");    

    Log.Information("Building application.");

    // Information logs above this line are logged
    var app = builder.Build();

    // Information logs below are not getting logged        
    Log.Information("Running application");

    app.Run();

    Log.Information("Application Started");
}
catch (Exception ex)
{
    Log.Fatal(ex, "An unhandled exception occurred during bootstrapping");
}
finally
{
    Log.CloseAndFlush();
}

appsettings.json

"Serilog": {
  "Using": [ "Serilog.Sinks.Console","Serilog.Sinks.File" ],
  "MinimumLevel": {
    "Default": "Error",
    "Override": {
      "Microsoft": "Warning",        
      "MyNameSpace.Program": "Information"
    }
  },
  "WriteTo": [
    {
      "Name": "Console"
    },
    {
      "Name": "File",
      "Args": {
        "path": "C:\\Logs\\UI.txt",
        "fileSizeLimitBytes": "10485760",
        "rollingInterval": "Day",
        "rollOnFileSizeLimit": true
      }
    }
  ]
},
net-6.0 serilog serilog-sinks-file microsoft.extensions.logging

评论


答: 暂无答案