C
C#5mo ago
Angius

`Microsoft.Extensions.Logging` and Serilog compatible timing library?

I'm currently using https://github.com/nblumhardt/serilog-timings to log how much time a given operation took. It was nice and all when I was using a static logger, but I wanted to switch to an injected ILogger instance. Problem is, SerilogTimings works on a Serilog.ILogger instance, not MEL.ILogger which feels kinda smelly to me. Is there any other library I could use with Serilog and MEL that would let me easily time whatever operations?
2 Replies
Angius
AngiusOP5mo ago
[SuppressMessage("Usage", "CA2254")]
public sealed class Operation(ILogger logger, string messageTemplate, params object[] args) : IDisposable
{
private static readonly double StopwatchToTimeSpanTicks = Stopwatch.Frequency / 10_000_000.0;

private readonly long _start = (long)(Stopwatch.GetTimestamp() / StopwatchToTimeSpanTicks);

public void Dispose()
{
var elapsed = Stopwatch.GetElapsedTime(_start).TotalMilliseconds;
var template = $"{messageTemplate} in {{Elapsed:0.0}}ms";
object[] args1 = [..args, elapsed];
logger.Log(LogLevel.Information, template, args1);
}
}
[SuppressMessage("Usage", "CA2254")]
public sealed class Operation(ILogger logger, string messageTemplate, params object[] args) : IDisposable
{
private static readonly double StopwatchToTimeSpanTicks = Stopwatch.Frequency / 10_000_000.0;

private readonly long _start = (long)(Stopwatch.GetTimestamp() / StopwatchToTimeSpanTicks);

public void Dispose()
{
var elapsed = Stopwatch.GetElapsedTime(_start).TotalMilliseconds;
var template = $"{messageTemplate} in {{Elapsed:0.0}}ms";
object[] args1 = [..args, elapsed];
logger.Log(LogLevel.Information, template, args1);
}
}
public static class LoggerExtension
{
public static Operation TimeOperation(this ILogger logger, [StructuredMessageTemplate] string messageTemplate, params object[] args)
{
return new Operation(logger, messageTemplate, args);
}
}
public static class LoggerExtension
{
public static Operation TimeOperation(this ILogger logger, [StructuredMessageTemplate] string messageTemplate, params object[] args)
{
return new Operation(logger, messageTemplate, args);
}
}
did the trick
Joschi
Joschi5mo ago
You could also just use traces and start a new Activity. And you can log traces to serilog if you really want to with Serilog.Tracing
Want results from more Discord servers?
Add your server