Last active
September 14, 2017 15:00
-
-
Save stdray/dee56d7b979887a73a9ab51d1a84b8e0 to your computer and use it in GitHub Desktop.
Simple metrics attrinute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}"; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IDataDogService | |
{ | |
void LogMetric(string name, TimeSpan value); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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