Introduction
How to set up logging in an ASP.NET Core Web API using MongoDB in .NET 8. This step-by-step guide shows you how to use Serilog to capture logs and store them in MongoDB, making it easy to track errors, monitor API behavior, and analyze application activity in real time.
Logging is one of the most important parts of building a real-world application. It helps you track errors, monitor behavior, and understand what your app is doing behind the scenes.
In this article, you’ll learn how to,
- Set up a Web API in ASP.NET Core (.NET 8)
- Use Serilog for logging
- Store logs in MongoDB
- View logs in MongoDB Compass
We’ll keep things simple but detailed so even beginners can follow along.
Prerequisites
Make sure you have these installed.
- .NET 8 SDK
- MongoDB
- MongoDB Compass (optional, for viewing logs)
- Basic knowledge of ASP.NET Core
Step 1. Create a New ASP.NET Core Web API Project.
Open your terminal and run.
dotnet new webapi -n LoggingWithMongo
cd LoggingWithMongo
This will create a sample Web API project.
Step 2. Install Required NuGet Packages.
We’ll use Serilog to handle logging, and a MongoDB sink to write logs to MongoDB.
Run these commands.
dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.MongoDB
Step 3. Set Up Serilog in Program.cs.
Open Program.cs, and update it as follows.
1. Add the using statement.
using Serilog;
2. Configure Serilog Logging.
Add this before the builder.Build()
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.MongoDB(
"mongodb://localhost:27017/logs", // MongoDB connection string
collectionName: "logEntries", // MongoDB collection name
cappedMaxSizeMb: 50 // Optional: limit collection size
)
.Enrich.FromLogContext()
.CreateLogger();
builder.Host.UseSerilog();
Here’s the full updated Program.cs.
using Serilog;
var builder = WebApplication.CreateBuilder(args);
// Configure Serilog
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.MongoDB(
"mongodb://localhost:27017/logs", // Replace with your MongoDB connection string
collectionName: "logEntries"
)
.Enrich.FromLogContext()
.CreateLogger();
builder.Host.UseSerilog(); // Replace default logger
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.UseAuthorization();
app.MapControllers();
app.Run();

Join the conversation! Your thoughts help the community grow.