Created
July 12, 2016 10:49
-
-
Save doeringp/af5c763d658acf6babe62a9a1b6ba97c to your computer and use it in GitHub Desktop.
Time measuring for code blocks with StopWatch and NLog.
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; | |
using NLog; | |
namespace Doering.Logging | |
{ | |
/// <summary> | |
/// Use MonitoredScope within a using statement to measure the time the operation needs. | |
/// The result will be written to the NLog logger. | |
/// </summary> | |
public class MonitoredScope : IDisposable | |
{ | |
private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); | |
private readonly Stopwatch _watch; | |
public string Name { get; set; } | |
public MonitoredScope(string name) | |
{ | |
Name = name; | |
Logger.Info($"Entering monitored scope \"{name}\"."); | |
_watch = new Stopwatch(); | |
_watch.Start(); | |
} | |
public void Dispose() | |
{ | |
_watch.Stop(); | |
Logger.Info($"Leaving monitored scope \"{Name}\". (Elapsed time: {_watch.ElapsedMilliseconds}ms)"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment