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...

.NET 10: Your Ultimate Guide to the Coolest New Features (with Real-World Goodies!)

 Hey .NET warriors! 🤓 Are you ready to explore the latest and greatest features that .NET 10 and C# 14 bring to the table? Whether you're a seasoned developer or just starting out, this guide will show you how .NET 10 makes your apps faster, safer, and more productive — with real-world examples to boot! So grab your coffee ☕️ and let’s dive into the awesome . 💪 1️⃣ JIT Compiler Superpowers — Lightning-Fast Apps .NET 10 is all about speed . The Just-In-Time (JIT) compiler has been turbocharged with: Stack Allocation for Small Arrays 🗂️ Think fewer heap allocations, less garbage collection, and blazing-fast performance . Better Code Layout 🔥 Hot code paths are now smarter, meaning faster method calls and fewer CPU cache misses. 💡 Why you care: Your APIs, desktop apps, and services now respond quicker — giving users a snappy experience . 2️⃣ Say Hello to C# 14 — More Power in Your Syntax .NET 10 ships with C# 14 , and it’s packed with developer goodies: Field-Bac...

Optional Parameters in C# — Writing Flexible and Clean Methods

Hello, .NET developers! 👋 How often have you created multiple method overloads just to handle slightly different cases? Maybe one method accepts two parameters, another three, and one more adds a flag for debugging? That’s a lot of code duplication for something that can be solved beautifully with optional parameters . Optional parameters in C# let you define default values for method arguments. When a caller doesn’t pass a value, the compiler automatically substitutes the default. This feature helps keep your APIs simple, readable, and maintainable. 🎥 Explore more on YouTube : DotNet Full Stack Dev Understanding Optional Parameters Optional parameters are defined by assigning default values in the method signature. When calling the method, you can omit those parameters if you’re okay with the defaults. Example public class Logger { public void Log(string message, string level = "INFO", bool writeToFile = false) ...