1+ using System ;
2+ using System . Globalization ;
3+ using System . Threading . Tasks ;
14using Serilog ;
25
36namespace GitHub . Logging
@@ -25,5 +28,37 @@ public static void Assert(this ILogger logger, bool condition, string messageTem
2528#pragma warning restore Serilog004
2629 }
2730 }
31+
32+ public static void Time ( this ILogger logger , string name , Action method )
33+ {
34+ var startTime = DateTime . Now ;
35+ method ( ) ;
36+ logger . Information ( "{Name} took {Seconds} seconds" , name , FormatSeconds ( DateTime . Now - startTime ) ) ;
37+ }
38+
39+ public static T Time < T > ( this ILogger logger , string name , Func < T > method )
40+ {
41+ var startTime = DateTime . Now ;
42+ var value = method ( ) ;
43+ logger . Information ( "{Name} took {Seconds} seconds" , name , FormatSeconds ( DateTime . Now - startTime ) ) ;
44+ return value ;
45+ }
46+
47+ public static async Task TimeAsync ( this ILogger logger , string name , Func < Task > methodAsync )
48+ {
49+ var startTime = DateTime . Now ;
50+ await methodAsync ( ) . ConfigureAwait ( false ) ;
51+ logger . Information ( "{Name} took {Seconds} seconds" , name , FormatSeconds ( DateTime . Now - startTime ) ) ;
52+ }
53+
54+ public static async Task < T > TimeAsync < T > ( this ILogger logger , string name , Func < Task < T > > methodAsync )
55+ {
56+ var startTime = DateTime . Now ;
57+ var value = await methodAsync ( ) . ConfigureAwait ( false ) ;
58+ logger . Information ( "{Name} took {Seconds} seconds" , name , FormatSeconds ( DateTime . Now - startTime ) ) ;
59+ return value ;
60+ }
61+
62+ static string FormatSeconds ( TimeSpan timeSpan ) => timeSpan . TotalSeconds . ToString ( "0.##" , CultureInfo . InvariantCulture ) ;
2863 }
29- }
64+ }
0 commit comments