Skip to content

Instantly share code, notes, and snippets.

@mhamrah
Created February 12, 2010 02:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhamrah/302225 to your computer and use it in GitHub Desktop.
Save mhamrah/302225 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
namespace PerformanceTracer
{
public interface IPerformanceTracer
{
void WriteElapsedTime(string message);
void WriteInfo(string title, string message);
string EndTrace();
}
public class PerformanceTracer : IDisposable, IPerformanceTracer
{
private Stopwatch _sw;
private List<string> _perfMessages;
private List<string> _infoMessages;
private string _title;
private LogWriter _writer;
private long _lastTime;
private bool _eventLogEnabled = false;
/// <summary>
/// Creates a new instance of a performance tracer. An EventLog entry is automatically written to the event log when this object is disposed. An instance should usually be declared in a using() statement.
/// </summary>
/// <param name="title">The title of this performance trace</param>
public PerformanceTracer(string title)
{
if (string.IsNullOrEmpty(title))
throw new ArgumentNullException("Operation name can't be null or empty when instantiating the Performance Tracer");
_sw = new Stopwatch();
_perfMessages = new List<string>();
_infoMessages = new List<string>();
_title = title;
try
{
_writer = new LogWriterFactory(new SystemConfigurationSource()).Create();
_eventLogEnabled = true;
}
catch { } // ignore exception if no logging available.
_sw.Start();
}
public PerformanceTracer(string title, string message)
: this(title)
{
_infoMessages.Add(message);
}
/// <summary>
/// Writes a message to the log with the elapsed time since the performance instance was created.
/// </summary>
/// <param name="message"></param>
public void WriteElapsedTime(string message)
{
var current = _sw.ElapsedMilliseconds;
var diff = current - _lastTime;
_perfMessages.Add(string.Format("{0}:{1}: {2}", current.ToString().PadLeft(4), diff.ToString().PadLeft(4), message));
_lastTime = current;
}
/// <summary>
/// Writes information without a timestamp; useful for auxilary information.
/// </summary>
/// <param name="title"></param>
/// <param name="message"></param>
public void WriteInfo(string title, string message)
{
_infoMessages.Add(string.Format("{0}: {1}", title, message));
}
public void Dispose()
{
EndTrace();
}
public string EndTrace()
{
_sw.Stop();
this.WriteElapsedTime(string.Format("{0}: Complete", _title));
var sb = new StringBuilder();
sb.AppendLine("Timers:");
sb.AppendLine(string.Join(Environment.NewLine, _perfMessages.ToArray()));
sb.AppendLine("Info:");
sb.AppendLine(string.Join(Environment.NewLine, _infoMessages.ToArray()));
if (IsTracingEnabled())
{
var logEntry = new LogEntry();
logEntry.Title = _title;
logEntry.Message = sb.ToString();
logEntry.Categories = new List<string>();
logEntry.Categories.Add("Performance");
logEntry.Severity = TraceEventType.Verbose;
_writer.Write(logEntry);
}
return sb.ToString();
}
public bool IsTracingEnabled()
{
return _eventLogEnabled && _writer != null && _writer.IsTracingEnabled();
}
}
public static class PerformanceTraceHelper
{
public static void LogPerformanceTrace(this IPerformanceTracer value, string message)
{
if (value != null) { value.WriteElapsedTime(message); }
}
public static void LogInfoTrace(this IPerformanceTracer value, string title, string message)
{
if (value != null) { value.WriteInfo(title, message); }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment