Logging Using Microsoft.Extensions.Logging

Logging is a critical part of building reliable, maintainable .NET applications. Whether you're developing a small API or a large enterprise system, proper logging helps you diagnose issues, track application behavior, and improve performance. One of the most widely used logging frameworks in modern .NET applications is Microsoft.Extensions.Logging.

This post provides a complete guide to logging using Microsoft.Extensions.Logging in C#, you’ll learn what Microsoft.Extensions.Logging is, how it works, how to configure it, and best practices for producing high-quality logs.

A Complete Guide to Logging Using Microsoft.Extensions.Logging

Getting Started

Modern .NET applications whether web APIs, background services, microservices, or desktop applications which require a reliable and flexible way to record events, diagnose issues, and monitor system behavior. That’s where Microsoft.Extensions.Logging comes in. It is a built-in logging framework introduced with .NET Core and now serves as the foundational logging abstraction across the entire .NET ecosystem.

What makes Microsoft.Extensions.Logging unique is its provider-based architecture, which separates the logging API from the underlying logging implementation. This means your application code always logs through a simple, consistent interface (ILogger), while you are free to plug in any logging provider you prefer—Console, Debug, EventLog, Serilog, NLog, Application Insights, or custom providers. This decoupling gives developers the freedom to evolve their logging strategy without changing core business logic.

Microsoft.Extensions.Logging also promotes structured logging, which helps produce machine-readable logs and makes debugging far more efficient, especially in distributed cloud environments. With first-class support for .NET’s dependency injection system, loggers are automatically created, scoped, and available throughout your application with minimal setup.

Because of its simplicity, extensibility, and deep integration with the .NET runtime, Microsoft.Extensions.Logging has become the standard way developers handle logging in modern .NET applications. Whether you’re building microservices on Kubernetes, serverless Azure Functions, or a simple console app, this framework provides everything you need for scalable, maintainable, and production-ready logging.

What Is Microsoft.Extensions.Logging?

Microsoft.Extensions.Logging is a lightweight, flexible logging abstraction built into .NET. Instead of tying your application to a single logging framework, it provides a common interface that works with many providers, including:

  • Console logging
  • Debug logging
  • Event Source/Event Log
  • Azure Application Insights
  • Serilog
  • NLog
  • Elasticsearch/Splunk providers
This approach lets you switch or combine logging systems without rewriting your application code.

Why Use Microsoft.Extensions.Logging?

Here are some key advantages:
  1. Built-in and Easy to Use: It’s included with .NET, making setup simple and consistent across projects.
  2. Extensible: You can plug in virtually any third-party logging provider.
  3. Structured Logging Support: Log values instead of concatenated strings, enabling richer search and filtering.
  4. Dependency Injection Integration: Works seamlessly with .NET’s DI container.
  5. Minimal Performance Overhead: Efficient log level checks and message formatting reduce runtime cost.

Add Microsoft.Extensions.Logging to a .NET Project

For ASP.NET Core, logging is already configured by default. For console or class library projects, you can add it manually:
  • Microsoft.Extensions.Logging
  • Microsoft.Extensions.Logging.Console

Basic Configuration and Usage Example In Console App

Program.cs
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
var host = Host.CreateDefaultBuilder(args)
.ConfigureServices((context, services) =>
{
  services.AddLogging(config =>
  {
    config.ClearProviders();
    config.AddConsole();
    config.SetMinimumLevel(LogLevel.Information);
    });
    })
    .Build();
    var logger = host.Services.GetRequiredService<ILogger<Program>>();
    logger.LogInformation("Application started");
    logger.LogWarning("This is a sample warning message");
    logger.LogError("An error occurred!");
    await host.RunAsync();

Supported Log Levels

  1. Trace: Very detailed debugging messages
  2. Debug: General debugging information
  3. Information: Normal application events
  4. Warning: Possible issues that are not yet errors
  5. Error: Recoverable errors
  6. Critical: Application crashes or serious failures
  7. None: Disable logging

Basic Logging Example in ASP.NET Core

public class WeatherService
{
  private readonly ILogger<WeatherService> _logger;
  public WeatherService(ILogger<WeatherService> logger)
  {
    _logger = logger;
  }
  public string GetForecast()
  {
    _logger.LogInformation("Fetching the weather forecast...");
    return "Sunny";
  }
}

Best Practices for Using Microsoft.Extensions.Logging

  1. Use Structured Logging Everywhere
      Avoid string concatenation:
      
      logger.LogInformation("User {UserId} logged in at {Time}", user.Id, DateTime.UtcNow);
      
      
  2. Log Exceptions Properly
      Always pass the exception object:
      
              
      logger.LogError(ex, "Failed to process payment");
      
      
  3. Avoid Logging Sensitive Data: Don’t log passwords, tokens, or private user information.
  4. Use Appropriate Log Levels: Prevent log overload and reduce storage costs.
  5. Combine Providers for Better Visibility
    For example:
    • Console for local development
    • Serilog file sink for auditing
    • Application Insights for cloud monitoring

Summary

Microsoft.Extensions.Logging is a powerful, flexible, and extensible logging framework that fits naturally into any .NET application. Its ability to integrate with third-party providers, support structured logging, and work seamlessly with dependency injection makes it the ideal choice for modern development.

Thanks

Kailash Chandra Behera

I am an IT professional with over 13 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies.

Previous Post Next Post

نموذج الاتصال