ClientEventLogger.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. using MediaBrowser.Controller.Net;
  5. using MediaBrowser.Model.ClientLog;
  6. using Microsoft.Extensions.Logging;
  7. namespace MediaBrowser.Controller.ClientEvent
  8. {
  9. /// <inheritdoc />
  10. public class ClientEventLogger : IClientEventLogger
  11. {
  12. private const string LogString = "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level}] [{ClientName}:{ClientVersion}]: UserId: {UserId} DeviceId: {DeviceId}{NewLine}{Message}";
  13. private readonly ILogger<ClientEventLogger> _logger;
  14. private readonly IServerApplicationPaths _applicationPaths;
  15. /// <summary>
  16. /// Initializes a new instance of the <see cref="ClientEventLogger"/> class.
  17. /// </summary>
  18. /// <param name="logger">Instance of the <see cref="ILogger{ClientEventLogger}"/> interface.</param>
  19. /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param>
  20. public ClientEventLogger(
  21. ILogger<ClientEventLogger> logger,
  22. IServerApplicationPaths applicationPaths)
  23. {
  24. _logger = logger;
  25. _applicationPaths = applicationPaths;
  26. }
  27. /// <inheritdoc />
  28. public void Log(ClientLogEvent clientLogEvent)
  29. {
  30. _logger.Log(
  31. LogLevel.Critical,
  32. LogString,
  33. clientLogEvent.Timestamp,
  34. clientLogEvent.Level.ToString(),
  35. clientLogEvent.ClientName,
  36. clientLogEvent.ClientVersion,
  37. clientLogEvent.UserId ?? Guid.Empty,
  38. clientLogEvent.DeviceId,
  39. Environment.NewLine,
  40. clientLogEvent.Message);
  41. }
  42. /// <inheritdoc />
  43. public async Task<string> WriteDocumentAsync(AuthorizationInfo authorizationInfo, Stream fileContents)
  44. {
  45. var fileName = $"upload_{authorizationInfo.Client}_{(authorizationInfo.IsApiKey ? "apikey" : authorizationInfo.Version)}_{DateTime.UtcNow:yyyyMMddHHmmss}.log";
  46. var logFilePath = Path.Combine(_applicationPaths.LogDirectoryPath, fileName);
  47. await using var fileStream = new FileStream(logFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None);
  48. await fileContents.CopyToAsync(fileStream).ConfigureAwait(false);
  49. await fileStream.FlushAsync().ConfigureAwait(false);
  50. return fileName;
  51. }
  52. }
  53. }