Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

ASP.NET Core: How Log Filtering Works

DZone's Guide to

ASP.NET Core: How Log Filtering Works

In this post we take a look at how logging in ASP.NET Core works, especially as it pertains to using separate environment profiles. Read on for some examples!

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

The logging infrastructure of ASP.NET Core supports log filtering that is useful when we need one logging configuration for the development environment and the another for the live environment, for example. This blog post introduces log filtering in ASP.NET Core through simple dummy controller code samples.

In ASP.NET Core loggers have names. When we ask for the logger we also specify the name of the logger. The example below shows a dummy controller that accepts the logger factory as a constructor argument and asks for the logger names as “My Logger.”


public class HomeController : Controller
{
    private readonly ILogger _logger;public HomeController(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger("My logger");
    }   }

The case of multiple loggers. One may ask why I injected the logger factory to the controller. This way my controller can support multiple loggers. Suppose the case where an application is using some external service. For applications, I want to keep logs at a warning level, but as external service, this can be very sensitive to input data, so I want this logger to run at information level.

Loggers are added to the application pipeline in the Configure() method of the start-up class.


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();// ...
}

By default, we don’t have any filters and all the logs we write to log targets. Default targets are console and debug.

Sample Controller

To play with log filtering we will use a simple dummy controller.


public class HomeController : Controller
{
    private readonly ILogger _logger;public HomeController(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger("My logger");
    }       public IActionResult Index()
    {
        _logger.LogInformation("This is info by my logger");
        _logger.LogCritical("This is critical by my logger");return View();
    }
}

When we run the application we will see the following output.

ASP.NET Core: No log filtering activated

Now let’s add filtering for “My log” in the start-up class.


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory
        .WithFilter(new FilterLoggerSettings
            {

                { "My logger", LogLevel.Warning }
            })
        .AddConsole(Configuration.GetSection("Logging"))
        .AddDebug();// ..
}

Now only warning level logs and above are allowed for “My logger.” Let’s run the application again and see the output.

ASP.NET Core: Log filtering activated

Although our dummy controller added two messages to logs – one informative and one critical – only the critical message is shown because all messages below the warning are ignored.

Wrapping up

Log filtering allows us to set minimal log levels for all the loggers our application uses. We can log messages with lower importance when debugging and we can go to live with a warning as a minimal log level. As filters are set by logger name then applications, where multiple loggers are used, can configure different loggers to log messages at different levels. Perhaps some loggers are configured to log only critical messages and for some components warning or information-level messages are logged. This kind of filtering support allows us to build very flexible logging for more complex applications, as well. 

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
asp.net core ,web dev ,logging ,log management

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}