using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace LC.Newtonsoft.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;
private readonly object _lock;
///
/// Gets the that will be used to filter the trace messages passed to the writer.
/// For example a filter level of will exclude messages and include ,
/// and 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();
_lock = new object();
}
///
/// 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)
{
StringBuilder sb = new StringBuilder();
sb.Append(DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff", CultureInfo.InvariantCulture));
sb.Append(" ");
sb.Append(level.ToString("g"));
sb.Append(" ");
sb.Append(message);
string s = sb.ToString();
lock (_lock)
{
if (_traceMessages.Count >= 1000)
{
_traceMessages.Dequeue();
}
_traceMessages.Enqueue(s);
}
}
///
/// 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()
{
lock (_lock)
{
StringBuilder sb = new StringBuilder();
foreach (string traceMessage in _traceMessages)
{
if (sb.Length > 0)
{
sb.AppendLine();
}
sb.Append(traceMessage);
}
return sb.ToString();
}
}
}
}