Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

ASP.NET Core LogLevel configuration

Suggested Videos
Part 61 - Logging in ASP.NET Core | Text | Slides
Part 62 - Logging exceptions in ASP.NET Core | Text | Slides
Part 63 - Logging to file in asp.net core using nlog | Text | Slides

In this video we will discuss the significance of LogLevel configuration in ASP.NET Core.

LogLevel indicates the severity of the logged message. It can be any of the following. They are listed here from lowest to highest severity.
  • Trace = 0
  • Debug = 1
  • Information = 2
  • Warning = 3
  • Error = 4
  • Critical = 5
  • None = 6

LogLevel Enum

LogLevel enum is present in Microsoft.Extensions.Logging namespace


namespace Microsoft.Extensions.Logging
{
    public enum LogLevel
    {
        Trace = 0,
        Debug = 1,
        Information = 2,
        Warning = 3,
        Error = 4,
        Critical = 5,
        None = 6
    }
}

LogLevel in appsettings.json 

LogLevel setting in appsettings.json file is used to control how much log data is logged or displayed. 

{
  "Logging": {
    "LogLevel": {
      "Default": "Trace",
      "Microsoft": "Warning"
    }
  }
}

ILogger Methods

On the ILogger interface, we have log methods that include the log level in the method name. For example to log a TRACE message we use LogTrace() method. Similarly to log a WARNING message we use LogWarning() method. Notice, except for LogLevel = None, we have a corresponding method for every log level.

LogTrace()
LogDebug()
LogInformation()
LogWarning()
LogError()
LogCritical()

LogLevel Example

Consider the following Details() action in HomeController

public class HomeController : Controller
{
    public ViewResult Details(int? id)
    {
        logger.LogTrace("Trace Log");
        logger.LogDebug("Debug Log");
        logger.LogInformation("Information Log");
        logger.LogWarning("Warning Log");
        logger.LogError("Error Log");
        logger.LogCritical("Critical Log");

        // Rest of the code
    }
}

The following is the LogLevl configuration in appsettings.json file.

{
  "Logging": {
    "LogLevel": {
      "Default": "Trace",
      "Microsoft": "Warning"
    }
  }
}

The following Log output is displayed in the Debug Output window. Since we have set "Default": "Trace", we see everything from Trace level and higher. Since Trace is the lowest level we see all the logs.

EmployeeManagement.Controllers.HomeController:Trace: Trace Log
EmployeeManagement.Controllers.HomeController:Debug: Debug Log
EmployeeManagement.Controllers.HomeController:Information: Information Log
EmployeeManagement.Controllers.HomeController:Warning: Warning Log
EmployeeManagement.Controllers.HomeController:Error: Error Log
EmployeeManagement.Controllers.HomeController:Critical: Critical Log

However if you want WARNING and higher then set "Default": "Warning"

If you do not want anything logged set LogLevel to None. The integer value of LogLevel.None is 6, which is higher than all the other log levels. So nothing gets logged.

Log filtering in ASP.NET Core

Consider the following log statement

EmployeeManagement.Controllers.HomeController:Trace: My log message

EmployeeManagement.Controllers.HomeController is the LOG CATEGORY
Trace is the LOG LEVEL. Remeber log level can be (Trace, Debug, Information, etc...)

In simple terms, LOG CATEGORY is the fully qualified name of the class that logged the message. The log category is displayed as a string in the logged message so we can use it easily determine from which class the log came from. LOG CATEGORY is used to filter logs.

With the following LogLevel configuration, we see everything from Trace level and higher from the log category "EmployeeManagement.Controllers.HomeController". However, for the category "EmployeeManagement.Models.SQLEmployeeRepository" only Error level logs and higher are displayed.

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "EmployeeManagement.Controllers.HomeController": "Trace",
      "EmployeeManagement.Models.SQLEmployeeRepository": "Error",
      "Microsoft": "Warning"
    }
  }
}

The above LogLevel configuration applies to all logging providers. A logging provider is the component that stores or displays logs. For example, the Console logging provider displays logs on the console. Similarly, the Debug logging provider displays logs on the Debug window in Visual Studio.

Log Filtering by Log Category and by Logging Provider

It is also possible to filter logs by Provider and by Category. The following is an example. With the following configuration, for the Debug logging provider, Warning and higher level logs are logged and displayed for all the log categories. Where as for the rest of the logging providers, Trace and higher level logs are logged and displayed for all the log categories. 

{
  "Logging": {
    "Debug": {
      "LogLevel": {
        "Default": "Warning",
        "EmployeeManagement.Controllers.HomeController": "Warning",
        "EmployeeManagement.Models.SQLEmployeeRepository": "Warning",
        "Microsoft": "Warning"
      }
    },
    "LogLevel": {
      "Default": "Trace",
      "EmployeeManagement.Controllers.HomeController": "Trace",
      "EmployeeManagement.Models.SQLEmployeeRepository": "Trace",
      "Microsoft": "Trace"
    }
  }
}

LogLevel configuration in environment specific appsettings.json file

Please remember the configuration in environment specific appsettings.json file (for example appsettings.development.json) overrides the settings in appsettings.json file. Make sure the log level configuration in the environment specific appsettings.json file is what you really want, to avoid surprises.

asp.net core tutorial for beginners

ASP.NET Core LogLevel configuration - Slides





Logging to file in asp.net core using nlog

Suggested Videos
Part 60 - Global exception handling in asp.net core mvc | Text | Slides
Part 61 - Logging in ASP.NET Core | Text | Slides
Part 62 - Logging exceptions in ASP.NET Core | Text | Slides

In this video we will discuss how to log to a file in ASP.NET Core using NLog.

