Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 

56 righe
1.6 KiB

  1. using System;
  2. namespace MQTTnet.Diagnostics
  3. {
  4. public sealed 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 IMqttNetChildLogger CreateChildLogger(string source = null)
  13. {
  14. return new MqttNetChildLogger(this, source);
  15. }
  16. public void Publish(MqttNetLogLevel logLevel, string source, string message, object[] parameters, Exception exception)
  17. {
  18. var hasLocalListeners = LogMessagePublished != null;
  19. var hasGlobalListeners = MqttNetGlobalLogger.HasListeners;
  20. if (!hasLocalListeners && !hasGlobalListeners)
  21. {
  22. return;
  23. }
  24. if (parameters?.Length > 0)
  25. {
  26. try
  27. {
  28. message = string.Format(message, parameters);
  29. }
  30. catch
  31. {
  32. message = "MESSAGE FORMAT INVALID: " + message;
  33. }
  34. }
  35. var traceMessage = new MqttNetLogMessage(_logId, DateTime.UtcNow, Environment.CurrentManagedThreadId, source, logLevel, message, exception);
  36. if (hasGlobalListeners)
  37. {
  38. MqttNetGlobalLogger.Publish(traceMessage);
  39. }
  40. if (hasLocalListeners)
  41. {
  42. LogMessagePublished?.Invoke(this, new MqttNetLogMessagePublishedEventArgs(traceMessage));
  43. }
  44. }
  45. }
  46. }