Created
May 21, 2013 18:31
-
-
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
}
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
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