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

103,241

Solution 1

I'm not sure if I am missing something but don't you just want to raise the log level for the Microsoft logs?

Edit appsettings.json (assumes .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())

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": "Information",  
"Microsoft.AspNetCore.Mvc.Internal": "Warning",
"Microsoft.AspNetCore.Authentication":  "Warning"

Appologies if this doesn't work for log4net

Solution 2

What have really worked for me was adding this in ASP.NET Core 2.0 project's Startup.cs file:

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.

My log4net.log file now doesn't show that huge amount of INFO logging spit by Microsoft and others.

More info here @ Microsoft Docs: Log filtering

Solution 3

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": {
  "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.

Solution 4

In ASP.NET Core version 3, you can clear the existing log providers in the ConfigureServices function:

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

Solution 5

Setting Logging.LogLevel in appsettings.json for the key Microsoft was not enough. I had to specifically set the following keys specifically, e.g.:

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

But as an alternative using a key with a wildcard, e.g. Microsoft.*, worked. So I ended up with:

{
  "Logging": {
    "LogLevel": {
      "Default":     "Warning",
      "Microsoft.*": "Warning" 
  }
  ...
}
Share:
103,241
gdoron is supporting Monica
Author by

gdoron is supporting Monica

Doron Grinzaig

Updated on June 30, 2021

Comments

  • gdoron is supporting Monica
    gdoron is supporting Monica almost 3 years

    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\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
    DEBUG 09:38:41 Hosting starting
    DEBUG 09:38:41 Hosting started
    INFO 09:38:41 Request starting 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
    DEBUG 09:38:41 The request path / does not match a supported file type
    DEBUG 09:38:41 Request successfully matched the route with name 'default' and template '{controller=Home}/{action=Index}/{id?}'. DEBUG 09:38:41 Request successfully matched the route with name 'default' and template '{controller=Home}/{action=Index}/{id?}'. DEBUG 09:38:41 Executing action Forums.Controllers.HomeController.Index
    DEBUG 09:38:41 Executing action Forums.Controllers.HomeController.Index
    INFO 09:38:41 Executing action method Forums.Controllers.HomeController.Index with arguments () - ModelState is Valid'
    INFO 09:38:41 Executing action method 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:

    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:

    "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

  • gdoron is supporting Monica
    gdoron is supporting Monica about 8 years
    This is not what I'm after. I do not want to change the logging level globally in my application, I just wish to turn off the ASP.NET logging which is tunneled through my provider. I deep dived into the source code, it's not a trivial task, I'm unhappy :(
  • Tseng
    Tseng about 8 years
    @gdoron: All logging requests will be tunneled to every registered ILoggingProvider. It's the task of the provider/logger to do the log level filtering. That's why MinimumLevel was removed and the now can only be set on per provider level
  • gdoron is supporting Monica
    gdoron is supporting Monica about 8 years
    I understand that all the loggers should get all logging requests. I just don't understand why there's no way to set ASP.NET itself logging to a specific level, why do I need my logging provider to be aware of all of the components, to me it seems like bad design.
  • Tseng
    Tseng about 8 years
    @gdoron: Because it's the providers responsibility. An application can have more than one provider, setting it globally may make no sense. For example you may have a ConsoleLogger for development, where you want to have all information, including "Trace" and "Debug" Level, on the other side you may want to have file logging which only logs Errors and Criticals. ASP.NET Core is made to be very flexible and be easy to add or remove a certain feature and for that reason. All you need to do is set your logger to Warning Level or higher, then Debug, Information and Trace level won't be logged
  • Tseng
    Tseng about 8 years
    Also your logger provider doesn't need to be aware of any components, just about the debug level, as this is what tells the logger what kind of messages it should log and which not.
  • gdoron is supporting Monica
    gdoron is supporting Monica about 8 years
    This is not true, see this example from Microsoft samples, the logger is aware of all of the components. If I set my logger to "information" level, it will ignore debug level of ASP.NET as well as of my application level, a thing I do not want. I can understand the reason for this design, it just makes things much more complicated for most users.
  • Tseng
    Tseng about 8 years
    @gdoron: I think you are a confusing two things here: ILoggerProvider and the logger itself. In most cases, the ILoggerProvider wraps the actual logger around this interface and handles/translates ASP.NET Core related types (like LogLevel) to your logging library types, also also does the rough filtering. In the example, the ConsoleLogger is so simple, that it does both in one class. All the provider has to do is receive the log messages from the application, apply log level and source filter, and if it passes it, call the log method of your log library
  • Tseng
    Tseng about 8 years
    The actual logger, that is called from ILoggerProvider can do the actual logging (i.e. broadcast it via message bus, write it to the database, to a file, or event log like in windows etc). The actual logger never knows about how the log system works or details about it. The provider however, may need to know this to do the filtering and the ILoggerProvider is tied to the Logger abstractions of ASP.NET Core (since it depends on that interface to be plugged in in the logging pipeline)
  • Alyce
    Alyce over 7 years
    I couldn't get this to work with Serilog, but it did work for the console logging when running the app on the command line (i.e. dotnet run).
  • scott
    scott about 7 years
    This config file is only used to control console logging unfortunately. loggerFactory.AddConsole(Configuration.GetSection("Logging")‌​);
  • Mani Gandham
    Mani Gandham almost 7 years
    @Alyce Serilog has filtering available as well: new LoggerConfiguration().Filter.ByExcluding(Matching.FromSource‌​("Microsoft")) - see this for more info: stackoverflow.com/questions/38760381/…
  • Mani Gandham
    Mani Gandham almost 7 years
    You can also override so that only events above a certain level are logged for a specific source by using new LoggerConfiguration().MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
  • timeshift
    timeshift over 6 years
    I can't find the correct answer anywhere here, the correct one should be: loggerFactory.WithFilter(new FilterLoggerSettings { { "Microsoft", LogLevel.Warning }, { "System", LogLevel.Warning }, { "MyOwnProject", LogLevel.Debug } }) .AddConsole(Configuration.GetSection("Logging")) .AddDebug();
  • Mike Gledhill
    Mike Gledhill almost 6 years
    Ooooooooh, that's what those strange "LogLevels" for Microsoft and System were for... I didn't realise that. Excellent tip.
  • Sunny Okoro Awa
    Sunny Okoro Awa over 5 years
    This did the job for me. Thank You.
  • DharmaTurtle
    DharmaTurtle over 4 years
    For noobs like me, add using Microsoft.Extensions.Logging;
  • jhhwilliams
    jhhwilliams over 4 years
    If it isn't working, check your appsettings.Development.json. From the docs: If levels are specified in Logging.{providername}.LogLevel, they override anything set in Logging.LogLevel.
  • korulis
    korulis over 4 years
    Also, you can use Logging__LogLevel__Microsoft=None syntax instead of Logging:LogLevel:Microsoft=None in environment variable setup. Also, you can not write breviations, like, Warn or Info, you must write the full level names, like, Information or Warning.
  • korulis
    korulis over 4 years
    Actually, in Linux Logging:LogLevel:Microsoft=None might not even work. I just have just experienced that myself.
  • rdelgado-incinc
    rdelgado-incinc over 3 years
    This did not work for me. ASP.NET core was still logging :'(
  • Stack Em Up
    Stack Em Up over 2 years
    Thank you. Yes, if you use WebHost.CreateDefaultBuilder(args).UseStartup<Startup>() then you should configure logs in Startup.cs
  • Haukland
    Haukland about 2 years
    This worked in .NET 6