No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 

74 líneas
2.4 KiB

  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 Trace<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. }