简体   繁体   English

如何关闭由 ASP.NET 核心框架完成的日志记录

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

How do I turn off the logging done by ASP.NET for each request eg如何关闭 ASP.NET 为每个请求完成的日志记录,例如

INFO 09:38:41 User profile is available.信息 09:38:41 用户配置文件可用。 Using 'C:\Users\xxxx xxxx\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.使用“C:\Users\xxxx xxxx\AppData\Local\ASP.NET\DataProtection-Keys”作为密钥存储库和 Windows DPAPI 来加密静态密钥。
DEBUG 09:38:41 Hosting starting调试 09:38:41 托管开始
DEBUG 09:38:41 Hosting started调试 09:38:41 托管开始
INFO 09:38:41 Request starting HTTP/1.1 GET http://localhost:23369/ INFO 09:38:41 请求开始 HTTP/1.1 GET http://localhost:23369/
INFO 09:38:41 Request starting HTTP/1.1 DEBUG http://localhost:23369/ text/html DEBUG 09:38:41 DEBUG requests are not supported INFO 09:38:41 请求开始 HTTP/1.1 调试http://localhost:23369/ text/html 调试 09:38:41 不支持调试请求
DEBUG 09:38:41 The request path / does not match a supported file type DEBUG 09:38:41 请求路径 / 与支持的文件类型不匹配
DEBUG 09:38:41 Request successfully matched the route with name 'default' and template '{controller=Home}/{action=Index}/{id?}'.调试 09:38:41 请求成功匹配名称为“默认”和模板“{controller=Home}/{action=Index}/{id?}”的路由。 DEBUG 09:38:41 Request successfully matched the route with name 'default' and template '{controller=Home}/{action=Index}/{id?}'.调试 09:38:41 请求成功匹配名称为“默认”和模板“{controller=Home}/{action=Index}/{id?}”的路由。 DEBUG 09:38:41 Executing action Forums.Controllers.HomeController.Index调试 09:38:41 执行操作 Forums.Controllers.HomeController.Index
DEBUG 09:38:41 Executing action Forums.Controllers.HomeController.Index调试 09:38:41 执行操作 Forums.Controllers.HomeController.Index
INFO 09:38:41 Executing action method Forums.Controllers.HomeController.Index with arguments () - ModelState is Valid'信息 09:38:41 使用参数 () 执行操作方法 Forums.Controllers.HomeController.Index - ModelState 有效'
INFO 09:38:41 Executing action method Forums.Controllers.HomeController.Index INFO 09:38:41 执行动作方法 Forums.Controllers.HomeController.Index
.. ..

I couldn't find yet how I can turn this logging off...我还找不到如何关闭此注销...

This is my Configure method in the Startup class:这是我在Startup类中的Configure方法:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddProvider(new Log4NetProvider());

    if (env.IsDevelopment())
    {
        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");

        // For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
        try
        {
            using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
                .CreateScope())
            {
                serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
                     .Database.Migrate();
            }
        }
        catch { }
    }

    app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

    app.UseStaticFiles();

    app.UseIdentity();

    // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

And this is my project.json file:这是我的 project.json 文件:

"dependencies": {
  "EntityFramework.Commands": "7.0.0-rc1-final",
  "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
  "log4net": "2.0.5",
  "Microsoft.AspNet.Authentication.Cookies": "1.0.0-rc1-final",
  "Microsoft.AspNet.Diagnostics.Entity": "7.0.0-rc1-final",
  "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final",
  "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
  "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
  "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
  "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
  "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
  "Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
  "Microsoft.Extensions.CodeGenerators.Mvc": "1.0.0-rc1-final",
  "Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
  "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
  "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
  "Microsoft.Extensions.Logging": "1.0.0-rc1-final",
  "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final"
},

"commands": {
  "web": "Microsoft.AspNet.Server.Kestrel",
  "ef": "EntityFramework.Commands"
},

"frameworks": {
  "dnx451": { }
},

Update:更新:
My log4net provider was taken from here我的 log4net 提供程序取自这里

I'm not sure if I am missing something but don't you just want to raise the log level for the Microsoft logs?我不确定我是否遗漏了什么,但您不只是想提高 Microsoft 日志的日志级别吗?

