Centralized logging resource usage for all controller actions

.NET Framework


Create a Custom Action Filter

using System;
using System.Diagnostics;
using System.Web.Mvc;


public class ResourceUsageLoggingFilter : ActionFilterAttribute
{
    private Stopwatch _stopwatch;
    private long _startMemory;
    private TimeSpan _startCpuTime;


    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Start measuring CPU and memory
        _stopwatch = Stopwatch.StartNew();
        var process = Process.GetCurrentProcess();
        _startMemory = process.WorkingSet64;
        _startCpuTime = process.TotalProcessorTime;


        base.OnActionExecuting(filterContext);
    }


    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        _stopwatch.Stop();
        var process = Process.GetCurrentProcess();
        var endMemory = process.WorkingSet64;
        var endCpuTime = process.TotalProcessorTime;


        // Calculate memory and CPU usage
        var memoryUsedMb = (endMemory - _startMemory) / (1024 * 1024);
        var cpuUsedMs = (endCpuTime - _startCpuTime).TotalMilliseconds;


        // Log if usage exceeds thresholds
        if (memoryUsedMb > 50 || cpuUsedMs > 100) // Example thresholds
        {
            Debug.WriteLine($"High Resource Usage: Action: {filterContext.ActionDescriptor.ActionName}, " +
                            $"Memory: {memoryUsedMb} MB, CPU: {cpuUsedMs} ms, Duration: {_stopwatch.ElapsedMilliseconds} ms");
        }


        base.OnActionExecuted(filterContext);
    }
}


Register the filter in Global.asax

protected void Application_Start()
{
    GlobalFilters.Filters.Add(new ResourceUsageLoggingFilter());
}


Decorate individual controllers or actions with the filter

[ResourceUsageLoggingFilter]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}


.NET Core


Create Middleware

public class ResourceUsageLoggingMiddleware
{
    private readonly RequestDelegate _next;


    public ResourceUsageLoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }


    public async Task InvokeAsync(HttpContext context)
    {
        var process = Process.GetCurrentProcess();
        var startMemory = process.WorkingSet64;
        var startCpuTime = process.TotalProcessorTime;
        var stopwatch = Stopwatch.StartNew();


        await _next(context);


        stopwatch.Stop();
        var endMemory = process.WorkingSet64;
        var endCpuTime = process.TotalProcessorTime;


        var memoryUsedMb = (endMemory - startMemory) / (1024 * 1024);
        var cpuUsedMs = (endCpuTime - startCpuTime).TotalMilliseconds;


        if (memoryUsedMb > 50 || cpuUsedMs > 100) // Example thresholds
        {
            Console.WriteLine($"High Resource Usage: Request: {context.Request.Path}, " +
                              $"Memory: {memoryUsedMb} MB, CPU: {cpuUsedMs} ms, Duration: {stopwatch.ElapsedMilliseconds} ms");
        }
    }
}


Register the middleware in Startup.cs

public void Configure(IApplicationBuilder app)
{
    app.UseMiddleware<ResourceUsageLoggingMiddleware>();
    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}