Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Logging

Introduction

Logging is an essential feature for diagnosing and troubleshooting issues in an application. ASP.NET Core provides a flexible logging framework that allows developers to create and manage log messages in their applications. This tutorial will guide you through the process of setting up and using logging in an ASP.NET Core application.

Setting Up the Development Environment

Before you start, ensure you have the following installed:

  • Visual Studio 2019 or later
  • .NET Core SDK

Example: Installing .NET Core SDK

https://dotnet.microsoft.com/download/dotnet-core

Creating a New ASP.NET Core Project

Open Visual Studio and create a new project:

  • Select "Create a new project".
  • Choose "ASP.NET Core Web Application" and click "Next".
  • Name your project and select the location to save it. Click "Create".
  • In the "Create a new ASP.NET Core Web Application" dialog, select "Web Application (Model-View-Controller)" and click "Create".

Setting Up Logging

ASP.NET Core includes a built-in logging framework that works with various logging providers. By default, it includes providers for console, debug, and event source logging. Additional providers like Serilog, NLog, and others can be added as needed.

Example: Configuring Logging in Program.cs

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.AddConsole();
                logging.AddDebug();
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

Using the Logger

To use the logger in your application, inject an ILogger instance into your classes. You can then use this logger to create log messages.

Example: Using ILogger in a Controller

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        _logger.LogInformation("Index action method called.");
        return View();
    }

    public IActionResult Privacy()
    {
        _logger.LogWarning("Privacy action method called.");
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        _logger.LogError("Error action method called.");
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}

Logging Levels

ASP.NET Core supports different logging levels to categorize the importance and severity of log messages:

  • Trace: Detailed information, typically of interest only when diagnosing problems.
  • Debug: Information useful to developers for debugging the application.
  • Information: Informational messages that highlight the progress of the application.
  • Warning: Potentially harmful situations or warnings.
  • Error: Error events that might still allow the application to continue running.
  • Critical: Severe error events that lead the application to abort.

Configuring Logging Levels

You can configure logging levels in the appsettings.json file:

Example: Configuring Logging Levels in appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Using Third-Party Logging Providers

While the built-in logging providers are sufficient for many applications, you can also use third-party logging providers like Serilog, NLog, and Log4Net for more advanced scenarios.

Example: Using Serilog

public class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .WriteTo.Console()
            .CreateLogger();

        try
        {
            Log.Information("Starting up the application");
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Application start-up failed");
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseSerilog()
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

Conclusion

Congratulations! You have learned the basics of logging in ASP.NET Core. This tutorial covered setting up a new project, configuring logging providers, using the logger, understanding logging levels, configuring logging levels, and using third-party logging providers. From here, you can further explore more advanced logging scenarios like structured logging, log filtering, and integrating with logging platforms like Splunk or ELK stack.