gpt4 book ai didi

asp.net-core-webapi - 通用记录器中的 Serilog 缺少异常

转载 作者:行者123 更新时间:2023-12-04 08:04:58 30 4
gpt4 key购买 nike

在 Controller 方法中,通用记录器似乎没有定义的丰富器。
这是 Controller :

public class TestController : Controller
{
ILogger _logger;

public TestController(ILogger<TestController> logger)
{
_logger = logger;
}

public IActionResult action()
{
try
{
throw new NullReferenceException();
}
catch(Exception e)
{
Serilog.Log.Error(ex, "action KO");
_logger.LogError("action KO", ex);
}
}
}
appsettings.json:
{
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
},
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"path": "Log/api.log",
"outputTemplate": "{Timestamp} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
"rollingInterval": "Day",
"retainedFileCountLimit": 7
}
}
],
"Enrich": [
"FromLogContext",
"WithExceptionDetails"
]
}
}
主机楼:
        IHost host = Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseUrls($"http://*:12345");
})
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
.ReadFrom.Configuration(hostingContext.Configuration)
)
.Build()
;
文件/控制台中的输出:
02/18/2021 12:24:57 +01:00 [ERR] () action KO
System.NullReferenceException: Object reference not set to an instance of an object.
at App.TestController`1.action()
02/18/2021 12:24:57 +01:00 [ERR] (App.TestController) action KO
因此,当我尝试使用通用记录器时,会忽略异常。鉴于静态记录器写入它。
我是不是缺少 Controller 记录器的提供者之类的东西,还是应该由 UseSerilog 来完成? ?
编辑
  • 试过 UseSerilogwriteToProviders: true => 没有效果
  • 试过 AddSerilog作为日志生成器 => 无效
      services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(
    new LoggerConfiguration().ReadFrom.Configuration(Configuration).CreateLogger(), true));
  • 试过 AddSerilogServices => 没有效果
      public static IServiceCollection AddSerilogServices(
    this IServiceCollection services,
    LoggerConfiguration configuration)
    {
    Log.Logger = configuration.CreateLogger();
    AppDomain.CurrentDomain.ProcessExit += (s, e) => Log.CloseAndFlush();
    return services.AddSingleton(Log.Logger);
    }
  • 最佳答案

    首先,请更改

    _logger.LogError("action KO", ex); 
    _logger.LogError(ex, "action KO");
    测试以下 try/catch
    try
    {
    throw new NullReferenceException();
    }
    catch (Exception ex)
    {
    _logger.LogError(ex, "action KO");
    }
    ...将其写入日志文件:
    02/27/2021 22:55:59 +01:00 [ERR] (MyMicroservice.Controllers.WeatherForecastController) action KO
    System.NullReferenceException: Object reference not set to an instance of an object.
    at MyMicroservice.Controllers.WeatherForecastController.Get() in C:\Prosjekter\MyMicroservice\WebApp\Controllers\WeatherForecastController.cs:line 51
    在使用文档检查您的配置并进行一些测试后,您添加到问题中的部分对我来说似乎没问题。
    我在测试和阅读文档期间添加了一些关于一个有趣发现的词,最后还有一个 Program.cs你可能想看看。

    TL;DR: Serilog recommends two-stage initialization in order to have atemporary logger before starting the host. The code below showshow to skip stage #1 with a tiny change and still get a logger before starting the host.


    Serilog.AspNetCore 文档 :
    https://github.com/serilog/serilog-aspnetcore#inline-initialization
    开头 Program#Main ,您将有一个 Serilog.Core.Pipeline.SilentLogger .
    如果您遵循这些建议,您将获得 Serilog.Extensions.Hosting.ReloadableLogger在第 1 阶段之后。
    第 1 阶段看起来像这样,需要 Nuget Serilog.Extensions.Hosting
            Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .CreateBootstrapLogger();
    为了尝试为我们节省一些代码行和额外的依赖项,请注释掉阶段 #1,让我们尝试以下方法,看看是否可以在启动 Web 主机之前获得初始化的记录器。
    var webHost = CreateHostBuilder(args).Build();
    在这一行之后,我们确实有一个 Serilog.Core.Logger 的实例,这与我们在使用 CreateHostBuilder(args).Build().Run() 时最终得到的结果相同.因此,我最终得到了以下 Program.cs我完全省略了第 1 阶段,但保留了第 2 阶段。
    这不应该有任何副作用,医生说:

    To address this, Serilog supports two-stage initialization. An initial"bootstrap" logger is configured immediately when the program starts,and this is replaced by the fully-configured logger once the host hasloaded.


    请注意,在注释掉文档中的代码行后, UseSerilog部分现在等于问题中的配置。
    我正在使用 appsettings.json从你的问题。
    我在 Startup.cs 中没有 Serilog 配置.
    using System;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    using Serilog;
    using Microsoft.Extensions.DependencyInjection;

    namespace MyMicroservice
    {
    public class Program
    {
    public static void Main(string[] args)
    {
    // Serilog.Core.Pipeline.SilentLogger at this stage

    var webHost = CreateHostBuilder(args).Build();

    // Serilog.Core.Logger at this stage

    // proof-of-concept: This will log to file before starting the host
    var logger = webHost.Services.GetService<ILogger<Program>>();
    logger.LogWarning("Hello from Program.cs");

    try
    {
    Log.Information("Starting up");
    webHost.Run();
    }
    catch (Exception ex)
    {
    Log.Fatal(ex, "Application start-up failed");
    }
    finally
    {
    Log.CloseAndFlush();
    }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
    .UseSerilog((context, services, configuration) => configuration
    .ReadFrom.Configuration(context.Configuration)
    /*.ReadFrom.Services(services) not required for this case */
    /*.Enrich.FromLogContext() already configured in appsettings.json */
    /*.WriteTo.Console() already configured in appsettings.json */
    )
    .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>());
    }
    }

    关于asp.net-core-webapi - 通用记录器中的 Serilog 缺少异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66260515/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com