Edit appsettings.json (assumes .AddJsonFile("appsettings.json", ...) )编辑appsettings.json (假设.AddJsonFile("appsettings.json", ...)

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Trace",
      "System": "Information",
      "Microsoft": "Information"

To

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Trace",
      "System": "Information",
      "Microsoft": "None"

Or the same modification via environment variables (assumes .AddEnvironmentVariables() )或通过环境变量进行相同的修改(假设.AddEnvironmentVariables()

Logging:LogLevel:Microsoft=None

You can also be more specific, the following reduces most entries but leaves Microsoft.AspNetCore.Hosting.Internal.WebHost at Information .您还可以更具体地说,以下内容减少了大多数条目,但将Microsoft.AspNetCore.Hosting.Internal.WebHostInformation中。

"Microsoft": "Information",  
"Microsoft.AspNetCore.Mvc.Internal": "Warning",
"Microsoft.AspNetCore.Authentication":  "Warning"

Appologies if this doesn't work for log4net如果这不适用于log4net

What have really worked for me was adding this in ASP.NET Core 2.0 project's Startup.cs file:真正对我有用的是在 ASP.NET Core 2.0 项目的Startup.cs文件中添加它:

using Microsoft.Extensions.Logging;
public void ConfigureServices(IServiceCollection services)
{
    .
    .
    .

    services.AddLogging(
    builder =>
    {
        builder.AddFilter("Microsoft", LogLevel.Warning)
               .AddFilter("System", LogLevel.Warning)
               .AddFilter("NToastNotify", LogLevel.Warning)
               .AddConsole();
    });
}

This way you'll only get Warning level logs for logging info starting with the filters passed to builder.AddFilter .这样,您将只获得从传递给builder.AddFilter的过滤器开始记录信息的警告级别日志。

My log4net.log file now doesn't show that huge amount of INFO logging spit by Microsoft and others.我的 log4net.log 文件现在没有显示 Microsoft 和其他公司吐出的大量INFO日志记录。

More info here @ Microsoft Docs: Log filtering更多信息在这里@Microsoft Docs: 日志过滤

If you're using Serilog to do your .NET Core logging, you can update your appsettings.json file to set the log levels like so:如果您使用 Serilog 进行 .NET Core 日志记录,则可以更新 appsettings.json 文件以设置日志级别,如下所示:

"Serilog": {
  "MinimumLevel": {
    "Default": "Verbose",
    "Override": {
      "Microsoft": "Error",
      "System": "Error"
    }
  },
  "Properties": {
    "Application": "your-app"
  }
}

This allows you to only log errors from System/Microsoft while logging everything else as you'd like.这允许您只记录来自 System/Microsoft 的错误,同时根据需要记录其他所有内容。

In ASP.NET Core version 3, you can clear the existing log providers in the ConfigureServices function:在 ASP.NET Core 版本 3 中,您可以在 ConfigureServices 函数中清除现有的日志提供程序:

public void ConfigureServices(IServiceCollection services) {
    //Do everything else...
    services.AddLogging(c => c.ClearProviders());
}

Since the new logging infrastructure is being used (by design) by asp.net itself (as well as other vendor code), it's up to the ILoggerProvider implementation to decide whether it wants to log that source or not.由于 asp.net 本身(以及其他供应商代码)正在(按设计)使用新的日志记录基础结构,因此由ILoggerProvider实现决定是否要记录该源。

Here's a revised implementation for log4net that adds a basic source filtering:这是log4net的一个修改后的实现,它添加了一个基本的源过滤:

public class Log4NetProvider : ILoggerProvider
{
    private static readonly NoopLogger _noopLogger = new NoopLogger();
    private readonly Func<string, bool> _sourceFilterFunc;
    private readonly ConcurrentDictionary<string, Log4NetLogger> _loggers = new ConcurrentDictionary<string, Log4NetLogger>();

    public Log4NetProvider(Func<string, bool> sourceFilterFunc = null)
    {
        _sourceFilterFunc = sourceFilterFunc != null ? sourceFilterFunc : x => true;
    }

    public ILogger CreateLogger(string name)
    {
        if (!_sourceFilterFunc(name))
            return _noopLogger;

        return _loggers.GetOrAdd(name, x => new Log4NetLogger(name));
    }

    public void Dispose()
    {
        _loggers.Clear();
    }

    private class NoopLogger : ILogger
    {
        public IDisposable BeginScopeImpl(object state)
        {
            return null;
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            return false;
        }

        public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter)
        {
        }
    }
}

And the Log4NetAspExtensions :Log4NetAspExtensions

public static void ConfigureLog4Net(this IApplicationEnvironment appEnv, string configFileRelativePath)
{
    GlobalContext.Properties["appRoot"] = appEnv.ApplicationBasePath;
    XmlConfigurator.Configure(new FileInfo(Path.Combine(appEnv.ApplicationBasePath, configFileRelativePath)));
}

public static void AddLog4Net(this ILoggerFactory loggerFactory, Func<string, bool> sourceFilterFunc = null)
{
    loggerFactory.AddProvider(new Log4NetProvider(sourceFilterFunc));
}

public static void AddLog4Net(this ILoggerFactory loggerFactory)
{
    loggerFactory.AddLog4Net(null);
}

Possible usage (in Startup.cs ):可能的用法(在Startup.cs中):

public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv, ILoggerFactory loggerFactory)
{
    appEnv.ConfigureLog4Net("log4net.xml");

    loggerFactory.AddLog4Net(x => !x.StartsWith("Microsoft."));
}

Setting Logging.LogLevel in appsettings.json for the key Microsoft was not enough.appsettings.json中为Microsoft键设置 Logging.LogLevel 是不够的。 I had to specifically set the following keys specifically, eg:我必须专门设置以下键,例如:

"Microsoft.Hosting.Lifetime": "Warning",
"Microsoft.AspNetCore.Hosting.Diagnostics": "Warning",
"Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware": "Warning"

