Skip to content

Commit d4c38a5

Browse files
committed
Fixed the way an HTTP request is consider for logging.
1 parent e241e4c commit d4c38a5

File tree

1 file changed

+7
-7
lines changed

1 file changed

+7
-7
lines changed

Sources/TodoWebApp/Logging/LoggingService.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
using System.Linq;
55
using System.Net;
66
using System.Text;
7-
using System.Text.RegularExpressions;
87

98
namespace TodoWebApp.Logging
109
{
@@ -17,8 +16,8 @@ public class LoggingService : IHttpContextLoggingHandler, IHttpObjectConverter
1716
private const int RESPONSE_SIZE = 1000;
1817

1918
private static readonly string[] textBasedHeaderNames = { "Accept", "Content-Type" };
20-
private static readonly string[] textBasedFragments = { "application/json", "application/xml", "text/" };
21-
private static readonly Regex textBasedRegex = new Regex("/api/", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
19+
private static readonly string[] textBasedHeaderValues = { "application/json", "application/xml", "text/" };
20+
private const string ACCEPTABLE_REQUEST_URL_PREFIX = "/api/";
2221
private readonly ILogger logger;
2322

2423
/// <summary>
@@ -43,10 +42,11 @@ public bool ShouldLog(HttpContext httpContext)
4342
}
4443

4544
var result = IsTextBased(httpContext.Request);
45+
var willBeLoggedOutcome = result ? string.Empty : " NOT";
4646

4747
if (logger.IsEnabled(LogLevel.Debug))
4848
{
49-
logger.LogDebug($"HTTP context {httpContext.TraceIdentifier} will be logged: {result.ToString().ToLowerInvariant()}");
49+
logger.LogDebug($"HTTP context {httpContext.TraceIdentifier} will{willBeLoggedOutcome} be logged");
5050
}
5151

5252
return result;
@@ -119,13 +119,13 @@ public string ToLogMessage(HttpResponse httpResponse)
119119
private static bool IsTextBased(HttpRequest httpRequest)
120120
{
121121
return textBasedHeaderNames.Any(headerName => IsTextBased(httpRequest, headerName))
122-
|| textBasedRegex.IsMatch(httpRequest.Path);
122+
|| httpRequest.Path.ToUriComponent().StartsWith(ACCEPTABLE_REQUEST_URL_PREFIX);
123123
}
124124

125125
private static bool IsTextBased(HttpRequest httpRequest, string headerName)
126126
{
127-
return httpRequest.Headers.TryGetValue(headerName, out var headerValue)
128-
&& textBasedFragments.Any(fragment => headerValue.Contains(fragment));
127+
return httpRequest.Headers.TryGetValue(headerName, out var headerValues)
128+
&& textBasedHeaderValues.Any(textBasedHeaderValue => headerValues.Any(headerValue => headerValue.StartsWith(textBasedHeaderValue)));
129129
}
130130
}
131131
}

0 commit comments

Comments
 (0)