You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Aspnetcore.Authentication.JwtBearer的日志源以过滤日志?

解决Bearer认证成功日志无法过滤的问题

第一步:确认日志的具体来源命名空间

你当前的Serilog配置里,Console输出没有包含SourceContext(日志来源的命名空间),所以没法确定那条AuthenticationScheme: Bearer was successfully authenticated日志到底来自哪个具体命名空间。

修改你的Console日志输出模板,加入SourceContext字段,这样就能看到每条日志的精确来源:

Log.Logger = new LoggerConfiguration()
    .Enrich.FromLogContext()
    .MinimumLevel.Information()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
    .MinimumLevel.Override("System", LogEventLevel.Warning)
    .MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Warning)
    // 修改Console输出模板,添加SourceContext字段
    .WriteTo.Logger(l => l.MinimumLevel.Verbose().WriteTo.Console(
        outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u3}] {SourceContext} - {Message:lj}{NewLine}{Exception}"))
    .WriteTo.Logger(l => l.MinimumLevel.Information().WriteTo.File("logs/logfile.log", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 10))
    .CreateLogger();

运行API并触发一次Bearer认证,查看Console里的对应日志,就能找到它的SourceContext值——大概率是Microsoft.AspNetCore.Authentication.JwtBearer或者IdentityServer4.AccessTokenValidation。

第二步:添加对应的日志级别覆盖

根据你找到的SourceContext,在Serilog配置里新增对应的MinimumLevel.Override规则。比如如果来源是Microsoft.AspNetCore.Authentication.JwtBearer,就添加:

.MinimumLevel.Override("Microsoft.AspNetCore.Authentication.JwtBearer", LogEventLevel.Warning)

如果是IdentityServer4.AccessTokenValidation,就添加:

.MinimumLevel.Override("IdentityServer4.AccessTokenValidation", LogEventLevel.Warning)

额外说明

你之前配置的MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Warning)理论上应该覆盖其下所有子命名空间,但有时候日志输出的具体命名空间可能和预期有差异,所以通过第一步确认精确来源是最稳妥的方法。

另外要确保你的Override规则是在MinimumLevel.Information()之后设置的,Serilog会按顺序应用规则,后续的Override会覆盖前面的全局设置。

内容的提问来源于stack exchange,提问作者Eugene S.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:55:55