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

Logging exceptions in ASP.NET Core

Suggested Videos
Part 59 - UseStatusCodePagesWithRedirects vs UseStatusCodePagesWithReExecute | Text | Slides
Part 60 - Global exception handling in 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;

    public IActionResult Error()
        // Retrieve the exception Details
        var exceptionHandlerPathFeature =
        // 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");

    public IActionResult HttpStatusCodeHandler(int statusCode)
        var statusCodeResult =

        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 = " +

        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 = ?

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. core tutorial for beginners

No comments:

Post a Comment

It would be great if you can help share these free resources