Logging in .NET Core

In the world of software development, logging is an indispensable practice. It allows developers to track, debug, and maintain applications efficiently. In .NET Core, Microsoft has created a robust logging framework that integrates seamlessly with various components and third-party libraries. In this blog post, we'll dive deep into the world of logging in .NET Core, highlighting how to utilize its built-in features, how to configure logging providers, and how to implement your own custom logging feature.

1. Understanding the Logging Framework in .NET Core

Logging in .NET Core is unified, meaning the framework provides a consistent way to log messages irrespective of where your application is running. This means you can easily switch between different logging implementations without major code changes.

The core logging interfaces are contained within the Microsoft.Extensions.Logging namespace. At its core, the framework provides different log levels which include:

  • Trace
  • Debug
  • Information
  • Warning
  • Error
  • Critical

Using these log levels allows you to categorize the significance of the messages that you log.

2. Setting Up Logging

To utilize logging in your .NET Core application, you don’t have to configure much. Here’s how you can set it up in a typical .NET Core web application.

Example Application

Let's create a simple web application. Start by creating a new ASP.NET Core web application:

dotnet new webapp -n LoggingDemo cd LoggingDemo

Configuring Logging

By default, logging is already configured in a .NET Core web application. You can find the Program.cs file where the logging services are configured for you.

public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); }

As you can see, Host.CreateDefaultBuilder sets up logging (including console and debug output) automatically. However, you can customize logging as needed.

Injecting a Logger

To log messages in your application, you need to inject an ILogger<T> instance into your class. Here’s how you can do that in the IndexModel of your Razor Pages application:

using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace LoggingDemo.Pages { public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; public IndexModel(ILogger<IndexModel> logger) { _logger = logger; } public void OnGet() { _logger.LogInformation("Page loaded on Get request."); } } }

In this example, we inject the logger instance into the IndexModel constructor. We then log an information-level message whenever the page is accessed via a GET request.

Logging Different Levels

You can log messages at various levels based on your needs. Here’s an example of how to log multiple levels:

public void OnPost() { _logger.LogDebug("Debugging information for OnPost method."); _logger.LogInformation("Processing OnPost request."); try { // Imagine code that could throw an exception } catch (Exception ex) { _logger.LogError(ex, "An error occurred while processing OnPost."); } }

Console Output

When you run the application and access the home page, you should see the log messages outputted to the console. By default, the logging configuration sends messages at the Information level and above to the console.

3. Customizing Logging

.NET Core allows you to customize the logging behavior depending on the environment, add custom providers, or even filter the logs.

Configuring Log Levels

You can configure the minimum log level for different parts of your application in your appsettings.json:

{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "LoggingDemo": "Debug" } } }

This configuration sets the default log level to Information but allows more verbose logging for your specific application (i.e., LoggingDemo).

Adding Additional Logging Providers

If you want to store logs in a file or a database, you can add additional logging providers such as Serilog or NLog. Below is an example of how to integrate Serilog:

  1. Install the required NuGet packages:
dotnet add package Serilog.AspNetCore dotnet add package Serilog.Sinks.File
  1. Configure Serilog in Program.cs:
using Serilog; public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseSerilog((context, services, configuration) => configuration .ReadFrom.Configuration(context.Configuration) .Enrich.FromLogContext() .WriteTo.File("logs/Log-.txt", rollingInterval: RollingInterval.Day)) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
  1. Modify your appsettings.json to configure Serilog:
{ "Serilog": { "Using": [ "Serilog.Sinks.File" ], "MinimumLevel": "Information", "WriteTo": [ { "Name": "File", "Args": { "path": "logs/log-.txt", "rollingInterval": "Day" } } ] } }

Now your application can log messages to a file, which can be incredibly useful for long-term storage and analysis.

Conclusion and Best Practices

In summary, logging in .NET Core provides a powerful framework for capturing application details, performance metrics, and exceptions. By ensuring that you're using proper log levels and structuring your log messages effectively, you can make diagnostics and monitoring of your applications far more manageable and efficient. Use the built-in functionality to configure logging to suit your application needs, and don’t shy away from utilizing third-party providers to enhance your logging capabilities further.

Share now!

Like & Bookmark!