Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging long running API or other call

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#?

like image 531
Jesse Liberty Avatar asked Sep 11 '26 20:09

Jesse Liberty


2 Answers

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.

like image 65
Theodor Zoulias Avatar answered Sep 14 '26 10:09

Theodor Zoulias


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.

like image 32
ThomasArdal Avatar answered Sep 14 '26 09:09

ThomasArdal