Last active
August 20, 2017 01:52
-
-
Save jlattimer/0c85129d8ae865f894e6a8c351d48e60 to your computer and use it in GitHub Desktop.
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 void Execute(IServiceProvider serviceProvider) | |
{ | |
ITracingService tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); | |
MethodTimeLogger.Tracer = tracer; | |
// What manually setting up method timing might look like | |
ManualTimer(tracer); | |
// What using IL weaving to inject logging looks like | |
IlWeavngTimer(); | |
} | |
private void ManualTimer(ITracingService tracer) | |
{ | |
// Create new stopwatch. | |
Stopwatch stopwatch = new Stopwatch(); | |
// Begin timing. | |
stopwatch.Start(); | |
// Do something. | |
Thread.Sleep(5000); | |
// Stop timing. | |
stopwatch.Stop(); | |
// Get the current method name | |
var methodName = MethodBase.GetCurrentMethod().Name; | |
// Write result. | |
tracer.Trace($"{methodName} Method Time elapsed: {stopwatch.ElapsedMilliseconds}ms"); | |
} | |
[Time] | |
private void IlWeavngTimer() | |
{ | |
// Do something. | |
Thread.Sleep(5000); | |
} | |
//What got compiled | |
private void IlWeavngTimerCompiled() | |
{ | |
Stopwatch stopwatch = Stopwatch.StartNew(); | |
try | |
{ | |
Thread.Sleep(5000); | |
} | |
finally | |
{ | |
stopwatch.Stop(); | |
MethodTimeLogger.Log(MethodBase.GetMethodFromHandle(typeof(LoggingTest).GetMethod("AopTime").MethodHandle, typeof(LoggingTest).TypeHandle), stopwatch.ElapsedMilliseconds); | |
} | |
} | |
internal static class MethodTimeLogger | |
{ | |
public static ITracingService Tracer; | |
public static void Log(MethodBase methodBase, long milliseconds) | |
{ | |
Tracer.Trace($"{methodBase.Name} Method Time elapsed: {milliseconds}ms"); | |
} | |
} | |
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | | |
AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Constructor)] | |
internal class TimeAttribute : Attribute | |
{ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment