using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Text; namespace DPumpHydr.WinFrmUI.WenSkin.Json.Serialization { /// /// Represents a trace writer that writes to memory. When the trace message limit is /// reached then old trace messages will be removed as new messages are added. /// public class MemoryTraceWriter : ITraceWriter { private readonly Queue _traceMessages; /// /// Gets the that will be used to filter the trace messages passed to the writer. /// For example a filter level of Info will exclude Verbose messages and include Info, /// Warning and Error messages. /// /// /// The that will be used to filter the trace messages passed to the writer. /// public TraceLevel LevelFilter { get; set; } /// /// Initializes a new instance of the class. /// public MemoryTraceWriter() { LevelFilter = TraceLevel.Verbose; _traceMessages = new Queue(); } /// /// Writes the specified trace level, message and optional exception. /// /// The at which to write this trace. /// The trace message. /// The trace exception. This parameter is optional. public void Trace(TraceLevel level, string message, Exception ex) { if (_traceMessages.Count >= 1000) { _traceMessages.Dequeue(); } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff", CultureInfo.InvariantCulture)); stringBuilder.Append(" "); stringBuilder.Append(level.ToString("g")); stringBuilder.Append(" "); stringBuilder.Append(message); _traceMessages.Enqueue(stringBuilder.ToString()); } /// /// Returns an enumeration of the most recent trace messages. /// /// An enumeration of the most recent trace messages. public IEnumerable GetTraceMessages() { return _traceMessages; } /// /// Returns a of the most recent trace messages. /// /// /// A of the most recent trace messages. /// public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); foreach (string traceMessage in _traceMessages) { if (stringBuilder.Length > 0) { stringBuilder.AppendLine(); } stringBuilder.Append(traceMessage); } return stringBuilder.ToString(); } } }