Created
September 26, 2019 21:04
-
-
Save Wind010/88a37285fa1daddbc226859ef194adb4 to your computer and use it in GitHub Desktop.
OperationLogger
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
namespace Profiler | |
{ | |
using Serilog; | |
using Serilog.Events; | |
public class OperationLogger : Stopwatch, IDisposable | |
{ | |
private readonly string _operationName; | |
private readonly LogEventLevel _logEventLevel; | |
private readonly ILogger _logger; | |
public const string OperationStarted = "{operationName}:Operation started."; | |
public const string OperationFinished = "{operationName}:Operation finished. Elapsed={elapsedMilliseconds} ms"; | |
public OperationLogger(string operationName, ILogger logger, LogEventLevel logEventLevel = LogEventLevel.Information) | |
{ | |
_logger = logger ?? throw new ArgumentNullException(nameof(logger)); | |
_operationName = operationName ?? throw new ArgumentNullException(nameof(operationName)); | |
_logEventLevel = logEventLevel; | |
this.Start(); | |
_logger.Write(_logEventLevel, OperationStarted, _operationName); | |
} | |
public void Dispose() | |
{ | |
this.Stop(); | |
_logger.Write(_logEventLevel, OperationFinished, _operationName, this.ElapsedMilliseconds); | |
Dispose(true); | |
GC.SuppressFinalize(this); | |
} | |
protected virtual void Dispose(bool disposing) | |
{ | |
if (disposing) | |
{ | |
// Free managed resources | |
} | |
// Free native resources if there are any. | |
} | |
~OperationLogger() | |
{ | |
Dispose(false); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment