Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 

78 wiersze
2.7 KiB

  1. using System;
  2. namespace MQTTnet.Core.Diagnostics
  3. {
  4. public sealed class MqttNetTrace : IMqttNetTraceHandler
  5. {
  6. private readonly IMqttNetTraceHandler _traceHandler;
  7. public MqttNetTrace(IMqttNetTraceHandler customTraceHandler = null)
  8. {
  9. _traceHandler = customTraceHandler ?? this;
  10. }
  11. public static event EventHandler<MqttNetTraceMessagePublishedEventArgs> TraceMessagePublished;
  12. public bool IsEnabled => TraceMessagePublished != null;
  13. public void Verbose(string source, string message, params object[] parameters)
  14. {
  15. Publish(source, MqttNetTraceLevel.Verbose, null, message, parameters);
  16. }
  17. public void Information(string source, string message, params object[] parameters)
  18. {
  19. Publish(source, MqttNetTraceLevel.Information, null, message, parameters);
  20. }
  21. public void Warning(string source, string message, params object[] parameters)
  22. {
  23. Publish(source, MqttNetTraceLevel.Warning, null, message, parameters);
  24. }
  25. public void Warning(string source, Exception exception, string message, params object[] parameters)
  26. {
  27. Publish(source, MqttNetTraceLevel.Warning, exception, message, parameters);
  28. }
  29. public void Error(string source, string message, params object[] parameters)
  30. {
  31. Publish(source, MqttNetTraceLevel.Error, null, message, parameters);
  32. }
  33. public void Error(string source, Exception exception, string message, params object[] parameters)
  34. {
  35. Publish(source, MqttNetTraceLevel.Error, exception, message, parameters);
  36. }
  37. public void HandleTraceMessage(MqttNetTraceMessage mqttNetTraceMessage)
  38. {
  39. TraceMessagePublished?.Invoke(this, new MqttNetTraceMessagePublishedEventArgs(mqttNetTraceMessage));
  40. }
  41. private void Publish(string source, MqttNetTraceLevel traceLevel, Exception exception, string message, params object[] parameters)
  42. {
  43. if (!_traceHandler.IsEnabled)
  44. {
  45. return;
  46. }
  47. var now = DateTime.Now;
  48. if (parameters?.Length > 0)
  49. {
  50. try
  51. {
  52. message = string.Format(message, parameters);
  53. }
  54. catch (Exception formatException)
  55. {
  56. Error(nameof(MqttNetTrace), formatException, "Error while tracing message: " + message);
  57. return;
  58. }
  59. }
  60. _traceHandler.HandleTraceMessage(new MqttNetTraceMessage(now, Environment.CurrentManagedThreadId, source, traceLevel, message, exception));
  61. }
  62. }
  63. }