ASP.NET Core  

Logging and Monitoring Security Events in ASP.NET Core

Security is not only about preventing attacks but also about detecting, monitoring, and responding to them. In ASP.NET Core applications, proper logging and monitoring of security events is critical for identifying suspicious activities, ensuring compliance, and strengthening your application’s defense posture.

This article will guide you through implementing structured logging, monitoring, and alerting for security events in ASP.NET Core.

Why Logging Security Events Matters

Security-focused logging allows you to:

  • Detect brute-force login attempts.

  • Trace suspicious API calls.

  • Identify unauthorized access attempts.

  • Support incident response and forensic investigations.

  • Comply with security standards (GDPR, ISO 27001, PCI-DSS, etc.).

Best Practices for Security Event Logging

  1. Log only necessary data – Avoid sensitive data like passwords or full credit card numbers.

  2. Use structured logging – Store logs in a structured format (JSON, key-value pairs) for easy querying.

  3. Include security context – Always log UserId, IP address, Action, and Result.

  4. Apply log levels correctly

    • Information: Successful login, user registered.

    • Warning: Multiple failed login attempts.

    • Error: Unauthorized access attempt.

    • Critical: Possible intrusion or data breach.

Setting Up Logging in ASP.NET Core

ASP.NET Core includes a flexible logging framework out of the box. You can integrate providers such as Serilog, NLog, or Microsoft.Extensions.Logging.

Example: Configuring Serilog

Install the required NuGet packages:

dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.File
dotnet add package Serilog.Sinks.Console

In Program.cs:

using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Configure Serilog
Log.Logger = new LoggerConfiguration()
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .WriteTo.File("logs/security-.log", rollingInterval: RollingInterval.Day)
    .CreateLogger();

builder.Host.UseSerilog();

var app = builder.Build();
app.MapGet("/", () => "Secure Logging Demo");
app.Run();

Logging Security Events in Controllers

You can inject ILogger<T> to log security-related activities.

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class AccountController : ControllerBase
{
    private readonly ILogger<AccountController> _logger;

    public AccountController(ILogger<AccountController> logger)
    {
        _logger = logger;
    }

    [HttpPost("login")]
    public IActionResult Login(string username, string password)
    {
        if (username == "admin" && password == "123")
        {
            _logger.LogInformation("User {Username} logged in successfully from IP {IP}", username, HttpContext.Connection.RemoteIpAddress);
            return Ok("Login Successful");
        }

        _logger.LogWarning("Failed login attempt for {Username} from IP {IP}", username, HttpContext.Connection.RemoteIpAddress);
        return Unauthorized("Invalid credentials");
    }
}

Monitoring Security Events

Logging alone isn’t enough—you need monitoring and alerting.

Options:

  1. Application Insights (Azure) – Centralized monitoring, custom queries (Kusto Query Language).

  2. Elastic Stack (ELK) – Elasticsearch, Logstash, Kibana for real-time log analysis.

  3. SIEM Tools (Splunk, Graylog, Sentinel) – Advanced correlation and intrusion detection.

Adding Alerts for Suspicious Behavior

For example, you can detect multiple failed login attempts:

private static Dictionary<string, int> FailedAttempts = new();

[HttpPost("login")]
public IActionResult Login(string username, string password)
{
    var ip = HttpContext.Connection.RemoteIpAddress?.ToString();

    if (username == "admin" && password == "123")
    {
        FailedAttempts[ip] = 0;
        _logger.LogInformation("User {Username} logged in successfully from {IP}", username, ip);
        return Ok("Login Successful");
    }

    if (!FailedAttempts.ContainsKey(ip)) FailedAttempts[ip] = 0;
    FailedAttempts[ip]++;

    _logger.LogWarning("Failed login attempt {Count} for {Username} from {IP}", FailedAttempts[ip], username, ip);

    if (FailedAttempts[ip] > 5)
    {
        _logger.LogError("Possible brute force attack detected from IP {IP}", ip);
        // Trigger alert, block IP, or notify admin
    }

    return Unauthorized("Invalid credentials");
}

Securing Log Data

  • Store logs in secure storage (Azure Blob, AWS S3 with encryption).

  • Restrict access to logs.

  • Use log rotation to avoid large files.

  • Apply GDPR compliance (e.g., anonymize IP addresses if required).

Conclusion

By combining structured logging, real-time monitoring, and alerts, you can make your ASP.NET Core application resilient against intrusions and better prepared for incident response.

Key Takeaways:

  • Use structured logging (Serilog, NLog, built-in logging).

  • Always log security-related activities.

  • Monitor logs with Application Insights, ELK, or SIEM tools.

  • Trigger alerts on suspicious activity.

  • Secure and protect logs from tampering.

With these practices, you can proactively detect, investigate, and respond to threats in your ASP.NET Core applications.