首页 新闻 会员 周边 捐助

Serilog: app.UseSerilogRequestLogging 出现 "Unable to resolve service" 错误

0
悬赏园豆:30 [已解决问题] 解决于 2023-02-21 19:59

在 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>
dudu的主页 dudu | 高人七级 | 园豆:30939
提问于:2023-02-21 13:39

DiagnosticContext 是在 Serilog.Extensions.Hosting 中实现的,Serilog.AspNetCore 依赖了 Serilog.Extensions.Hosting

dudu 1年前
< >
分享
最佳答案
0

改用 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 */ }));
    });
}
dudu | 高人七级 |园豆:30939 | 2023-02-21 19:58
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册