【问题标题】:Can I Reduce Library's Log Level In .NET Core?我可以在 .NET Core 中降低库的日志级别吗?
【发布时间】:2021-08-23 16:46:24
【问题描述】:

我在 .NET Core 服务中使用来自 Microsoft.IdentityModel.S2S 命名空间的 S2SAuthenticationHandler 进行身份验证。

当身份验证失败时,有许多冗余错误日志我希望作为警告(例如,如果令牌已过期 - 我不希望看到任何错误)。

如果我将 minimum 日志级别设置为 Critical(以避免 Error 日志),我会错过一些有关身份验证失败原因的信息。

有没有办法将库的错误日志级别降低到警告

谢谢!

services.AddAuthentication()
    .AddS2SAuthentication(services, authManager, options =>
            {
                var events = new S2SAuthenticationEvents
                {
                    OnTokenValidated = validatedToken =>
                    {
                        validatedToken.Principal = FixClaims(validatedToken.AuthenticationTicket);
                        return Task.FromResult<object>(null);
                    },
                    OnAuthenticationMessageReceived = context =>
                    {
                        context.S2SContext = new S2SContext(Guid.NewGuid()) { CaptureLogs = true };
                        return Task.FromResult<object>(null);
                    },
                    OnAuthenticationFailed = context =>
                    {
                        // This exception do not the authentication failure reason
                        logger.LogWarning(context.Exception, "Authentication failed, exception might contain additional details");
                        return Task.FromResult<object>(null);
                    }
                };

                options.Events = events;
            })

【问题讨论】:

  • @SnowGroomer OP 正在谈论来自库的一些日志消息声明为错误,他会将它们归类为警告

标签: c# asp.net asp.net-core authentication .net-core


【解决方案1】:

我不确定您当前使用的是什么日志框架,但您通常可以根据您在代码中设置的条件相应地指定日志级别。

例如,NLog 允许您命名您的记录器,并且您可以相应地设置该记录器的详细程度。例如,您可以根据程序集的根命名空间命名您的记录器。

见:https://github.com/nlog/nlog/wiki/Configuration-file#targets

【讨论】:

  • 如果我理解正确,您所指的文章也是在谈论更改最低日志级别。我想将库的错误日志更改为警告日志。我正在使用 .NET Core 的 ILogger 但我想这并不重要,因为库以与我的服务不同的方式处理日志记录,对吗?
  • 这对您有帮助吗?请特别阅读“配置日志记录”部分。您应该能够过滤类别或提供者。 .NET Core Logging Documentation
  • 很遗憾,没有,因为此配置用于设置最低日志级别:“LogLevel 指定了所选类别的最低日志级别”。我想要的是让库的错误日志在我的服务中显示为警告日志
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-07
  • 2019-02-10
  • 2023-03-16
  • 2022-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多