LogHub.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using Log;
  2. using Microsoft.AspNetCore.SignalR.Client;
  3. using System.Text;
  4. using Universal;
  5. namespace OnlineLogViewer;
  6. public class LogInfo(LogLevel logLevel, string message, DateTime dateTime)
  7. {
  8. public LogLevel Level { get; } = logLevel;
  9. public string Message { get; } = message;
  10. public DateTime DateTime { get; } = dateTime;
  11. }
  12. public class LogHub
  13. {
  14. public LogHub()
  15. {
  16. this._LogEventQueue = new(LogHandler);
  17. }
  18. private HubConnection? _hubConnection;
  19. public readonly EventQueue<LogInfo> _LogEventQueue;
  20. private int _logLevel;
  21. private static void LogHandler(LogInfo logInfo)
  22. {
  23. StringBuilder sb = new();
  24. sb.Append(logInfo.Level.ToString().PadRight(10));
  25. sb.Append(logInfo.DateTime.ToString("HH:mm:ss.ff").PadRight(18));
  26. sb.Append(logInfo.Message);
  27. Console.WriteLine(sb);
  28. }
  29. public bool Initialize(string ip, int port, string hub, LogLevel logLevel)
  30. {
  31. if (_hubConnection is not null)
  32. return false;
  33. this._logLevel = (int)logLevel;
  34. HubConnection temp = new HubConnectionBuilder().WithUrl($"http://{ip}:{port}/{hub}").WithAutomaticReconnect().Build();
  35. temp.On<string, DateTime>("Debug", this.Debug);
  36. temp.On<string, DateTime>("Info", this.Info);
  37. temp.On<string, DateTime>("Warning", this.Warning);
  38. temp.On<string, DateTime>("Error", this.Error);
  39. temp.On<string, DateTime>("Fatal", this.Fatal);
  40. while (true)
  41. {
  42. try
  43. {
  44. temp.StartAsync().Wait();
  45. _hubConnection = temp;
  46. Console.WriteLine("Connected");
  47. break;
  48. }
  49. catch
  50. {
  51. Thread.Sleep(1000);
  52. }
  53. }
  54. return true;
  55. }
  56. public void Debug(string message, DateTime dateTime)
  57. {
  58. this._LogEventQueue.Enqueue(new(LogLevel.Debug, message, dateTime));
  59. }
  60. public void Info(string message, DateTime dateTime)
  61. {
  62. if (_logLevel < (int)LogLevel.Info)
  63. return;
  64. this._LogEventQueue.Enqueue(new(LogLevel.Info, message, dateTime));
  65. }
  66. public void Warning(string message, DateTime dateTime)
  67. {
  68. if (_logLevel < (int)LogLevel.Warning)
  69. return;
  70. this._LogEventQueue.Enqueue(new(LogLevel.Warning, message, dateTime));
  71. }
  72. public void Error(string message, DateTime dateTime)
  73. {
  74. if (_logLevel < (int)LogLevel.Error)
  75. return;
  76. this._LogEventQueue.Enqueue(new(LogLevel.Error, message, dateTime));
  77. }
  78. public void Fatal(string message, DateTime dateTime)
  79. {
  80. if (_logLevel < (int)LogLevel.Fatal)
  81. return;
  82. this._LogEventQueue.Enqueue(new(LogLevel.Fatal, message, dateTime));
  83. }
  84. }