NLOG 5.0-过滤Microsoft.extensions.logging Logs不工作

发布于 2025-02-05 16:35:58 字数 5646 浏览 3 评论 0原文

我已经迁移了 asp.net core 项目从 3.1到6.0 ,现在我在使用 Authentication Middleware

例如,当我调用API端点[授权(角色=“ admin”)]从未经授权的客户端注释时,我

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. 

总是有这些日志改装客户端

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

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

<?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>

I've migrated an ASP.NET Core project from 3.1 to 6.0 and now I can't get rid of many Microsoft logs when using an Authentication middleware

For example, I always have those logs when I call my API endpoint having[Authorize(Roles = "admin")] annotation from an unauthorized client

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. 

I also have those logs when calling another API using a Refit Client

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

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

<?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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

后eg是否自 2025-02-12 16:35:58

您应该在布局中包含$ {Logger},以便您可以看到应该滤走的logger名称。

<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” 的替代更新。

<logger name="*" minlevel="Warn" writeTo="logfile" />

>如 NLOG 5.0-重大更改列表。然后,NLOG将继续遵循Microsoft logggng滤光片 - 配置。

请注意,您应该对$ {callite}小心,因为它引入了巨大的性能开销。

请注意,$ {replace-newlines}$ {repent}用Regex快。

You should include ${logger} in your layout, so you can see the logger-name that should be filtered away.

<variable name="verbose" value="${longdate} ${level:uppercase=true} ${logger} ${message}" />
<variable name="verbose_inline" value="${replace-newlines:replacement=->:${verbose}} ${exception:format=toString,Data}"/>

Alternative update to minLevel="Warn" for everything:

<logger name="*" minlevel="Warn" writeTo="logfile" />

Alternative specify RemoveLoggerFactoryFilter = false for NLogProviderOptions when calling UseNLog() as mentioned in NLog 5.0 - List of major changes. Then NLog will continue to follow Microsoft Logggng Filter-configuration.

Notice that you should be careful with ${callsite}, since it introduces a huge performance overhead.

Notice that ${replace-newlines} is faster than ${replace} with regex.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文