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

57 lines
1.9 KiB

  1. using System;
  2. using System.Text;
  3. using MQTTnet.Diagnostics;
  4. namespace MQTTnet.TestApp.NetCore
  5. {
  6. public static class MqttNetConsoleLogger
  7. {
  8. private 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. private static void PrintToConsole(object sender, MqttNetLogMessagePublishedEventArgs e)
  25. {
  26. var output = new StringBuilder();
  27. output.AppendLine($">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}");
  28. if (e.TraceMessage.Exception != null)
  29. {
  30. output.AppendLine(e.TraceMessage.Exception.ToString());
  31. }
  32. var color = ConsoleColor.Red;
  33. switch (e.TraceMessage.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. }