HeaderRecordService.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using Azure.Core;
  2. using HeaderRecord;
  3. using Microsoft.AspNetCore.Builder;
  4. using Microsoft.AspNetCore.Http;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using Microsoft.Extensions.Logging;
  7. using System.Net.Http;
  8. namespace EVCB_OCPP.Service
  9. {
  10. public static partial class AppExtention
  11. {
  12. public static void AddHeaderRecordService(this IServiceCollection services)
  13. {
  14. services.AddTransient<HeaderRecordService>();
  15. }
  16. public static void UseHeaderRecordService(this WebApplication webApplication)
  17. {
  18. webApplication.Use(async (context, next) =>
  19. {
  20. var servcie = context.RequestServices.GetService<HeaderRecordService>();
  21. servcie.LogRequest(context.TraceIdentifier, context.Request);
  22. await next(context);
  23. servcie.LogResponse(context.TraceIdentifier, context.Response);
  24. return;
  25. });
  26. }
  27. }
  28. }
  29. namespace HeaderRecord
  30. {
  31. public class HeaderRecordService
  32. {
  33. private readonly ILogger<HeaderRecordService> logger;
  34. public HeaderRecordService(ILogger<HeaderRecordService> logger)
  35. {
  36. this.logger = logger;
  37. }
  38. internal void LogRequest(string traceIdentifier, HttpRequest request)
  39. {
  40. logger.LogInformation("LogRequest============================================================");
  41. logger.LogInformation("{id} {method} {path} {protocol}", traceIdentifier, request.Method, request.Path, request.Protocol);
  42. foreach (var headerKey in request.Headers.Keys)
  43. {
  44. logger.LogInformation("{id} {key} {value}", traceIdentifier, headerKey, request.Headers[headerKey]);
  45. }
  46. logger.LogInformation("LogRequest============================================================");
  47. }
  48. internal void LogResponse(string traceIdentifier, HttpResponse response)
  49. {
  50. logger.LogInformation("LogResponse============================================================");
  51. foreach (var headerKey in response.Headers.Keys)
  52. {
  53. logger.LogInformation("{id} {key} {value}", traceIdentifier, headerKey, response.Headers[headerKey]);
  54. }
  55. logger.LogInformation("LogResponse============================================================");
  56. }
  57. }
  58. }