But as an alternative using a key with a wildcard, eg Microsoft.* , worked.但作为替代方案,使用带有通配符的密钥,例如Microsoft.* ,工作。 So I ended up with:所以我最终得到:

{
  "Logging": {
    "LogLevel": {
      "Default":     "Warning",
      "Microsoft.*": "Warning" 
  }
  ...
}

In and before ASP.NET 5 RC1 (now ASP.NET Core 1.0), you could do it via the logger factory, ie在 ASP.NET 5 RC1(现为 ASP.NET Core 1.0)之前及之前,您可以通过记录器工厂来实现,即

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.现在您需要为每个提供者传递LogLevel Typically this is done via extension method.通常这是通过扩展方法完成的。

For the built in console logger, it would be loggerFactory.AddConsole(minimumLevel: LogLevel.Warning);对于内置的控制台记录器,它将是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 :来自GitHub 源代码

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.当然你也可以直接设置 log4net 的日志级别,而不是传递委托。

Update : To extend on what I've pointed out in the comments更新:扩展我在评论中指出的内容

The ILoggerProvider is only a wrapper around the actual logging framework. ILoggerProvider只是实际日志框架的包装器。 In the simple case of ConsoleLoggerProvider , there is no framework as all behind it, just a simple Console.WriteLine call.ConsoleLoggerProvider的简单案例中,它背后没有框架,只是一个简单的Console.WriteLine调用。

In case of log4net, it's obvious from the example that logging can be enabled on a per level basis.在 log4net 的情况下,从示例中可以明显看出可以在每个级别上启用日志记录。 This isn't possible with the .NET Core logger abstraction liked above, as the abstraction doesn't do any filtering.这对于上面喜欢的 .NET Core 记录器抽象是不可能的,因为抽象不做任何过滤。

In a log4net ILoggerProvider one would simply route all log levels to the log4net net library and have it filter it.在 log4net ILoggerProvider中,只需将所有日志级别路由到 log4net 网络库并让它过滤它。

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.根据创建的链接 GitHub 问题@haim770,您有用于过滤的 SourceContext,如果 log4net 没有 SourceContext 的概念,您必须在提供程序中实现它。 If it has a concept of SourceContext, then the provider needs to reroute/translate it into the structure log4net expects it.如果它有 SourceContext 的概念,那么提供者需要将其重新路由/翻译成 log4net 期望的结构。

As you can see, the logger itself always stays unaware about internal specifics and implementation details of ASP.NET.如您所见,记录器本身始终不了解 ASP.NET 的内部细节和实现细节。 The Log4NetProvider can't and shouldn't, because it's task is to translate/wrap around that api. Log4NetProvider不能也不应该,因为它的任务是翻译/环绕该 api。 Providers are just abstractions, so we don't have to leak implementation details into a library for example.提供者只是抽象,因此我们不必将实现细节泄漏到例如库中。

With Serilog, I found it was a simple case of specifying an override for Microsoft components when defining the logger configuration:使用 Serilog,我发现在定义记录器配置时为 Microsoft 组件指定覆盖是一个简单的案例:

Log.Logger = new LoggerConfiguration()
    ... // Other config
    .MinimumLevel.Information()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
    ... // Other config
    .CreateLogger();

This allowed me to only log Warning level or above entries for Microsoft components, but Information and above for my own components.这使我只能为 Microsoft 组件记录Warning级别或更高级别的条目,而为我自己的组件记录Information及更高级别。

Set these two configuration flags in the startup.cs在 startup.cs 中设置这两个配置标志

        services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>((module, options) =>
        {
            options.EnableDependencyTrackingTelemetryModule = false;
            options.EnableRequestTrackingTelemetryModule = false;
        });

then you will only see the trace telemetry type in the logs那么您只会在日志中看到跟踪遥测类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何关闭 ASP.NET 和实体框架为每个请求完成的默认日志记录? - How do I turn off the default logging done by ASP.NET and Entity Framework for each request? 使用 serilog 关闭 asp.net 核心 2.2 中的 mvc 请求日志记录 - Turn off mvc request logging in asp.net core 2.2 with serilog 关闭asp.net mvc core 2 OpenIdConnect中的AutomaticChallenge - Turn off AutomaticChallenge in asp.net mvc core 2 OpenIdConnect 如何在 JSON 响应 ASP.NET Core 中关闭或处理驼峰式? - How to turn off or handle camelCasing in JSON response ASP.NET Core? ASP.NET Core 2.2 实体框架日志记录 - ASP.NET Core 2.2 Entity Framework Logging 如何关闭 ASP.NET ZERO 的 JS 捆绑 - How to turn off JS Bundling for ASP.NET ZERO 如何关闭asp.net和C#的视图 - How to turn off views asp.net and C# 如何在ASP.NET Core Web Api中完成版本控制 - How can versioning be done in ASP.NET Core Web Api 在ASP.NET Core中分离应用程序级日志记录和框架级日志记录 - Separating application level logging and framework level logging in ASP.NET Core 如何关闭日志级别和类别 output 中的 .NET Core 日志记录到 AWS CloudWatch? - How can I turn off log level & category output in .NET Core logging to AWS CloudWatch?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM