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