Sia*_*ash 5 c# logging middleware .net-core asp.net-core
我熟悉中间件概念,并且在我的项目中实现了许多中间件。我还阅读了Microsoft 文档中的ASP.NET Core 中间件文档。但这一次我遇到了令人困惑的问题,实际上我编写了一个简单的中间件来为每个请求写入日志。
这是我的中间件类:
public class LoggerMiddleware
{
private readonly RequestDelegate _next;
public LoggerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext, LogDbContext dbContext)
{
var logInfo = await Logger.InitiateLogging(httpContext, dbContext);
try
{
await _next(httpContext);
}
catch (Exception ex)
{
await Logger.AddException(httpContext, ex, true);
}
finally
{
await Logger.PersistLog(logInfo, httpContext);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后我声明了一个扩展方法:
public static class LoggingMiddlewareExtensions
{
public static IApplicationBuilder UseLogger(this IApplicationBuilder builder)
{
return builder.UseMiddleware<LoggerMiddleware>();
}
}
Run Code Online (Sandbox Code Playgroud)
最后我在 Startup.cs 上调用了UseLogger方法Configure。
这是我的startup.cs代码:
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory,
IServiceScopeFactory scopeFactory,
IOptions<BaranSettings> baranSettings)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
// other lines of code...
app.UseLogger();
// other lines of code...
}
Run Code Online (Sandbox Code Playgroud)
问题:
问题是LoggerMiddleware调用了构造函数,但Invoke没有调用该方法。有谁知道问题是什么?
对于这个特定的用例,我强烈建议您考虑使用 .Net Core DI 并注入 ILoggerFactory:
为什么 ASP.NET Core DI 知道如何解析 ILogger<T>,但不知道如何解析 ILogger?
也可以看看:
如何使用 LoggerFactory 和 Microsoft.Extensions.Logging 通过 C# 进行 .NET Core 日志记录
| 归档时间: |
|
| 查看次数: |
2731 次 |
| 最近记录: |