Skip to content

Instantly share code, notes, and snippets.

@johndobrien
Created April 17, 2014 20:10
Show Gist options
  • Save johndobrien/11008731 to your computer and use it in GitHub Desktop.
Save johndobrien/11008731 to your computer and use it in GitHub Desktop.
PostSharp Aspect for Metrics
using System;
using System.Diagnostics;
using System.Reflection;
using PostSharp.Aspects;
using PostSharp.Extensibility;
namespace Common.Metrics
{
[Serializable]
[MulticastAttributeUsage(MulticastTargets.Method)]
public sealed class TimingAttribute : OnMethodBoundaryAspect
{
[NonSerialized]
private Stopwatch _stopwatch;
private string _name;
public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo)
{
_name = method.DeclaringType != null ? string.Format("{0}.{1}", method.DeclaringType.FullName.Replace(".", ""), method.Name) : method.Name;
}
public override void OnEntry(MethodExecutionArgs args)
{
_stopwatch = Stopwatch.StartNew();
base.OnEntry(args);
}
public override void OnExit(MethodExecutionArgs args)
{
Metrics.Timing(_name, (long)_stopwatch.Elapsed.TotalMilliseconds);
base.OnExit(args);
}
public override void OnException(MethodExecutionArgs args)
{
Metrics.Timing(string.Format("error.{0}", _name), (long)_stopwatch.Elapsed.TotalMilliseconds);
base.OnException(args);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment