You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.9 KiB

  1. using System;
  2. using System.Diagnostics;
  3. using DiagnosticsTrace = System.Diagnostics.Trace;
  4. namespace Newtonsoft.Json.Serialization
  5. {
  6. /// <summary>
  7. /// Represents a trace writer that writes to the application's <see cref="TraceListener"/> instances.
  8. /// </summary>
  9. internal class DiagnosticsTraceWriter : ITraceWriter
  10. {
  11. /// <summary>
  12. /// Gets the <see cref="TraceLevel"/> that will be used to filter the trace messages passed to the writer.
  13. /// For example a filter level of <see cref="TraceLevel.Info"/> will exclude <see cref="TraceLevel.Verbose"/> messages and include <see cref="TraceLevel.Info"/>,
  14. /// <see cref="TraceLevel.Warning"/> and <see cref="TraceLevel.Error"/> messages.
  15. /// </summary>
  16. /// <value>
  17. /// The <see cref="TraceLevel"/> that will be used to filter the trace messages passed to the writer.
  18. /// </value>
  19. public TraceLevel LevelFilter { get; set; }
  20. private TraceEventType GetTraceEventType(TraceLevel level)
  21. {
  22. switch (level)
  23. {
  24. case TraceLevel.Error:
  25. return TraceEventType.Error;
  26. case TraceLevel.Warning:
  27. return TraceEventType.Warning;
  28. case TraceLevel.Info:
  29. return TraceEventType.Information;
  30. case TraceLevel.Verbose:
  31. return TraceEventType.Verbose;
  32. default:
  33. throw new ArgumentOutOfRangeException(nameof(level));
  34. }
  35. }
  36. /// <summary>
  37. /// Writes the specified trace level, message and optional exception.
  38. /// </summary>
  39. /// <param name="level">The <see cref="TraceLevel"/> at which to write this trace.</param>
  40. /// <param name="message">The trace message.</param>
  41. /// <param name="ex">The trace exception. This parameter is optional.</param>
  42. public void Trace(TraceLevel level, string message, Exception ex)
  43. {
  44. if (level == TraceLevel.Off)
  45. {
  46. return;
  47. }
  48. TraceEventCache eventCache = new TraceEventCache();
  49. TraceEventType traceEventType = GetTraceEventType(level);
  50. foreach (TraceListener listener in DiagnosticsTrace.Listeners)
  51. {
  52. if (!listener.IsThreadSafe)
  53. {
  54. lock (listener)
  55. {
  56. listener.TraceEvent(eventCache, "Newtonsoft.Json", traceEventType, 0, message);
  57. }
  58. }
  59. else
  60. {
  61. listener.TraceEvent(eventCache, "Newtonsoft.Json", traceEventType, 0, message);
  62. }
  63. if (DiagnosticsTrace.AutoFlush)
  64. {
  65. listener.Flush();
  66. }
  67. }
  68. }
  69. }
  70. }