【发布时间】:2021-02-18 13:01:48
【问题描述】:
在控制器方法中,通用记录器似乎没有定义的丰富器。
这里是控制器:
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
所以当我尝试使用通用记录器时,会忽略异常。当静态记录器写入它时。
我是否缺少诸如控制器记录器提供程序之类的东西,还是应该由 UseSerilog 完成?
编辑
-
尝试
UseSerilog和writeToProviders: 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); }
【问题讨论】:
标签: asp.net-core-webapi serilog