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.
 
 
 
 

59 lines
1.9 KiB

  1. using System;
  2. using System.Text;
  3. using MQTTnet.Diagnostics.Logger;
  4. namespace MQTTnet.TestApp.NetCore
  5. {
  6. public static class MqttNetConsoleLogger
  7. {
  8. static readonly object _lock = new object();
  9. public static void ForwardToConsole(MqttNetEventLogger logger)
  10. {
  11. if (logger == null) throw new ArgumentNullException(nameof(logger));
  12. logger.LogMessagePublished -= PrintToConsole;
  13. logger.LogMessagePublished += PrintToConsole;
  14. }
  15. public static void PrintToConsole(string message, ConsoleColor color)
  16. {
  17. lock (_lock)
  18. {
  19. var backupColor = Console.ForegroundColor;
  20. Console.ForegroundColor = color;
  21. Console.Write(message);
  22. Console.ForegroundColor = backupColor;
  23. }
  24. }
  25. static void PrintToConsole(object sender, MqttNetLogMessagePublishedEventArgs e)
  26. {
  27. var output = new StringBuilder();
  28. output.AppendLine($">> [{e.LogMessage.Timestamp:O}] [{e.LogMessage.ThreadId}] [{e.LogMessage.Source}] [{e.LogMessage.Level}]: {e.LogMessage.Message}");
  29. if (e.LogMessage.Exception != null)
  30. {
  31. output.AppendLine(e.LogMessage.Exception.ToString());
  32. }
  33. var color = ConsoleColor.Red;
  34. switch (e.LogMessage.Level)
  35. {
  36. case MqttNetLogLevel.Error:
  37. color = ConsoleColor.Red;
  38. break;
  39. case MqttNetLogLevel.Warning:
  40. color = ConsoleColor.Yellow;
  41. break;
  42. case MqttNetLogLevel.Info:
  43. color = ConsoleColor.Green;
  44. break;
  45. case MqttNetLogLevel.Verbose:
  46. color = ConsoleColor.Gray;
  47. break;
  48. }
  49. PrintToConsole(output.ToString(), color);
  50. }
  51. }
  52. }