| | | 1 | | using Microsoft.Extensions.Options; |
| | | 2 | | using ProjectTemplate.Web.Options; |
| | | 3 | | |
| | | 4 | | namespace ProjectTemplate.Web.Diagnostics; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Applies the request-logging privacy options to diagnostic log entries written outside the request-logging |
| | | 8 | | /// middleware, such as rate-limit rejection and error-page log entries. |
| | | 9 | | /// </summary> |
| | | 10 | | /// <remarks> |
| | | 11 | | /// <see cref="ApplicationRequestLoggingOptions.IncludeRemoteIpAddress"/> is the single application-wide decision about |
| | | 12 | | /// whether client IP addresses are written to logs. Every log entry that would otherwise record the remote IP address |
| | | 13 | | /// should obtain it through this class so the decision is honored consistently. |
| | | 14 | | /// </remarks> |
| | | 15 | | internal static class RequestLoggingPrivacy |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Gets the remote IP address to write to a log entry, or <see langword="null"/> when remote IP address logging is |
| | | 19 | | /// not enabled. |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="httpContext">The current HTTP context.</param> |
| | | 22 | | /// <returns> |
| | | 23 | | /// The remote IP address when <see cref="ApplicationRequestLoggingOptions.IncludeRemoteIpAddress"/> is |
| | | 24 | | /// <see langword="true"/> and an address is available; otherwise <see langword="null"/>. When the options are not |
| | | 25 | | /// registered, the privacy-preserving default applies and <see langword="null"/> is returned. |
| | | 26 | | /// </returns> |
| | | 27 | | internal static string? GetLoggableRemoteIpAddress(HttpContext httpContext) |
| | | 28 | | { |
| | 34 | 29 | | ArgumentNullException.ThrowIfNull(httpContext); |
| | | 30 | | |
| | 34 | 31 | | ApplicationRequestLoggingOptions? options = httpContext.RequestServices? |
| | 34 | 32 | | .GetService<IOptions<ApplicationRequestLoggingOptions>>()? |
| | 34 | 33 | | .Value; |
| | | 34 | | |
| | 34 | 35 | | return options?.IncludeRemoteIpAddress == true |
| | 34 | 36 | | ? httpContext.Connection.RemoteIpAddress?.ToString() |
| | 34 | 37 | | : null; |
| | | 38 | | } |
| | | 39 | | } |