Skip to content
This repository was archived by the owner on Jun 21, 2023. It is now read-only.

Commit 066ec81

Browse files
committed
Add extension methods for logging timings
1 parent 5722b18 commit 066ec81

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

src/GitHub.Logging/Logging/ILoggerExtensions.cs

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
using System;
2+
using System.Globalization;
3+
using System.Threading.Tasks;
14
using Serilog;
25

36
namespace 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

Comments
 (0)