Mastering Logging in .NET Core Web API – With Hands-On Examples!
Logging in .NET Core Web API
Logging is
the backbone of every well-built application. It helps track issues, debug
errors, and monitor performance effortlessly. Whether
you’re a beginner or an experienced developer, a well-structured
logging system can save hours of debugging time.
1. Setting Up Logging in .NET Core
Web API
Step 1: Create a .NET Core Web API
Project
Open a terminal and run:
dotnet new webapi -n LoggingDemo
cd LoggingDemo
Step 2: Configure Logging in
Program.cs
In .NET 6+, logging is
configured inside Program.cs like this:
var builder =
WebApplication.CreateBuilder(args);
//Configure built-in logging
builder.Logging.ClearProviders(); //
Remove default logging providers
builder.Logging.AddConsole(); //
Log to the console
builder.Logging.AddDebug(); //
Log to Visual Studio Output Window
var app = builder.Build();
app.MapControllers();
app.Run();
Now, logs will appear in the
console & Debug output!
2. Implementing Logging in
Controllers
In ASP.NET Core,
ILogger<T> is injected into controllers to enable logging.
Example: Add Logging in a
Controller
using Microsoft.AspNetCore.Mvc;
using
Microsoft.Extensions.Logging;
[ApiController]
[Route("[controller]")]
public class
WeatherForecastController : ControllerBase
{
private
readonly ILogger<WeatherForecastController> _logger;
public
WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger
= logger;
}
[HttpGet]
public
IActionResult Get()
{
_logger.LogInformation("WeatherForecastController.Get()
called");
try
{
throw
new Exception("Simulated exception!");
}
catch
(Exception ex)
{
_logger.LogError(ex,
"Error occurred while fetching data!");
}
return
Ok(new { Message = "Check logs for details." });
}
}
Logging Levels Explained
Log Level |
Purpose |
LogTrace() |
Most detailed logs (for debugging only) |
LogDebug() |
Debugging logs (useful for local
development) |
LogInformation() |
General application flow logs |
LogWarning() |
Logs potential issues that need attention |
LogError() |
Captures exceptions & errors |
LogCritical() |
Logs serious system failures |
Run the API and check the logs in
the console!
3. Configuring Logging in
appsettings.json
By default, .NET Core allows you
to configure logging in appsettings.json.
{
"Logging": {
"LogLevel":
{
"Default":
"Information",
"Microsoft":
"Warning",
"Microsoft.Hosting.Lifetime":
"Information"
}
}
}
What Does This Mean?
Default: Logs
Information and higher
Microsoft: Logs only Warning and higher (reduces clutter)
4. Logging to a File with Serilog
Although built-in logging is
powerful, Serilog makes logging structured,
persistent, and flexible.
Step 1: Install Serilog Packages
Run the following command:
dotnet add package
Serilog.AspNetCore
dotnet add package
Serilog.Sinks.File
Step 2: Configure Serilog in
Program.cs
Modify Program.cs to use Serilog:
using Serilog;
var builder =
WebApplication.CreateBuilder(args);
// Configure Serilog for
structured logging
Log.Logger = new
LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File("logs/log.txt",
rollingInterval: RollingInterval.Day)
.CreateLogger();
builder.Host.UseSerilog();
var app = builder.Build();
app.MapControllers();
app.Run();
Now, all logs will be saved in
logs/log.txt automatically!
5. Structured Logging with Serilog
Instead of plain text logs, structured
logs make it easier to query and analyze data.
_logger.LogInformation("User
{UserId} logged in at {Time}", userId, DateTime.UtcNow);
Output (JSON Format)
{
"Message":
"User 123 logged in at 2025-03-18T12:00:00Z",
"UserId":
123,
"Time":
"2025-03-18T12:00:00Z"
}
Now, logs are searchable and
filterable in tools like Seq or ELK Stack!
6. Centralized Logging with Seq
(Real-Time Monitoring)
For real-time log
monitoring, Seq is an excellent choice!
Step 1: Install Seq Sink
Run the command:
dotnet add package
Serilog.Sinks.Seq
Step 2: Modify Program.cs
Log.Logger = new
LoggerConfiguration()
.WriteTo.Console()
.WriteTo.Seq("http://localhost:5341")
.CreateLogger();
Step 3: Start Seq with Docker
docker run --name seq -d -p
5341:80 datalust/seq
Now, all logs can be viewed in an
interactive UI in Seq!
Conclusion
You’ve
just built a fully functional logging system for your .NET Core Web API!
· Built-in
Logging with ILogger<T>
· Configured
Logging in appsettings.json
· Saved
Logs to Files with Serilog
· Used
Structured Logging for Better Analysis
· Implemented
Centralized Logging with Seq
Comments
Post a Comment