microsoft/healthcare-shared-components
Publicmirrored from https://github.com/microsoft/healthcare-shared-componentsAvailable
src/Microsoft.Health.Core/ActionTimer.cs
45lines · modecode
| 1 | // ------------------------------------------------------------------------------------------------- |
| 2 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. |
| 4 | // ------------------------------------------------------------------------------------------------- |
| 5 | |
| 6 | using System; |
| 7 | using System.Diagnostics; |
| 8 | using EnsureThat; |
| 9 | using Microsoft.Extensions.Logging; |
| 10 | |
| 11 | namespace Microsoft.Health.Core |
| 12 | { |
| 13 | public sealed class ActionTimer : IDisposable |
| 14 | { |
| 15 | private readonly ILogger _logger; |
| 16 | private readonly string _componentName; |
| 17 | private readonly Stopwatch _stopwatch; |
| 18 | private readonly IDisposable _scope; |
| 19 | |
| 20 | public ActionTimer(ILogger logger, string componentName) |
| 21 | { |
| 22 | EnsureArg.IsNotNull(logger, nameof(logger)); |
| 23 | EnsureArg.IsNotNull(componentName, nameof(componentName)); |
| 24 | |
| 25 | _logger = logger; |
| 26 | _componentName = componentName; |
| 27 | _stopwatch = new Stopwatch(); |
| 28 | |
| 29 | _scope = _logger.BeginScope($"Beginning execution of {componentName}"); |
| 30 | _stopwatch.Start(); |
| 31 | } |
| 32 | |
| 33 | public TimeSpan GetElapsedTime() |
| 34 | { |
| 35 | return _stopwatch.Elapsed; |
| 36 | } |
| 37 | |
| 38 | public void Dispose() |
| 39 | { |
| 40 | _stopwatch.Stop(); |
| 41 | _logger.LogInformation($"{_componentName} executed in {{Duration}}.", _stopwatch.Elapsed); |
| 42 | _scope.Dispose(); |
| 43 | } |
| 44 | } |
| 45 | } |