How to turn off the logging done by the ASP.NET core framework

后端 未结 7 1287
梦如初夏
梦如初夏 2020-12-02 11:57

How do I turn off the logging done by ASP.NET for each request e.g.

INFO 09:38:41 User profile is available. Using \'C:\\Users\\xxxx xxxx\\AppData\\L

相关标签:
7条回答
  • 2020-12-02 12:45

    In and before ASP.NET 5 RC1 (now ASP.NET Core 1.0), you could do it via the logger factory, i.e.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        // completely disable logging or use one of the other levels, such as Error, Critical, Warning etc. 
        loggerFactory.MinimumLevel = LogLevel.None;
    }
    

    However, with the current branch (not released yet, but available via nightly builds), this has been removed. Now you need to pass the LogLevel per provider. Typically this is done via extension method.

    For the built in console logger, it would be loggerFactory.AddConsole(minimumLevel: LogLevel.Warning); for example.

    Since your logger provider is a custom one, you will have to configure it yourself. Take a look on how the console logger does it. It passes a delegate to the provider, that does the filtering.

    From GitHub Source:

    public static ILoggerFactory AddConsole(
        this ILoggerFactory factory,
        LogLevel minLevel,
        bool includeScopes)
    {
        factory.AddConsole((category, logLevel) => logLevel >= minLevel, includeScopes);
        return factory;
    }
    

    Of course instead of passing a delegate you can also directly set the log level of log4net.

    Update: To extend on what I've pointed out in the comments

    The ILoggerProvider is only a wrapper around the actual logging framework. In the simple case of ConsoleLoggerProvider, there is no framework as all behind it, just a simple Console.WriteLine call.

    In case of log4net, it's obvious from the example that logging can be enabled on a per level basis. This isn't possible with the .NET Core logger abstraction liked above, as the abstraction doesn't do any filtering.

    In a log4net ILoggerProvider one would simply route all log levels to the log4net net library and have it filter it.

    Based on the linked GitHub issue @haim770 created, you have the SourceContext for filtering and if log4net doesn't have a concept of SourceContext, you'll have to implement this in the provider. If it has a concept of SourceContext, then the provider needs to reroute/translate it into the structure log4net expects it.

    As you can see, the logger itself always stays unaware about internal specifics and implementation details of ASP.NET. The Log4NetProvider can't and shouldn't, because it's task is to translate/wrap around that api. Providers are just abstractions, so we don't have to leak implementation details into a library for example.

    0 讨论(0)
提交回复
热议问题