Skip to content

Instantly share code, notes, and snippets.

@stdray
Last active September 14, 2017 15:00
Show Gist options
  • Save stdray/dee56d7b979887a73a9ab51d1a84b8e0 to your computer and use it in GitHub Desktop.
Save stdray/dee56d7b979887a73a9ab51d1a84b8e0 to your computer and use it in GitHub Desktop.
Simple metrics attrinute
public class DataDogFilterAttribute : ActionFilterAttribute
{
const string KEY = nameof(DataDogFilterAttribute) + "Value";
readonly string _name;
public DataDogFilterAttribute(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException(nameof(name));
_name = name;
}
private DataDogFilterAttribute()
{
}
public static DataDogFilterAttribute GetGlobalFilter() => new DataDogFilterAttribute();
public override void OnActionExecuting(HttpActionContext ctx)
{
base.OnActionExecuting(ctx);
ctx.Request.Properties[KEY] = DateTime.Now;
}
public override void OnActionExecuted(HttpActionExecutedContext ctx)
{
base.OnActionExecuted(ctx);
var time = DateTime.Now - (DateTime)ctx.Request.Properties[KEY];
var action = ctx.ActionContext.ActionDescriptor;
if (string.IsNullOrEmpty(_name) && action.GetCustomAttributes<DataDogFilterAttribute>().Any())
return;
var scope = ctx.Request.GetDependencyScope();
var dataDog = (IDataDogService)scope.GetService(typeof(IDataDogService));
if (!string.IsNullOrEmpty(_name))
{
dataDog.LogMetric(_name, time);
return;
}
var name = GetName(action);
dataDog.LogMetric(name, time);
}
static string GetName(HttpActionDescriptor descriptor) =>
$"{descriptor.ControllerDescriptor.ControllerName}_{descriptor.ActionName}";
}
public interface IDataDogService
{
void LogMetric(string name, TimeSpan value);
}
static void RegisterApiFilters(HttpFilterCollection filters)
{
filters.Add(DataDogFilterAttribute.GetGlobalFilter());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment