using System.Diagnostics; using Microsoft.Extensions.Logging; namespace Umbraco.Cms.Core.Logging; /// /// Implements by writing profiling results to an . /// public class LogProfiler : IProfiler { private readonly ILogger _logger; public LogProfiler(ILogger logger) => _logger = logger; /// public IDisposable Step(string name) { _logger.LogDebug("Begin: {ProfileName}", name); return new LightDisposableTimer(duration => _logger.LogInformation("End {ProfileName} ({ProfileDuration}ms)", name, duration)); } /// public void Start() { // the log will always be started } /// public void Stop(bool discardResults = false) { // the log never stops } // a lightweight disposable timer private class LightDisposableTimer : DisposableObjectSlim { private readonly Action _callback; private readonly Stopwatch _stopwatch = Stopwatch.StartNew(); protected internal LightDisposableTimer(Action callback) { _callback = callback ?? throw new ArgumentNullException(nameof(callback)); } protected override void DisposeResources() { _stopwatch.Stop(); _callback(_stopwatch.ElapsedMilliseconds); } } }