//----------------------------------------------------------------------- // // Copyright (c) 2009 Craig Sutherland. All rights reserved. // //----------------------------------------------------------------------- namespace FastForward.WinCore { using System; using System.Collections.Generic; using System.Linq; using System.Text; using NLog; using System.Threading; using System.Diagnostics; /// /// Provides tracing functionality. /// public class Trace : IDisposable { #region Private fields #region logFactory /// /// The to use in initialising new loggers. /// private static LogFactory logFactory = new LogFactory(); #endregion #region currentId /// /// The currently available identifier. /// private static int currentId = 0; #endregion #region logger /// /// The logger to use. /// private Logger logger; #endregion #region id /// /// The id of the current trace. /// private int id; #endregion #region hasFinished /// /// Has this trace finished yet? /// private bool hasFinished; #endregion #endregion #region Constructors /// /// Initialise a new . /// /// The logger to use. /// The identifier of the trace. private Trace(Logger logger, int id) { this.logger = logger; this.id = id; } #endregion #region Public properties #region MethodName /// /// The method being traced. /// public string MethodName { get; set; } #endregion #endregion #region Public methods #region Start() /// /// Starts a new trace event. /// /// The description of the trace event. /// The new instance. public static Trace Start(string description) { var newId = Interlocked.Increment(ref Trace.currentId); var logger = Trace.logFactory.GetLogger("Trace.Logger"); var trace = new Trace(logger, newId); if (logger.IsTraceEnabled) { var frame = new StackFrame(1); var method = frame.GetMethod(); trace.MethodName = method.DeclaringType.FullName + "." + method.Name; var message = newId.ToString("00000") + "->" + trace.MethodName + " start: " + description ?? string.Empty; logger.Trace(message); } return trace; } #endregion #region Finish() /// /// Finishes a trace. /// public void Finish() { this.hasFinished = true; if (this.logger.IsTraceEnabled) { var message = this.id.ToString("00000") + "->" + this.MethodName + " end"; this.logger.Trace(message); } } #endregion #region Dispose() /// /// Clean up and end the trace. /// public void Dispose() { if (!hasFinished) { this.Finish(); } } #endregion #endregion } }