| | | 1 | | using System.Diagnostics; |
| | | 2 | | using Microsoft.Extensions.Options; |
| | | 3 | | using Microsoft.Extensions.Primitives; |
| | | 4 | | using ProjectTemplate.Web.Options; |
| | | 5 | | using Serilog; |
| | | 6 | | using Serilog.Context; |
| | | 7 | | using Serilog.Events; |
| | | 8 | | |
| | | 9 | | namespace ProjectTemplate.Web.Extensions; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Provides extension methods for configuring structured HTTP request logging. |
| | | 13 | | /// </summary> |
| | | 14 | | public static class RequestLoggingExtensions |
| | | 15 | | { |
| | | 16 | | /// <summary> |
| | | 17 | | /// Registers structured request logging options. |
| | | 18 | | /// </summary> |
| | | 19 | | /// <param name="services">The service collection to configure.</param> |
| | | 20 | | /// <param name="configuration">The application configuration.</param> |
| | | 21 | | /// <returns>The original service collection for chaining.</returns> |
| | | 22 | | public static IServiceCollection AddApplicationRequestLogging( |
| | | 23 | | this IServiceCollection services, |
| | | 24 | | IConfiguration configuration) |
| | | 25 | | { |
| | 158 | 26 | | services |
| | 158 | 27 | | .AddOptions<ApplicationRequestLoggingOptions>() |
| | 158 | 28 | | .Bind(configuration.GetSection(ApplicationRequestLoggingOptions.SectionName)) |
| | 158 | 29 | | .Validate( |
| | 280 | 30 | | options => !string.IsNullOrWhiteSpace(options.CorrelationHeaderName), |
| | 158 | 31 | | "ProjectTemplate:RequestLogging:CorrelationHeaderName is required.") |
| | 158 | 32 | | .Validate( |
| | 280 | 33 | | options => options.ExcludedPathPrefixes.All(path => |
| | 4140 | 34 | | !string.IsNullOrWhiteSpace(path) && |
| | 4140 | 35 | | path.StartsWith('/')), |
| | 158 | 36 | | "ProjectTemplate:RequestLogging:ExcludedPathPrefixes values must start with '/'.") |
| | 158 | 37 | | .ValidateOnStart(); |
| | | 38 | | |
| | 158 | 39 | | return services; |
| | | 40 | | } |
| | | 41 | | |
| | | 42 | | /// <summary> |
| | | 43 | | /// Configures structured request logging with correlation identifiers, |
| | | 44 | | /// request duration metrics, filtering, and safe diagnostic enrichment. |
| | | 45 | | /// </summary> |
| | | 46 | | /// <param name="app">The web application to configure.</param> |
| | | 47 | | /// <returns>The same web application instance for chaining.</returns> |
| | | 48 | | public static WebApplication UseApplicationRequestLogging(this WebApplication app) |
| | | 49 | | { |
| | 142 | 50 | | ApplicationRequestLoggingOptions requestLoggingOptions = app.Services |
| | 142 | 51 | | .GetRequiredService<IOptions<ApplicationRequestLoggingOptions>>() |
| | 142 | 52 | | .Value; |
| | | 53 | | |
| | 142 | 54 | | if (!requestLoggingOptions.Enabled) |
| | | 55 | | { |
| | 0 | 56 | | return app; |
| | | 57 | | } |
| | | 58 | | |
| | 142 | 59 | | app.Use(async (context, next) => |
| | 142 | 60 | | { |
| | 102 | 61 | | string correlationId = GetCorrelationId(context, requestLoggingOptions); |
| | 142 | 62 | | |
| | 102 | 63 | | context.Response.OnStarting(() => |
| | 102 | 64 | | { |
| | 102 | 65 | | if (!context.Response.Headers.ContainsKey(requestLoggingOptions.CorrelationHeaderName)) |
| | 102 | 66 | | { |
| | 102 | 67 | | context.Response.Headers[requestLoggingOptions.CorrelationHeaderName] = correlationId; |
| | 102 | 68 | | } |
| | 102 | 69 | | |
| | 102 | 70 | | return Task.CompletedTask; |
| | 102 | 71 | | }); |
| | 142 | 72 | | |
| | 102 | 73 | | Activity? activity = Activity.Current; |
| | 102 | 74 | | string? traceId = activity?.TraceId.ToString(); |
| | 102 | 75 | | string? spanId = activity?.SpanId.ToString(); |
| | 102 | 76 | | string? traceParent = activity?.Id; |
| | 142 | 77 | | |
| | 102 | 78 | | using (LogContext.PushProperty("CorrelationId", correlationId)) |
| | 102 | 79 | | using (LogContext.PushProperty("RequestId", context.TraceIdentifier)) |
| | 102 | 80 | | using (LogContext.PushProperty("TraceId", traceId)) |
| | 102 | 81 | | using (LogContext.PushProperty("SpanId", spanId)) |
| | 102 | 82 | | using (LogContext.PushProperty("TraceParent", traceParent)) |
| | 142 | 83 | | { |
| | 102 | 84 | | await next(context); |
| | 102 | 85 | | } |
| | 244 | 86 | | }); |
| | | 87 | | |
| | 142 | 88 | | app.UseSerilogRequestLogging(options => |
| | 142 | 89 | | { |
| | 142 | 90 | | options.MessageTemplate = |
| | 142 | 91 | | "HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms"; |
| | 142 | 92 | | |
| | 142 | 93 | | options.GetLevel = (httpContext, _, exception) => |
| | 142 | 94 | | { |
| | 102 | 95 | | if (IsExcludedPath(httpContext.Request.Path, requestLoggingOptions)) |
| | 142 | 96 | | { |
| | 20 | 97 | | return LogEventLevel.Verbose; |
| | 142 | 98 | | } |
| | 142 | 99 | | |
| | 82 | 100 | | if (exception is not null) |
| | 142 | 101 | | { |
| | 0 | 102 | | return LogEventLevel.Error; |
| | 142 | 103 | | } |
| | 142 | 104 | | |
| | 82 | 105 | | int statusCode = httpContext.Response.StatusCode; |
| | 142 | 106 | | |
| | 82 | 107 | | return statusCode >= StatusCodes.Status500InternalServerError |
| | 82 | 108 | | ? LogEventLevel.Error |
| | 82 | 109 | | : statusCode >= StatusCodes.Status400BadRequest |
| | 82 | 110 | | ? LogEventLevel.Warning |
| | 82 | 111 | | : LogEventLevel.Information; |
| | 142 | 112 | | }; |
| | 142 | 113 | | |
| | 142 | 114 | | // Do not enrich request logs with request bodies, response bodies, cookies, |
| | 142 | 115 | | // authorization headers, access tokens, refresh tokens, SAML/OIDC payloads, |
| | 142 | 116 | | // password fields, form fields, or query strings unless explicitly reviewed. |
| | 142 | 117 | | // Request logging should default to operational metadata only. |
| | 142 | 118 | | options.EnrichDiagnosticContext = (diagnosticContext, httpContext) => |
| | 142 | 119 | | { |
| | 82 | 120 | | Activity? activity = Activity.Current; |
| | 142 | 121 | | |
| | 82 | 122 | | diagnosticContext.Set("CorrelationId", GetCorrelationId(httpContext, requestLoggingOptions)); |
| | 82 | 123 | | diagnosticContext.Set("RequestId", httpContext.TraceIdentifier); |
| | 82 | 124 | | diagnosticContext.Set("TraceIdentifier", httpContext.TraceIdentifier); |
| | 82 | 125 | | diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value); |
| | 82 | 126 | | diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme); |
| | 82 | 127 | | diagnosticContext.Set("RequestPathBase", httpContext.Request.PathBase.Value); |
| | 82 | 128 | | diagnosticContext.Set("TraceId", activity?.TraceId.ToString()); |
| | 82 | 129 | | diagnosticContext.Set("SpanId", activity?.SpanId.ToString()); |
| | 82 | 130 | | diagnosticContext.Set("TraceParent", activity?.Id); |
| | 142 | 131 | | |
| | 82 | 132 | | if (requestLoggingOptions.IncludeQueryString) |
| | 142 | 133 | | { |
| | 0 | 134 | | diagnosticContext.Set("QueryString", httpContext.Request.QueryString.Value); |
| | 142 | 135 | | } |
| | 142 | 136 | | |
| | 82 | 137 | | if (requestLoggingOptions.IncludeRemoteIpAddress) |
| | 142 | 138 | | { |
| | 82 | 139 | | diagnosticContext.Set( |
| | 82 | 140 | | "RemoteIpAddress", |
| | 82 | 141 | | httpContext.Connection.RemoteIpAddress?.ToString()); |
| | 142 | 142 | | } |
| | 142 | 143 | | |
| | 82 | 144 | | if (requestLoggingOptions.IncludeUserName) |
| | 142 | 145 | | { |
| | 82 | 146 | | diagnosticContext.Set( |
| | 82 | 147 | | "UserName", |
| | 82 | 148 | | httpContext.User?.Identity?.IsAuthenticated == true |
| | 82 | 149 | | ? httpContext.User.Identity.Name |
| | 82 | 150 | | : null); |
| | 142 | 151 | | } |
| | 224 | 152 | | }; |
| | 284 | 153 | | }); |
| | | 154 | | |
| | 142 | 155 | | return app; |
| | | 156 | | } |
| | | 157 | | |
| | | 158 | | private static string GetCorrelationId( |
| | | 159 | | HttpContext httpContext, |
| | | 160 | | ApplicationRequestLoggingOptions options) |
| | | 161 | | { |
| | 194 | 162 | | if (httpContext.Request.Headers.TryGetValue(options.CorrelationHeaderName, out StringValues headerValues)) |
| | | 163 | | { |
| | 12 | 164 | | string? headerValue = headerValues.FirstOrDefault(); |
| | | 165 | | |
| | 12 | 166 | | if (!string.IsNullOrWhiteSpace(headerValue)) |
| | | 167 | | { |
| | 8 | 168 | | string cleanValue = headerValue.Trim(); |
| | | 169 | | |
| | 8 | 170 | | return cleanValue.Length <= 128 |
| | 8 | 171 | | ? cleanValue |
| | 8 | 172 | | : cleanValue[..128]; |
| | | 173 | | } |
| | | 174 | | } |
| | | 175 | | |
| | 186 | 176 | | return httpContext.TraceIdentifier; |
| | | 177 | | } |
| | | 178 | | |
| | | 179 | | private static bool IsExcludedPath( |
| | | 180 | | PathString requestPath, |
| | | 181 | | ApplicationRequestLoggingOptions options) |
| | | 182 | | { |
| | 110 | 183 | | return requestPath.HasValue && options.ExcludedPathPrefixes.Any(prefix => |
| | 1290 | 184 | | requestPath.StartsWithSegments( |
| | 1290 | 185 | | new PathString(prefix), |
| | 1290 | 186 | | StringComparison.OrdinalIgnoreCase)); |
| | | 187 | | } |
| | | 188 | | } |