LoggerUtils.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Globalization;
  3. using MediaBrowser.Model.Services;
  4. using Microsoft.Extensions.Logging;
  5. namespace Emby.Server.Implementations.HttpServer
  6. {
  7. public static class LoggerUtils
  8. {
  9. public static void LogRequest(ILogger logger, string url, string method, string userAgent, QueryParamCollection headers)
  10. {
  11. if (headers == null)
  12. {
  13. logger.LogInformation("{0} {1}. UserAgent: {2}", "HTTP " + method, url, userAgent ?? string.Empty);
  14. }
  15. else
  16. {
  17. var headerText = string.Empty;
  18. var index = 0;
  19. foreach (var i in headers)
  20. {
  21. if (index > 0)
  22. {
  23. headerText += ", ";
  24. }
  25. headerText += i.Name + "=" + i.Value;
  26. index++;
  27. }
  28. logger.LogInformation("HTTP {0} {1}. {2}", method, url, headerText);
  29. }
  30. }
  31. /// <summary>
  32. /// Logs the response.
  33. /// </summary>
  34. /// <param name="logger">The logger.</param>
  35. /// <param name="statusCode">The status code.</param>
  36. /// <param name="url">The URL.</param>
  37. /// <param name="endPoint">The end point.</param>
  38. /// <param name="duration">The duration.</param>
  39. public static void LogResponse(ILogger logger, int statusCode, string url, string endPoint, TimeSpan duration, QueryParamCollection headers)
  40. {
  41. var durationMs = duration.TotalMilliseconds;
  42. var logSuffix = durationMs >= 1000 && durationMs < 60000 ? "ms (slow)" : "ms";
  43. //var headerText = headers == null ? string.Empty : "Headers: " + string.Join(", ", headers.Where(i => i.Name.IndexOf("Access-", StringComparison.OrdinalIgnoreCase) == -1).Select(i => i.Name + "=" + i.Value).ToArray());
  44. var headerText = string.Empty;
  45. logger.LogInformation("HTTP Response {0} to {1}. Time: {2}{3}. {4} {5}", statusCode, endPoint, Convert.ToInt32(durationMs).ToString(CultureInfo.InvariantCulture), logSuffix, url, headerText);
  46. }
  47. }
  48. }