ASP.NET Core supports several third-party logging providers like the following
  • NLog
  • Serilog
  • elmah
  • Sentry
  • JSNLog

If we know how to work with one of the third-party logging providers, working with the other's is similar.

Using NLog in ASP.NET Core

Step 1 : Install NLog.Web.AspNetCore nuget package

Once the NLog package is installed, you will see the PackageReference included in the .csproj file

<PackageReference Include="NLog.Web.AspNetCore" Version="4.8.2" />


Step 2 : Create nlog.config file

Create nlog.config file in the root of your project. I have included the minimum configuration required.

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file  -->
    <target name="allfile" xsi:type="File"
            fileName="c:\DemoLogs\nlog-all-${shortdate}.log"/>
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />
  </rules>
</nlog>

To learn more about the nlog.config file please refer to the following github wiki page
https://github.com/NLog/NLog/wiki/Configuration-file

Step 3 : Enable copy to bin folder

Right click on nlog.config file in the Solution Explorer and select Properties. In the Properties window set 

Copy to Output Directory = Copy if newer

Step 4 : Enable NLog as one of the Logging Provider

In addition to using the default logging providers (i.e Console, Debug & EventSource), we also added NLog using the extension method AddNLog(). This method is in NLog.Extensions.Logging namespace.

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            logging.AddConsole();
            logging.AddDebug();
            logging.AddEventSourceLogger();
            // Enable NLog as one of the Logging Provider
            logging.AddNLog();
        })
        .UseStartup<Startup>();
}

If you want only NLog as the logging provider, clear all the logging providers and then add NLog.

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .ConfigureLogging((hostingContext, logging) =>
        {
            // Remove all the default logging providers
            logging.ClearProviders();
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            // Add NLog as the Logging Provider
            logging.AddNLog();
        })
       .UseStartup<Startup>();
}

Next video : Control what is logged using the LogLevel configuration setting.

asp.net core tutorial for beginners

Logging to file in asp.net core using nlog - Slides






Logging exceptions in ASP.NET Core

Suggested Videos
Part 59 - UseStatusCodePagesWithRedirects vs UseStatusCodePagesWithReExecute | Text | Slides
Part 60 - Global exception handling in asp.net core mvc | Text | Slides
Part 61 - Logging in ASP.NET Core | Text | Slides

In this video we will discuss how to log our own messages, warnings and exceptions using the ILogger interface provided by ASP.NET Core.


If there are exceptions, while users are using our application we need to log the exceptions somewhere. A developer can then review the exception log and provide a fix if required. Logging exceptions is required to know what exceptions are occurring on production server as the application is being used.


public class ErrorController : Controller
{
    private readonly ILogger<ErrorController> logger;

    // Inject ASP.NET Core ILogger service. Specify the Controller
    // Type as the generic parameter. This helps us identify later
    // which class or controller has logged the exception
    public ErrorController(ILogger<ErrorController> logger)
    {
        this.logger = logger;
    }

    [AllowAnonymous]
    [Route("Error")]
    public IActionResult Error()
    {
        // Retrieve the exception Details
        var exceptionHandlerPathFeature =
            HttpContext.Features.Get<IExceptionHandlerPathFeature>();
        // LogError() method logs the exception under Error category in the log
        logger.LogError($"The path {exceptionHandlerPathFeature.Path} " +
            $"threw an exception {exceptionHandlerPathFeature.Error}");

        return View("Error");
    }

    [Route("Error/{statusCode}")]
    public IActionResult HttpStatusCodeHandler(int statusCode)
    {
        var statusCodeResult =
            HttpContext.Features.Get<IStatusCodeReExecuteFeature>();

        switch (statusCode)
        {
            case 404:
                ViewBag.ErrorMessage = "Sorry, the resource could not be found";
                // LogWarning() method logs the message under
                // Warning category in the log
                logger.LogWarning($"404 error occured. Path = " +
                    $"{statusCodeResult.OriginalPath} and QueryString = " +
                    $"{statusCodeResult.OriginalQueryString}");
                break;
        }

        return View("NotFound");
    }
}

Logging Exceptions in ASP.NET Core

Two simple steps to log your own custom messages, warnings or exceptions

Inject an instance of ILogger where you need the logging functionality

The type of the class or controller into which ILogger is injected can be specified as the argument for the generic parameter of ILogger. We do this because, the fully qualified name of the class or the controller is then included in the log output as the log category. Log category is used to group the log messages.

Since we have specified the type of ErrorController as the generic argument for ILogger, the fully qualified name of ErrorController is also included in the log output below.

private readonly ILogger<ErrorController> logger;

public ErrorController(ILogger<ErrorController> logger)
{
    this.logger = logger;
}

LogError() method logs the exception under Error category. 

logger.LogError($"The path {exceptionHandlerPathFeature.Path} " +
    $"threw an exception {exceptionHandlerPathFeature.Error}");

Here is the log generated by LogError() method 

EmployeeManagement.Controllers.ErrorController:Error: The path /home/details/1 threw an exception System.Exception: Error in Details Controller
   at EmployeeManagement.Controllers.HomeController.Details(Nullable`1 id) in C:\Projects\EmployeeManagement\EmployeeManagement\Controllers\HomeController.cs:line 36
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.Invoke(HttpContext context)

LogWarning() method logs the message under Warning category. 

EmployeeManagement.Controllers.ErrorController:Warning: 404 error occured. Path = /foo/bar and QueryString = ?email=abc@gmail.com&abc=xyz

In a real world application we usually log the exceptions and warnings to a database table, event viewer or a file. We will discuss logging to a file in our next video.

asp.net core tutorial for beginners