Serilog in .NET Core Web API
Serilog in .NET Core Web API
Logging is a critical aspect of application development as it helps in debugging, monitoring, and maintaining application health. Serilog is a popular structured logging framework for .NET that allows developers to log messages to various destinations (sinks) such as files, databases, and cloud storage. This article will guide you through integrating Serilog into a .NET Core Web API.
Setting Up Serilog in .NET Core
Web API
Step 1: Install Required NuGet
Packages
To get started with Serilog,
install the necessary NuGet packages:
Install-Package Serilog.AspNetCore
Install-Package Serilog.Settings.Configuration
Install-Package
Serilog.Sinks.Console
Install-Package Serilog.Sinks.File
These packages allow logging to
the console and files while using configurations from appsettings.json.
Step 2: Configure Serilog in
Program.cs
Modify the Program.cs file to
initialize Serilog:
using
Microsoft.AspNetCore.Builder;
using
Microsoft.AspNetCore.Hosting;
using
Microsoft.Extensions.DependencyInjection;
using
Microsoft.Extensions.Hosting;
using Serilog;
using System;
var builder = WebApplication.CreateBuilder(args);
// Configure Serilog
Log.Logger = new
LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.File("logs/log-.txt",
rollingInterval: RollingInterval.Day)
.CreateLogger();
builder.Host.UseSerilog();
var app = builder.Build();
app.UseSerilogRequestLogging(); //
Enable request logging
app.MapGet("/", () =>
"Hello, world!");
app.Run();
Step 3: Configure appsettings.json
You can configure Serilog settings
in appsettings.json:
{
"Serilog": {
"Using":
["Serilog.Sinks.Console", "Serilog.Sinks.File"],
"MinimumLevel":
"Information",
"WriteTo":
[
{
"Name": "Console" },
{
"Name": "File", "Args": { "path":
"logs/log-.txt", "rollingInterval": "Day" } }
],
"Enrich":
["FromLogContext"],
"Properties":
{ "Application": "MyAPI" }
}
}
Logging in Controllers
Now that Serilog is set up, you
can use it in your controllers:
using Microsoft.AspNetCore.Mvc;
using
Microsoft.Extensions.Logging;
[ApiController]
[Route("api/[controller]")]
public class SampleController :
ControllerBase
{
private
readonly ILogger<SampleController> _logger;
public
SampleController(ILogger<SampleController> logger)
{
_logger
= logger;
}
[HttpGet]
public
IActionResult Get()
{
_logger.LogInformation("Handling
GET request at {Time}", DateTime.UtcNow);
return
Ok("Logging with Serilog!");
}
}
Real-Time Example: User Login Logging
Let's implement a real-world
scenario where we log user login attempts.
Step 1: Update the Controller
Modify the controller to log login
attempts:
[ApiController]
[Route("api/[controller]")]
public class AuthController :
ControllerBase
{
private
readonly ILogger<AuthController> _logger;
public
AuthController(ILogger<AuthController> logger)
{
_logger
= logger;
}
[HttpPost("login")]
public
IActionResult Login([FromBody] LoginRequest request)
{
_logger.LogInformation("Login
attempt for user: {Username} at {Time}", request.Username,
DateTime.UtcNow);
if
(request.Username == "admin" && request.Password ==
"password")
{
_logger.LogInformation("Successful
login for user: {Username} at {Time}", request.Username, DateTime.UtcNow);
return
Ok("Login successful");
}
_logger.LogWarning("Failed
login attempt for user: {Username} at {Time}", request.Username,
DateTime.UtcNow);
return
Unauthorized("Invalid credentials");
}
}
public class LoginRequest
{
public
string Username { get; set; }
public
string Password { get; set; }
}
Step 2: View Logs
If you attempt a login, the logs
will show:
[Information] Login attempt for
user: admin at 2024-03-18T12:00:00Z
[Information] Successful login for
user: admin at 2024-03-18T12:00:01Z
[Warning] Failed login attempt for
user: hacker at 2024-03-18T12:05:00Z
Advanced Features
1. Logging to a Database
To log to a database like SQL Server,
install:
Install-Package
Serilog.Sinks.MSSqlServer
Modify Program.cs:
.WriteTo.MSSqlServer(
connectionString:
"YourConnectionString",
sinkOptions:
new Serilog.Sinks.MSSqlServer.MSSqlServerSinkOptions { TableName =
"Logs" }
)
2. Logging Enrichment
To enrich logs with user context:
Log.Logger = new
LoggerConfiguration()
.Enrich.WithProperty("Environment",
"Production")
.Enrich.WithThreadId()
.CreateLogger();
3. Serilog Middleware for Request
Logging
Enable request logging in
Program.cs:
app.UseSerilogRequestLogging();
This will automatically log HTTP
requests and responses.
Conclusion
Serilog provides a powerful, structured logging experience for .NET Core applications. By following this guide, you can set up and customize logging to meet your application's needs, ensuring better monitoring, debugging, and performance analysis. The real-time example of user login logging showcases how Serilog can be used in real-world scenarios to track authentication attempts effectively.
Comments
Post a Comment