#if HAVE_TRACE_WRITER
using System;
using System.Diagnostics;
using DiagnosticsTrace = System.Diagnostics.Trace;
namespace LC.Newtonsoft.Json.Serialization
{
///
/// Represents a trace writer that writes to the application's instances.
///
public class DiagnosticsTraceWriter : ITraceWriter
{
///
/// 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; }
private TraceEventType GetTraceEventType(TraceLevel level)
{
switch (level)
{
case TraceLevel.Error:
return TraceEventType.Error;
case TraceLevel.Warning:
return TraceEventType.Warning;
case TraceLevel.Info:
return TraceEventType.Information;
case TraceLevel.Verbose:
return TraceEventType.Verbose;
default:
throw new ArgumentOutOfRangeException(nameof(level));
}
}
///
/// 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 (level == TraceLevel.Off)
{
return;
}
TraceEventCache eventCache = new TraceEventCache();
TraceEventType traceEventType = GetTraceEventType(level);
foreach (TraceListener listener in DiagnosticsTrace.Listeners)
{
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.TraceEvent(eventCache, "Newtonsoft.Json", traceEventType, 0, message);
}
}
else
{
listener.TraceEvent(eventCache, "Newtonsoft.Json", traceEventType, 0, message);
}
if (DiagnosticsTrace.AutoFlush)
{
listener.Flush();
}
}
}
}
}
#endif