Skip to main content

Logging in .NET Core with an Item API

 

Logging is a fundamental aspect of any software application, providing insights into application behavior, performance, and errors. In .NET Core, logging is built into the framework, making it easy to implement consistent and configurable logging across your application. In this blog, we'll explore how to implement logging in a .NET Core application using an Item API as an example.

Why Logging is Important

  • Debugging: Helps in tracing and diagnosing issues.
  • Monitoring: Provides insights into application performance and user activities.
  • Auditing: Keeps track of important events and changes in the application.
  • Compliance: Assists in meeting regulatory requirements by maintaining records of critical operations.

Overview of .NET Core Logging

.NET Core includes a built-in logging framework that is both flexible and powerful. It supports logging to various outputs, including the console, files, and third-party systems like Azure Application Insights, Serilog, and more.

Key features of .NET Core logging:

  • Log Levels: Define the severity of the log messages (e.g., Information, Warning, Error).
  • Providers: Allow logging to different destinations (e.g., Console, Debug, EventLog).
  • Category-based Logging: Logs can be categorized, typically by class or namespace, to make it easier to filter and analyze logs.

Setting Up Logging in a .NET Core Application

Let’s implement logging in a .NET Core application using an Item API as an example.

1. Configuring Logging in Program.cs

In .NET Core, logging is typically configured in the Program.cs file. Here’s how to set up basic logging:

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

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();
                logging.AddEventLog(); // Optional, for Windows Event Log
                logging.SetMinimumLevel(LogLevel.Information);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

In this configuration:

  • ClearProviders() clears the default providers, allowing you to customize the logging setup.
  • AddConsole() adds logging to the console.
  • AddDebug() adds logging to the debug output (useful during development).
  • AddEventLog() adds logging to the Windows Event Log (optional and platform-specific).
  • SetMinimumLevel() sets the minimum log level. Only logs at this level or higher will be captured.

2. Using the Logger in Controllers

Once logging is configured, you can inject the ILogger service into your controllers and use it to log messages.

Example: Logging in the ItemsController
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Linq;

namespace ItemApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ItemsController : ControllerBase
    {
        private readonly ILogger<ItemsController> _logger;

        private static List<Item> Items = new List<Item>
        {
            new Item { Id = 1, Name = "Item1", Description = "First item" },
            new Item { Id = 2, Name = "Item2", Description = "Second item" },
        };

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

        [HttpGet]
        public ActionResult<IEnumerable<Item>> GetItems()
        {
            _logger.LogInformation("Fetching all items.");
            return Ok(Items);
        }

        [HttpGet("{id}")]
        public ActionResult<Item> GetItem(int id)
        {
            _logger.LogInformation("Fetching item with ID {ItemId}.", id);
            var item = Items.FirstOrDefault(i => i.Id == id);
            if (item == null)
            {
                _logger.LogWarning("Item with ID {ItemId} not found.", id);
                return NotFound();
            }
            return Ok(item);
        }

        [HttpPost]
        public ActionResult<Item> CreateItem(Item newItem)
        {
            _logger.LogInformation("Creating a new item with name {ItemName}.", newItem.Name);
            Items.Add(newItem);
            return CreatedAtAction(nameof(GetItem), new { id = newItem.Id }, newItem);
        }

        [HttpPut("{id}")]
        public IActionResult UpdateItem(int id, Item updatedItem)
        {
            _logger.LogInformation("Updating item with ID {ItemId}.", id);
            var item = Items.FirstOrDefault(i => i.Id == id);
            if (item == null)
            {
                _logger.LogWarning("Attempted to update item with ID {ItemId}, but it was not found.", id);
                return NotFound();
            }
            item.Name = updatedItem.Name;
            item.Description = updatedItem.Description;
            return NoContent();
        }

        [HttpDelete("{id}")]
        public IActionResult DeleteItem(int id)
        {
            _logger.LogInformation("Deleting item with ID {ItemId}.", id);
            var item = Items.FirstOrDefault(i => i.Id == id);
            if (item == null)
            {
                _logger.LogWarning("Attempted to delete item with ID {ItemId}, but it was not found.", id);
                return NotFound();
            }
            Items.Remove(item);
            return NoContent();
        }
    }
}

In this example:

  • The ILogger<ItemsController> is injected into the ItemsController class.
  • Various log messages are recorded at different stages of the CRUD operations:
    • Information level logs capture routine operations.
    • Warning level logs are used when an item is not found, which is useful for identifying potential issues.

3. Log Levels

Understanding log levels is crucial for effective logging:

  • Trace: Most detailed information, typically used for low-level debugging.
  • Debug: Information useful during development and debugging.
  • Information: General information about the application’s flow.
  • Warning: Indicates a potential issue or unexpected event.
  • Error: Indicates an error that prevents one or more functionalities from working.
  • Critical: Indicates a severe error that causes the application to crash or stop functioning.

By using appropriate log levels, you can filter logs and focus on the most critical issues.

4. Extending Logging with Third-Party Providers

.NET Core’s logging system can be extended with third-party providers such as Serilog, NLog, or log4net. These providers offer additional features like structured logging, log file management, and integration with cloud-based logging services.

Example: Integrating Serilog
Install the Serilog packages:
dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Sinks.File
Configure Serilog in Program.cs:
using Serilog;

public class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .WriteTo.Console()
            .WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Day)
            .CreateLogger();

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseSerilog() // Replacing default .NET Core logger with Serilog
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

With Serilog, logs are written to both the console and a file, with daily rolling logs.

Conclusion

Logging is a critical part of any application, providing the means to monitor, debug, and audit the application’s behavior. In this blog, we explored how to set up and use logging in a .NET Core application, focusing on an Item API as an example. We also looked at how to extend logging with third-party providers like Serilog for more advanced scenarios.

By implementing effective logging, you can gain valuable insights into your application, making it easier to maintain, debug, and optimize. Whether you're working on a small project or a large-scale system, logging will play a crucial role in ensuring your application runs smoothly and efficiently.

Comments

Popular posts from this blog

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...

Clean Architecture: What It Is and How It Differs from Microservices

In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...