Skip to content

Instantly share code, notes, and snippets.

@doeringp
Created July 12, 2016 10:49
Show Gist options
  • Save doeringp/af5c763d658acf6babe62a9a1b6ba97c to your computer and use it in GitHub Desktop.
Save doeringp/af5c763d658acf6babe62a9a1b6ba97c to your computer and use it in GitHub Desktop.
Time measuring for code blocks with StopWatch and NLog.
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