Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

MqttNetLogger.cs 2.4 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. namespace MQTTnet.Diagnostics
  3. {
  4. public class MqttNetLogger : IMqttNetLogger
  5. {
  6. private readonly string _logId;
  7. public MqttNetLogger(string logId = null)
  8. {
  9. _logId = logId;
  10. }
  11. public event EventHandler<MqttNetLogMessagePublishedEventArgs> LogMessagePublished;
  12. public void Verbose<TSource>(string message, params object[] parameters)
  13. {
  14. Publish<TSource>(MqttNetLogLevel.Verbose, null, message, parameters);
  15. }
  16. public void Info<TSource>(string message, params object[] parameters)
  17. {
  18. Publish<TSource>(MqttNetLogLevel.Info, null, message, parameters);
  19. }
  20. public void Warning<TSource>(Exception exception, string message, params object[] parameters)
  21. {
  22. Publish<TSource>(MqttNetLogLevel.Warning, exception, message, parameters);
  23. }
  24. public void Warning<TSource>(string message, params object[] parameters)
  25. {
  26. Warning<TSource>(null, message, parameters);
  27. }
  28. public void Error<TSource>(Exception exception, string message, params object[] parameters)
  29. {
  30. Publish<TSource>(MqttNetLogLevel.Error, exception, message, parameters);
  31. }
  32. public void Error<TSource>(string message, params object[] parameters)
  33. {
  34. Warning<TSource>(null, message, parameters);
  35. }
  36. private void Publish<TSource>(MqttNetLogLevel logLevel, Exception exception, string message, object[] parameters)
  37. {
  38. var hasLocalListeners = LogMessagePublished != null;
  39. var hasGlobalListeners = MqttNetGlobalLogger.HasListeners;
  40. if (!hasLocalListeners && !hasGlobalListeners)
  41. {
  42. return;
  43. }
  44. if (parameters.Length > 0)
  45. {
  46. message = string.Format(message, parameters);
  47. }
  48. var traceMessage = new MqttNetLogMessage(_logId, DateTime.Now, Environment.CurrentManagedThreadId, typeof(TSource).Name, logLevel, message, exception);
  49. if (hasGlobalListeners)
  50. {
  51. MqttNetGlobalLogger.Publish(traceMessage);
  52. }
  53. if (hasLocalListeners)
  54. {
  55. LogMessagePublished?.Invoke(this, new MqttNetLogMessagePublishedEventArgs(traceMessage));
  56. }
  57. }
  58. }
  59. }