Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Last active August 9, 2019 02:02
Show Gist options
  • Save dcomartin/7da98c1bb3c0e2654d035aa6d6f1c372 to your computer and use it in GitHub Desktop.
Save dcomartin/7da98c1bb3c0e2654d035aa6d6f1c372 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Amazon.CloudWatch;
using Amazon.CloudWatch.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace AspNetCore.Aws.Demo
{
public class CloudWatchExecutionTimeMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
private readonly IAmazonCloudWatch _amazonCloudWatch;
public CloudWatchExecutionTimeMiddleware(RequestDelegate next, ILogger<CloudWatchExecutionTimeMiddleware> logger, IAmazonCloudWatch amazonCloudWatch)
{
_next = next;
_logger = logger;
_amazonCloudWatch = amazonCloudWatch;
}
public async Task InvokeAsync(HttpContext context)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
await _next(context);
stopWatch.Stop();
try
{
await _amazonCloudWatch.PutMetricDataAsync(new PutMetricDataRequest
{
Namespace = "Demo",
MetricData = new List<MetricDatum>
{
new MetricDatum
{
MetricName = "AspNetExecutionTime",
Value = stopWatch.ElapsedMilliseconds,
Unit = StandardUnit.Milliseconds,
TimestampUtc = DateTime.UtcNow,
Dimensions = new List<Dimension>
{
new Dimension
{
Name = "Method",
Value = context.Request.Method
},
new Dimension
{
Name = "Path",
Value = context.Request.Path
}
}
}
}
});
}
catch (Exception ex)
{
_logger.LogCritical(ex, "Failed to send CloudWatch Metric");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment