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();
Step 4. Add Logging to a Controller.
Let’s add some logging inside the default WeatherForecastController.
Open Controllers/WeatherForecastController.cs and update it like this.
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
_logger.LogInformation("Weather forecast requested at {Time}", DateTime.UtcNow);
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
This line.
_logger.LogInformation("Weather forecast requested at {Time}", DateTime.UtcNow);
will write a log entry each time the endpoint is called.
Step 5. Run the Application.
Use this command to start the app.
dotnet run
Now open your browser and go to,
https://localhost:5001/weatherforecast
Each time you refresh the page, a new log will be generated and saved to MongoDB.
Step 6. View Logs in MongoDB.
Open MongoDB Compass or use the Mongo shell.
In MongoDB Compass.
- Connect to your server (mongodb://localhost:27017)
- Open the database logs
- Go to the logEntries collection
You’ll see documents like this.
{
"_id": ObjectId("665d1739a92a511a28e4d341"),
"Timestamp": "2025-06-03T14:00:00Z",
"Level": "Information",
"MessageTemplate": "Weather forecast requested at {Time}",
"RenderedMessage": "Weather forecast requested at 6/3/2025 2:00:00 PM",
"Properties": {
"Time": "2025-06-03T14:00:00Z",
"SourceContext": "LoggingWithMongo.Controllers.WeatherForecastController"
}
}
You can use MongoDB queries to search, filter, or export logs.
Conclusion
Now your Web API logs are being saved in MongoDB! This is useful for,
- Centralized log storage
- Debugging issues
- Monitoring app activity
- Viewing logs from multiple servers
You can expand this by adding more structured data, custom enrichers, and log filtering.
Let me know if you’d like help adding things like,
- Request/response logging
- Error logging middleware
- Logging user info or IP addresses
Happy coding!