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.
 
 
 
 

65 lines
2.3 KiB

  1. using System;
  2. using System.Linq;
  3. namespace MQTTnet.Core.Diagnostics
  4. {
  5. public static class MqttTrace
  6. {
  7. public static event EventHandler<MqttTraceMessagePublishedEventArgs> TraceMessagePublished;
  8. public static void Verbose(string source, string message, params object[] parameters)
  9. {
  10. Publish(source, MqttTraceLevel.Verbose, null, message, parameters);
  11. }
  12. public static void Information(string source, string message, params object[] parameters)
  13. {
  14. Publish(source, MqttTraceLevel.Information, null, message, parameters);
  15. }
  16. public static void Warning(string source, string message, params object[] parameters)
  17. {
  18. Publish(source, MqttTraceLevel.Warning, null, message, parameters);
  19. }
  20. public static void Warning(string source, Exception exception, string message, params object[] parameters)
  21. {
  22. Publish(source, MqttTraceLevel.Warning, exception, message, parameters);
  23. }
  24. public static void Error(string source, string message, params object[] parameters)
  25. {
  26. Publish(source, MqttTraceLevel.Error, null, message, parameters);
  27. }
  28. public static void Error(string source, Exception exception, string message, params object[] parameters)
  29. {
  30. Publish(source, MqttTraceLevel.Error, exception, message, parameters);
  31. }
  32. private static void Publish(string source, MqttTraceLevel traceLevel, Exception exception, string message, params object[] parameters)
  33. {
  34. var handler = TraceMessagePublished;
  35. if (handler == null)
  36. {
  37. return;
  38. }
  39. if (parameters?.Length > 0)
  40. {
  41. try
  42. {
  43. message = string.Format(message, parameters);
  44. }
  45. catch (Exception formatException)
  46. {
  47. Error(nameof(MqttTrace), formatException, "Error while tracing message: " + message);
  48. return;
  49. }
  50. }
  51. handler.Invoke(null, new MqttTraceMessagePublishedEventArgs(Environment.CurrentManagedThreadId, source, traceLevel, message, exception));
  52. }
  53. }
  54. }