Skip to content

Instantly share code, notes, and snippets.

@robertaarcoverde
Created May 21, 2013 18:31
Show Gist options
  • Save robertaarcoverde/5622122 to your computer and use it in GitHub Desktop.
Save robertaarcoverde/5622122 to your computer and use it in GitHub Desktop.
performance tracing using the IDisposable pattern and MS Enterprise Library. usage example: using (new PerformanceLogger("some time consuming routine")) { //do something }
public class PerformanceLogger : IDisposable
{
private Stopwatch sw;
private string context;
public PerformanceLogger(string context)
{
this.context = context;
this.sw = Stopwatch.StartNew();
}
public void Dispose()
{
StopTrace();
}
private void StopTrace()
{
this.sw.Stop();
var ellapsedTime = sw.ElapsedMilliseconds.ToString().PadLeft(5, ' ');
var message = String.Format("TIME: {0} - CONTEXT: {1}", ellapsedTime, context);
var logEntry = new LogEntry {
Message = message,
Severity = TraceEventType.Information,
TimeStamp = DateTime.Now
};
this.LogPerformance(logEntry);
}
private void LogPerformance(LogEntry logEntry)
{
try {
if (Logger.IsLoggingEnabled())
{
logEntry.Categories = new string[] { "Performance" }; //watch out for the magic string
Logger.Write(logEntry);
}
} catch (Exception) {
//ignore errors on logging
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment