Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

63 lignes
2.1 KiB

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