25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

57 lines
1.8 KiB

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