Skip to main content

Step-by-Step Guide to Monitoring API Activity and Logging Effectively


 

API calls are the backbone of modern applications, and monitoring them is crucial for debugging, performance analysis, and error tracking. If you need to track your application’s API calls and identify where logging happens, this guide will show you how to implement effective tracking mechanisms, log strategically, and pinpoint issues in your application.

Why Track API Calls and Logs?

  1. Debugging and Troubleshooting:
    • Identify bottlenecks and failures in the API workflow.
  2. Performance Monitoring:
    • Track response times and optimize slow endpoints.
  3. Compliance and Audit:
    • Log API usage for compliance and security auditing.
  4. Behavior Analysis:
    • Understand usage patterns and optimize frequently used APIs.

Step 1: Add Middleware to Track API Calls

In ASP.NET Core, middleware is a powerful way to intercept requests and responses. You can use custom middleware to log details about incoming API calls.

Example: Logging Middleware

Create a RequestLoggingMiddleware:

public class RequestLoggingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<RequestLoggingMiddleware> _logger;

    public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        // Log Request Details
        _logger.LogInformation("Request: {Method} {Path}", context.Request.Method, context.Request.Path);

        // Log Headers (Optional)
        foreach (var header in context.Request.Headers)
        {
            _logger.LogInformation("Header: {Key} = {Value}", header.Key, header.Value);
        }

        // Proceed to next middleware
        await _next(context);

        // Log Response Details
        _logger.LogInformation("Response: {StatusCode}", context.Response.StatusCode);
    }
}
Register the middleware in Program.cs:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseMiddleware<RequestLoggingMiddleware>();

app.MapControllers();
app.Run();

Step 2: Use Action Filters for Endpoint-Level Logging

To track logging at a more granular level, use Action Filters.

Example: Logging Action Filter

Create a LogActionFilter:

public class LogActionFilter : IActionFilter
{
    private readonly ILogger<LogActionFilter> _logger;

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

    public void OnActionExecuting(ActionExecutingContext context)
    {
        _logger.LogInformation("Executing action {ActionName} with parameters: {Parameters}",
            context.ActionDescriptor.DisplayName,
            context.ActionArguments);
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        _logger.LogInformation("Executed action {ActionName} with result: {Result}",
            context.ActionDescriptor.DisplayName,
            context.Result);
    }
}
Register the filter globally in Program.cs:
builder.Services.AddControllers(options =>
{
    options.Filters.Add<LogActionFilter>();
});

Step 3: Centralize and Enrich Your Logs

To ensure your logs are meaningful, use structured logging with a tool like Serilog or NLog.

Set Up Serilog

  1. Install the Serilog package:

dotnet add package Serilog.AspNetCore
  1. Configure Serilog in Program.cs:

using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Configure Serilog
builder.Host.UseSerilog((context, config) =>
{
    config.WriteTo.Console()
          .WriteTo.File("logs/api-log.txt", rollingInterval: RollingInterval.Day);
});

var app = builder.Build();

app.UseSerilogRequestLogging(); // Logs requests automatically
app.MapControllers();
app.Run();

Step 4: Correlate API Calls with Application Logs

For advanced tracking, use Correlation IDs to link API calls with logs across different services.

Example: Add Correlation ID Middleware

  1. Install the CorrelationId package:

  2. dotnet add package CorrelationId
    
  3. Register the middleware in Program.cs:

using CorrelationId;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDefaultCorrelationId();

var app = builder.Build();

app.UseCorrelationId();
app.MapControllers();
app.Run();
Log the Correlation ID in middleware:
_logger.LogInformation("Correlation ID: {CorrelationId}", context.TraceIdentifier);

Step 5: Visualize Logs and API Metrics

Use monitoring tools to make sense of the logs and API metrics:

  • Seq: A structured log viewer for debugging.
  • ELK Stack (Elasticsearch, Logstash, Kibana): For analyzing logs in real-time.
  • Application Insights (Azure): For end-to-end performance and diagnostics.

Step 6: Verify Logging Coverage

To ensure all critical parts of your application are covered:

  1. Create a Logging Checklist:
    • Are incoming and outgoing requests logged?
    • Are exceptions logged with enough context?
    • Is sensitive data excluded from logs?
  2. Test Logging:
    • Trigger API calls and validate logs for completeness and accuracy.

Explaining to a beginner

Think of logging as a surveillance system for your application:

  • Middleware acts as a front desk camera, recording every visitor (request).
  • Action filters are like security officers, noting down details of activities (actions) inside specific rooms (endpoints).
  • Structured logging tools like Serilog are log managers, organizing records so you can find the right footage quickly.

Conclusion

Tracking API calls and logging effectively is crucial for debugging, monitoring, and improving your application. By combining middleware, action filters, structured logging, and correlation IDs, you can gain clear insights into your API's activity and ensure your logs are meaningful and actionable.

Let me know if you need further examples or specific tools to enhance your logging setup! 

Comments

Popular posts from this blog

C# : How can we access private method outside class

Introduction In object-oriented programming, encapsulation is a fundamental principle that restricts direct access to the internal implementation details of a class. Private methods, being part of this internal implementation, are designed to be accessible only within the confines of the class they belong to. However, there might be scenarios where you need to access a private method from outside the class. In this blog post, we'll explore several techniques to achieve this in C#. 1. Reflection: A Powerful Yet Delicate Approach Reflection is a mechanism in C# that allows inspecting and interacting with metadata about types, fields, properties, and methods. While it provides a way to access private methods, it should be used cautiously due to its potential impact on maintainability and performance. using System ; using System . Reflection ; public class MyClass { private void PrivateMethod ( ) { Console . WriteLine ( "This is a private method."...

20+ LINQ Concepts with .Net Code

LINQ   (Language Integrated Query) is one of the most powerful features in .NET, providing a unified syntax to query collections, databases, XML, and other data sources. Below are 20+ important LINQ concepts, their explanations, and code snippets to help you understand their usage. 1.  Where  (Filtering) The  Where()  method is used to filter a collection based on a given condition. var numbers = new List < int > { 1 , 2 , 3 , 4 , 5 , 6 } ; var evenNumbers = numbers . Where ( n => n % 2 == 0 ) . ToList ( ) ; // Output: [2, 4, 6] C# Copy 2.  Select  (Projection) The  Select()  method projects each element of a sequence into a new form, allowing transformation of data. var employees = new List < Employee > { /* ... */ } ; var employeeNames = employees . Select ( e => e . Name ) . ToList ( ) ; // Output: List of employee names C# Copy 3.  OrderBy  (Sorting in Ascending Order) The  Or...

Clean Architecture: What It Is and How It Differs from Microservices

In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...