Warm tip: This article is reproduced from serverfault.com, please click

How to filter aspnet core logs?

发布于 2018-12-09 22:54:59

The following boilerplate, Microsoft-provided C# code for ASP.NET Core 2.1 should prevent merely informational logs from being written. But it doesn't.

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            var env = hostingContext.HostingEnvironment;
            config.AddEnvironmentVariables();
        })
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddConsole();
            logging.AddDebug();
            logging.AddEventSourceLogger();
        })
        .ConfigureLogging(logging => logging.SetMinimumLevel(LogLevel.Warning))
        .UseStartup<Startup>();

I still see messages like:

MyApp> info: Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker[2]

and

Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker:Information: Executed action /Index in 11.2286ms

I have deliberately removed (for now) the code to call AppSettings.json. Why am I still seeing information-severity log items?

Questioner
Scott Pendleton
Viewed
0
Xueli Chen 2018-12-11 19:05:20

Try the following change in your code, set the category of the first AddFilter is null

 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;
                config.AddEnvironmentVariables();
            })
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConsole();
                logging.AddFilter(null, LogLevel.Warning);

            })
            .UseStartup<Startup>()
            .ConfigureLogging(logging => logging.AddFilter("Microsoft", LogLevel.Warning));

Add logWarning to test in Home/Index

 private readonly ILogger _logger;
    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;
    }
    public void OnGet()
    {
        _logger.LogInformation("Log Information");
        _logger.LogWarning("Log Warning");
    }

The screenshot of result

enter image description here