在 Program 中通过 app.UseSerilogRequestLogging()
添加了 serilog 的中间件 RequestLoggingMiddleware
,运行时报错
Unhandled exception. System.InvalidOperationException: Unable to resolve service for type 'Serilog.Extensions.Hosting.DiagnosticContext' while attempting to activate 'Serilog.AspNetCore.RequestLoggingMiddleware'.
Serilog 是通过下面的扩展方法注册的
public static ILoggingBuilder AddCnblogsSerilog(this ILoggingBuilder builder)
{
return builder.AddSerilog((appConfig, loggerConfig) =>
{
loggerConfig.ReadFrom.Configuration(appConfig)
.Enrich.FromLogContext()
.Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
.WithDefaultDestructurers()
.WithDestructurers(new[] { new ApiExceptionDestructurer() /* For Refit */ }));
});
}
builder.AddSerilog
用的是 SerilogLoggingBuilderExtensions.cs#L27 中实现的扩展方法
通过下面的控制台代码可以重现问题
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
var builder = WebApplication.CreateBuilder();
builder.Logging.AddSerilog(logging => logging.WriteTo.Console());
using var app = builder.Build();
app.UseSerilogRequestLogging();
await app.StartAsync();
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Cnblogs.Serilog.Extensions" Version="1.1.0" />
<PackageReference Include="Serilog.AspNetCore" Version="6.1.0" />
</ItemGroup>
改用 Serilog.Extensions.Hosting 提供的针对 IHostBuilder 的扩展方法解决了,Cnblogs.Serilog.Extensions 原本的目的是想实现针对 ILoggingBuilder 的扩展方法
public static IHostBuilder UseCnblogsSerilog(this IHostBuilder builder)
{
return builder.UseSerilog((hostbuilderContext, loggerConfig) =>
{
loggerConfig.ReadFrom.Configuration(hostbuilderContext.Configuration)
.Enrich.FromLogContext()
.Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
.WithDefaultDestructurers()
.WithDestructurers(new[] { new ApiExceptionDestructurer() /* For Refit */ }));
});
}
DiagnosticContext 是在 Serilog.Extensions.Hosting 中实现的,Serilog.AspNetCore 依赖了 Serilog.Extensions.Hosting
– dudu 1年前