I'd like to be able to make a call (e.g., to an API) from within an Azure function, and make a log entry if it is taking longer than n milliseconds, but not interrupt or end the call. Note this is not for the UI, it would only be for logging.
How can I do this in C#?
Here is an application-agnostic solution (not tailored specifically for Azure).
static IDisposable CreateSlowCallLogger(string title, int dueTimeMilliseconds = 1000)
{
System.Threading.Timer timer = new(_ =>
{
// Log the slow call
Console.WriteLine($"{title} was slower than {dueTimeMilliseconds:#,0} msec!");
});
timer.Change(dueTimeMilliseconds, Timeout.Infinite);
return timer;
}
Usage example:
using (CreateSlowCallLogger("TheAPI"))
{
TheAPI();
}
The above implementation logs the slow call on a ThreadPool thread, while the call is still running. So there is no information available about how long the call lasted from start to finish. If you want this information you could implement something similar using a Stopwatch instead of a Timer, and logging synchronously after the completion of the call.
I'm not sure if it has already been proposed in part by one of the other answers. However, unless you want the log message to appear exactly at the time of the threshold, you can simply start a Stopwatch before the request. After the request is successful or failed, you log if Elapsed is more than the threshold.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With