StartupLogger.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using Jellyfin.Server.Migrations.Routines;
  6. using Microsoft.Extensions.Logging;
  7. namespace Jellyfin.Server.ServerSetupApp;
  8. /// <inheritdoc/>
  9. public class StartupLogger : IStartupLogger
  10. {
  11. private readonly SetupServer.StartupLogEntry? _groupEntry;
  12. /// <summary>
  13. /// Initializes a new instance of the <see cref="StartupLogger"/> class.
  14. /// </summary>
  15. public StartupLogger()
  16. {
  17. Loggers = [];
  18. }
  19. /// <summary>
  20. /// Initializes a new instance of the <see cref="StartupLogger"/> class.
  21. /// </summary>
  22. private StartupLogger(SetupServer.StartupLogEntry? groupEntry) : this()
  23. {
  24. _groupEntry = groupEntry;
  25. }
  26. internal static IStartupLogger Logger { get; } = new StartupLogger();
  27. private List<ILogger> Loggers { get; set; }
  28. /// <inheritdoc/>
  29. public IStartupLogger BeginGroup(FormattableString logEntry)
  30. {
  31. var startupEntry = new SetupServer.StartupLogEntry()
  32. {
  33. Content = logEntry.ToString(CultureInfo.InvariantCulture),
  34. DateOfCreation = DateTimeOffset.Now
  35. };
  36. if (_groupEntry is null)
  37. {
  38. SetupServer.LogQueue?.Enqueue(startupEntry);
  39. }
  40. else
  41. {
  42. _groupEntry.Children.Add(startupEntry);
  43. }
  44. return new StartupLogger(startupEntry);
  45. }
  46. /// <inheritdoc/>
  47. public IDisposable? BeginScope<TState>(TState state)
  48. where TState : notnull
  49. {
  50. return null;
  51. }
  52. /// <inheritdoc/>
  53. public bool IsEnabled(LogLevel logLevel)
  54. {
  55. return true;
  56. }
  57. /// <inheritdoc/>
  58. public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
  59. {
  60. foreach (var item in Loggers.Where(e => e.IsEnabled(logLevel)))
  61. {
  62. item.Log(logLevel, eventId, state, exception, formatter);
  63. }
  64. var startupEntry = new SetupServer.StartupLogEntry()
  65. {
  66. LogLevel = logLevel,
  67. Content = formatter(state, exception),
  68. DateOfCreation = DateTimeOffset.Now
  69. };
  70. if (_groupEntry is null)
  71. {
  72. SetupServer.LogQueue?.Enqueue(startupEntry);
  73. }
  74. else
  75. {
  76. _groupEntry.Children.Add(startupEntry);
  77. }
  78. }
  79. /// <inheritdoc/>
  80. public IStartupLogger With(ILogger logger)
  81. {
  82. return new StartupLogger(_groupEntry)
  83. {
  84. Loggers = [.. Loggers, logger]
  85. };
  86. }
  87. }