Tuesday, 3 June 2025

ASP.NET Core Web API Login with MongoDB

Leave a Comment

 How to use MongoDB in.NET 8 to configure logging in an ASP.NET Core Web API. This comprehensive tutorial demonstrates how to use Serilog to record logs and store them in MongoDB, which facilitates error tracking, API behavior monitoring, and real-time application activity analysis.



One of the most crucial aspects of developing a practical application is logging. It assists you in tracking faults, keeping an eye on behavior, and comprehending the background operations of your application.

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!

ASP.NET Core 10.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 10.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFE.eu guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

 

0 comments:

Post a Comment