首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >NLog 5.0 -过滤Microsoft.Extensions.Logging日志不起作用

NLog 5.0 -过滤Microsoft.Extensions.Logging日志不起作用
EN

Stack Overflow用户
提问于 2022-06-08 19:34:50
回答 1查看 585关注 0票数 1

我已经将ASP.NET核心项目从3.1迁移到了6.0,现在在使用身份验证中间件时无法摆脱许多微软日志

例如,当我调用API端点时总是有这些日志,其中包含来自未经授权的客户端的[Authorize(Roles = "admin")]注释。

代码语言:javascript
运行
复制
2022-06-08 14:36:28.1023 INFO Microsoft.Extensions.Logging.LoggingExtensions.AuthenticationSchemeChallenged AuthenticationScheme: Bearer was challenged. 
2022-06-08 14:40:58.7025 INFO Microsoft.Extensions.Logging.LoggingExtensions.AuthenticationSchemeChallenged AuthenticationScheme: Bearer was challenged. 
2022-06-08 14:42:53.8049 INFO Microsoft.Extensions.Logging.LoggingExtensions.AuthenticationSchemeChallenged AuthenticationScheme: Bearer was challenged. 

在使用Refit客户机调用另一个API时,我也有这些日志。

代码语言:javascript
运行
复制
2022-06-07 13:38:35.6434 INFO Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler+Log.RequestEnd Received HTTP response headers after 78.0306ms - 200
2022-06-07 13:38:35.6434 INFO Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler+Log.RequestPipelineEnd End processing HTTP request after 81.3323ms - 200
2022-06-07 13:38:35.6947 INFO Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler+Log.RequestPipelineStart Start processing HTTP request POST https://api.removed.com/endpoint
2022-06-07 13:38:35.6947 INFO Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler+Log.RequestStart Sending HTTP request POST https://api.removed.com/endpoint
2022-06-07 13:38:35.8336 INFO Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler+Log.RequestEnd Received HTTP response headers after 136.3691ms - 200
2022-06-07 13:38:35.8336 INFO Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler+Log.RequestPipelineEnd End processing HTTP request after 139.7244ms - 200
2022-06-07 13:38:35.8418 INFO Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler+Log.RequestStart Sending HTTP request POST https://api.removed.com/endpoint
2022-06-07 13:38:37.2229 INFO Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler+Log.RequestEnd Received HTTP response headers after 1379.9163ms - 200
2022-06-07 13:38:37.2229 INFO Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler+Log.RequestPipelineEnd End processing HTTP request after 2437.5144ms - 200

Program.cs

代码语言:javascript
运行
复制
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Web;
using System;

namespace CDL_CloudServerApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var logger = LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();

            try
            {
                logger.Debug("Create Host");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                //NLog: catch setup errors
                logger.Error(ex, "Stopped program because of exception");
                throw;
            }
            finally
            {
                LogManager.Shutdown();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Warning);
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder
                        .UseUrls("http://*:8282")
                        .UseStartup<Startup>()
                        .UseNLog();
                });
    }

}

nlog.config

代码语言:javascript
运行
复制
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" 
      internalLogFile="c:\temp\nlog-internal.log">

    <!-- enable asp.net core layout renderers -->
    <extensions>
        <add assembly="NLog.Web.AspNetCore"/>
    </extensions>

    <variable name="verbose" value="${longdate} ${uppercase:${level}} ${callsite:className=true:fileName=false:includeSourcePath=false:methodName=true:cleanNamesOfAnonymousDelegates=false:skipFrames=0} ${message}" />
    <variable name="verbose_inline" value="${replace:inner=${verbose}:searchFor=\\r\\n|\\n:replaceWith=->:regex=true} ${exception:format=toString,Data:maxInnerExceptionLevel=10}"/>

    <!-- 5GB max size per log-->
    <targets>
        <target name="logfile" xsi:type="File"
                fileName="${basedir}/log/logfile.txt"
                layout="${verbose_inline}"
                archiveFileName="${basedir}/log/archives/log.{#}.txt"
                archiveNumbering="Date"
                archiveDateFormat="yyyy-MM-dd"
                archiveEvery="Day"
                archiveAboveSize="5000000000"
                maxArchiveFiles="14"
                maxArchiveDays="7"
                concurrentWrites="true"
                keepFileOpen="false" />
    </targets>

    <rules>
        <!--Skip non-critical Microsoft logs and so log only own logs-->
        <logger name="Microsoft.*" finalMinLevel="Warn" />
        <logger name="System.Net.Http.*" finalMinLevel="Warn" />

        <logger name="*" minlevel="Info" writeTo="logfile" />
    </rules>
</nlog>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-09 05:09:11

您应该在布局中包括${logger},这样您就可以看到应该过滤掉的记录器名称。

代码语言:javascript
运行
复制
<variable name="verbose" value="${longdate} ${level:uppercase=true} ${logger} ${message}" />
<variable name="verbose_inline" value="${replace-newlines:replacement=->:${verbose}} ${exception:format=toString,Data}"/>

minLevel="Warn"的替代更新,用于所有内容:

代码语言:javascript
运行
复制
<logger name="*" minlevel="Warn" writeTo="logfile" />

另一种方法是在调用RemoveLoggerFactoryFilter = false时指定NLogProviderOptionsUseNLog(),如NLog 5.0 -主要更改列表中所提到的。然后,NLog将继续遵循配置。

注意,您应该小心使用${callsite},因为它带来了巨大的性能开销。

注意,使用regex,${replace-newlines}${replace}更快。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72551282

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档