-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpMessageLoggingMiddleware.cs
More file actions
156 lines (133 loc) · 5.97 KB
/
HttpMessageLoggingMiddleware.cs
File metadata and controls
156 lines (133 loc) · 5.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
using Application;
using Serilog.Context;
using Shared;
using System.Diagnostics;
using System.Security.Claims;
using System.Text.Json;
namespace WebApi
{
public class HttpMessageLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<HttpMessageLoggingMiddleware> _logger;
public HttpMessageLoggingMiddleware(RequestDelegate next,
ILogger<HttpMessageLoggingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext httpContext)
{
if (httpContext.GetEndpoint()?.Metadata?.GetMetadata<SkipLogAttribute>() is not null)
{
await _next(httpContext);
}
else
{
using (LogContext.PushProperty(LoggerContextProperty.ActionType.ToString(), LoggerContext.WebApi))
using (LogContext.PushProperty(LoggerContextProperty.TraceId.ToString(), httpContext.GetTraceId()))
using (LogContext.PushProperty(LoggerContextProperty.CorrelationId.ToString(), httpContext.GetCorrelationId()))
{
httpContext.Request.EnableBuffering();
string? requestBody = await ReadBodyAsync(httpContext.Request.Body);
if (string.IsNullOrWhiteSpace(requestBody))
requestBody = null;
using Stream originalResponseBody = httpContext.Response.Body;
using var tempResponseBody = new MemoryStream();
httpContext.Response.Body = tempResponseBody;
Stopwatch requestDuration = Stopwatch.StartNew();
await _next(httpContext);
requestDuration.Stop();
string? responseBody = await ReadBodyAsync(httpContext.Response.Body);
await tempResponseBody.CopyToAsync(originalResponseBody);
httpContext.Response.Body = originalResponseBody;
if (string.IsNullOrWhiteSpace(responseBody))
responseBody = null;
LogAction(httpContext, requestBody, responseBody, requestDuration);
}
}
}
private void LogAction(HttpContext httpContext, string? requestBody, string? responseBody, Stopwatch requestDuration)
{
SensitiveDataAttribute? sensitiveData = httpContext.GetEndpoint()?.Metadata?.GetMetadata<SensitiveDataAttribute>();
bool isSuccessStatusCode = httpContext.Response.StatusCode >= StatusCodes.Status200OK && httpContext.Response.StatusCode < StatusCodes.Status300MultipleChoices;
bool isRequestSensitive = sensitiveData is not null && sensitiveData.IsRequestSensitive;
bool isResponseSensitive = isSuccessStatusCode && sensitiveData is not null && sensitiveData.IsResponseSensitive;
var action = new HttpAction()
{
StatusCode = httpContext.Response.StatusCode,
Method = httpContext.Request.Method,
Duration = requestDuration.ElapsedMilliseconds,
FromIp = httpContext.GetIpAddresses(),
User = GetUser(httpContext, requestBody),
RequestData = isRequestSensitive ? null : requestBody,
ResponseData = isResponseSensitive ? null : responseBody
};
if (isSuccessStatusCode)
{
_logger.LogInformation("Request finished successful: {@HttpAction}", action);
}
else
{
_logger.LogError("Request finished with error: {@HttpAction}", action);
}
}
private static string? GetUser(HttpContext httpContext, string? requestBody)
{
string? user = null;
try
{
string? authorization = httpContext.GetAuthorization();
if (!string.IsNullOrWhiteSpace(authorization))
{
var authorizationObj = new Authorization(authorization);
if (authorizationObj.Schema == AuthorizationSchema.Basic)
{
user = new BasicCredentials(authorizationObj).Key;
}
else if (authorizationObj.Schema == AuthorizationSchema.Bearer)
{
user = httpContext.User.FindFirstValue(TokenClaim.Username.GetDescription());
if (string.IsNullOrWhiteSpace(user))
user = httpContext.User.FindFirstValue(TokenClaim.ClientId.GetDescription());
}
}
else if (!string.IsNullOrWhiteSpace(requestBody))
{
try
{
var credentials = JsonSerializer.Deserialize<V1.CreateOtpRequest>(requestBody) ?? throw new ArgumentException();
user = credentials.Username;
}
catch
{
var credentials = JsonSerializer.Deserialize<V2.UserCredentialsResponse>(requestBody) ?? throw new ArgumentException();
user = credentials.Username;
}
}
}
catch
{
// continue
}
return user;
}
private async Task<string> ReadBodyAsync(Stream body)
{
string bodyMsg = string.Empty;
try
{
bodyMsg = await body.ReadToEndAsync();
if (!string.IsNullOrWhiteSpace(bodyMsg))
{
bodyMsg = bodyMsg.RemoveJsonFormatting();
}
}
catch (Exception exception)
{
_logger.LogError(exception, exception.Message);
}
return bodyMsg;
}
}
}