Click or drag to resize
Json.NETCustom ITraceWriter
 

This sample creates a custom ITraceWriter that writes to NLog.

Sample
Types
 1public class NLogTraceWriter : ITraceWriter
 2{
 3    private static readonly Logger Logger = LogManager.GetLogger("NLogTraceWriter");
 4
 5    public TraceLevel LevelFilter
 6    {
 7        // trace all messages. nlog can handle filtering
 8        get { return TraceLevel.Verbose; }
 9    }
10
11    public void Trace(TraceLevel level, string message, Exception ex)
12    {
13        LogEventInfo logEvent = new LogEventInfo
14        {
15            Message = message,
16            Level = GetLogLevel(level),
17            Exception = ex
18        };
19
20        // log Json.NET message to NLog
21        Logger.Log(logEvent);
22    }
23
24    private LogLevel GetLogLevel(TraceLevel level)
25    {
26        switch (level)
27        {
28            case TraceLevel.Error:
29                return LogLevel.Error;
30            case TraceLevel.Warning:
31                return LogLevel.Warn;
32            case TraceLevel.Info:
33                return LogLevel.Info;
34            case TraceLevel.Off:
35                return LogLevel.Off;
36            default:
37                return LogLevel.Trace;
38        }
39    }
40}
Usage
 1IList<string> countries = new List<string>
 2{
 3    "New Zealand",
 4    "Australia",
 5    "Denmark",
 6    "China"
 7};
 8
 9string json = JsonConvert.SerializeObject(countries, Formatting.Indented, new JsonSerializerSettings
10{
11    TraceWriter = new NLogTraceWriter()
12});
13
14Console.WriteLine(json);
15// [
16//   "New Zealand",
17//   "Australia",
18//   "Denmark",
19//   "China"
20// ]