Last active
May 16, 2017 09:55
-
-
Save gubenkoved/c8aef4695b6e51e67f40fea79e7835f0 to your computer and use it in GitHub Desktop.
Instrument it!
This file contains hidden or 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 static class Instrument | |
{ | |
public class OperationMetrics | |
{ | |
public string OperationName { get; set; } | |
public DateTime StartedAt { get; set; } | |
public TimeSpan Duration { get; set; } | |
public bool IsSuccess { get; set; } | |
public Exception Error { get; set; } | |
} | |
public static bool Enabled = true; | |
public static event EventHandler<OperationMetrics> NewData; | |
public static void It(string operationName, Action action) | |
{ | |
It(operationName, () => { action.Invoke(); return 0; }); | |
} | |
public static T It<T>(string operationName, Func<T> action) | |
{ | |
if (!Enabled) | |
return action(); | |
var dto = new OperationMetrics(); | |
dto.OperationName = operationName; | |
dto.StartedAt = DateTime.UtcNow; | |
Stopwatch sw = new Stopwatch(); | |
sw.Start(); | |
try | |
{ | |
T result = action.Invoke(); | |
dto.IsSuccess = true; | |
return result; | |
} | |
catch (Exception e) | |
{ | |
dto.Error = e; | |
dto.IsSuccess = false; | |
throw; | |
} | |
finally | |
{ | |
sw.Stop(); | |
dto.Duration = sw.Elapsed; | |
NewData?.Invoke(null, dto); | |
} | |
} | |
public static async Task It(string operationName, Func<Task> promiseGen) | |
{ | |
Func<Task<int>> adaptor = async () => | |
{ | |
await promiseGen(); | |
return 0; | |
}; | |
await It(operationName, adaptor); | |
} | |
public static async Task<T> It<T>(string operationName, Func<Task<T>> promiseGen) | |
{ | |
if (!Enabled) | |
return await promiseGen(); | |
var dto = new OperationMetrics(); | |
dto.OperationName = operationName; | |
dto.StartedAt = DateTime.UtcNow; | |
Stopwatch sw = new Stopwatch(); | |
sw.Start(); | |
try | |
{ | |
Task<T> promise = promiseGen(); | |
T result = await promise; | |
dto.IsSuccess = true; | |
return result; | |
} | |
catch (Exception e) | |
{ | |
dto.Error = e; | |
dto.IsSuccess = false; | |
throw; | |
} | |
finally | |
{ | |
sw.Stop(); | |
dto.Duration = sw.Elapsed; | |
NewData?.Invoke(null, dto); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment