ClientEventLogger.cs 2.3 KB

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