This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
Note
This isn't the latest version of this article. For the current release, see the.NET 10 version of this article.
Warning
This version of ASP.NET Core is no longer supported. For more information, see the.NET and .NET Core Support Policy. For the current release, see the.NET 9 version of this article.
HTTP logging is a middleware that logs information about incoming HTTP requests and HTTP responses. HTTP logging provides logs of:
HTTP logging can:
HTTP loggingcan reduce the performance of an app, especially when logging the request and response bodies. Consider the performance impact when selecting fields to log. Test the performance impact of the selected logging properties.
Warning
HTTP logging can potentially log personally identifiable information (PII). Consider the risk and avoid logging sensitive information.For more information about redaction, checkredacting sensitive data
HTTP logging is enabled by callingAddHttpLogging andUseHttpLogging, as shown in the following example:
var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(o => { });var app = builder.Build();app.UseHttpLogging();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.MapGet("/", () => "Hello World!");app.Run();The empty lambda in the preceding example of callingAddHttpLogging adds the middleware with the default configuration. By default, HTTP logging logs common properties such as path, status-code, and headers for requests and responses.
Add the following line to theappsettings.Development.json file at the"LogLevel": { level so the HTTP logs are displayed:
"Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware": "Information"With the default configuration, a request and response is logged as a pair of messages similar to the following example:
info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[1] Request: Protocol: HTTP/2 Method: GET Scheme: https PathBase: Path: / Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7 Host: localhost:52941 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 Edg/118.0.2088.61 Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Upgrade-Insecure-Requests: [Redacted] sec-ch-ua: [Redacted] sec-ch-ua-mobile: [Redacted] sec-ch-ua-platform: [Redacted] sec-fetch-site: [Redacted] sec-fetch-mode: [Redacted] sec-fetch-user: [Redacted] sec-fetch-dest: [Redacted]info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[2] Response: StatusCode: 200 Content-Type: text/plain; charset=utf-8 Date: Tue, 24 Oct 2023 02:03:53 GMT Server: KestrelTo configure global options for the HTTP logging middleware, callAddHttpLogging inProgram.cs, using the lambda to configureHttpLoggingOptions.
using Microsoft.AspNetCore.HttpLogging;var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(logging =>{ logging.LoggingFields = HttpLoggingFields.All; logging.RequestHeaders.Add("sec-ch-ua"); logging.ResponseHeaders.Add("MyResponseHeader"); logging.MediaTypeOptions.AddText("application/javascript"); logging.RequestBodyLogLimit = 4096; logging.ResponseBodyLogLimit = 4096; logging.CombineLogs = true;});var app = builder.Build();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.UseHttpLogging();app.Use(async (context, next) =>{ context.Response.Headers["MyResponseHeader"] = new string[] { "My Response Header Value" }; await next();});app.MapGet("/", () => "Hello World!");app.Run();Note
In the preceding sample and following samples,UseHttpLogging is called afterUseStaticFiles, so HTTP logging isn't enabled for static files. To enable static file HTTP logging, callUseHttpLogging beforeUseStaticFiles.
LoggingFieldsHttpLoggingOptions.LoggingFields is an enum flag that configures specific parts of the request and response to log.LoggingFields defaults toRequestPropertiesAndHeaders |ResponsePropertiesAndHeaders.
RequestHeaders andResponseHeadersRequestHeaders andResponseHeaders are sets of HTTP headers that are logged. Header values are only logged for header names that are in these collections. The following code addssec-ch-ua to theRequestHeaders, so the value of thesec-ch-ua header is logged. And it addsMyResponseHeader to theResponseHeaders, so the value of theMyResponseHeader header is logged. If these lines are removed, the values of these headers are[Redacted].
using Microsoft.AspNetCore.HttpLogging;var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(logging =>{ logging.LoggingFields = HttpLoggingFields.All; logging.RequestHeaders.Add("sec-ch-ua"); logging.ResponseHeaders.Add("MyResponseHeader"); logging.MediaTypeOptions.AddText("application/javascript"); logging.RequestBodyLogLimit = 4096; logging.ResponseBodyLogLimit = 4096; logging.CombineLogs = true;});var app = builder.Build();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.UseHttpLogging();app.Use(async (context, next) =>{ context.Response.Headers["MyResponseHeader"] = new string[] { "My Response Header Value" }; await next();});app.MapGet("/", () => "Hello World!");app.Run();MediaTypeOptionsMediaTypeOptions provides configuration for selecting which encoding to use for a specific media type.
using Microsoft.AspNetCore.HttpLogging;var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(logging =>{ logging.LoggingFields = HttpLoggingFields.All; logging.RequestHeaders.Add("sec-ch-ua"); logging.ResponseHeaders.Add("MyResponseHeader"); logging.MediaTypeOptions.AddText("application/javascript"); logging.RequestBodyLogLimit = 4096; logging.ResponseBodyLogLimit = 4096; logging.CombineLogs = true;});var app = builder.Build();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.UseHttpLogging();app.Use(async (context, next) =>{ context.Response.Headers["MyResponseHeader"] = new string[] { "My Response Header Value" }; await next();});app.MapGet("/", () => "Hello World!");app.Run();This approach can also be used to enable logging for data that isn't logged by default (for example, form data, which might have a media type such asapplication/x-www-form-urlencoded ormultipart/form-data).
MediaTypeOptions methodsRequestBodyLogLimit andResponseBodyLogLimitusing Microsoft.AspNetCore.HttpLogging;var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(logging =>{ logging.LoggingFields = HttpLoggingFields.All; logging.RequestHeaders.Add("sec-ch-ua"); logging.ResponseHeaders.Add("MyResponseHeader"); logging.MediaTypeOptions.AddText("application/javascript"); logging.RequestBodyLogLimit = 4096; logging.ResponseBodyLogLimit = 4096; logging.CombineLogs = true;});var app = builder.Build();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.UseHttpLogging();app.Use(async (context, next) =>{ context.Response.Headers["MyResponseHeader"] = new string[] { "My Response Header Value" }; await next();});app.MapGet("/", () => "Hello World!");app.Run();CombineLogsSettingCombineLogs totrue configures the middleware to consolidate all of its enabled logs for a request and response into one log at the end. This includes the request, request body, response, response body, and duration.
using Microsoft.AspNetCore.HttpLogging;var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(logging =>{ logging.LoggingFields = HttpLoggingFields.All; logging.RequestHeaders.Add("sec-ch-ua"); logging.ResponseHeaders.Add("MyResponseHeader"); logging.MediaTypeOptions.AddText("application/javascript"); logging.RequestBodyLogLimit = 4096; logging.ResponseBodyLogLimit = 4096; logging.CombineLogs = true;});var app = builder.Build();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.UseHttpLogging();app.Use(async (context, next) =>{ context.Response.Headers["MyResponseHeader"] = new string[] { "My Response Header Value" }; await next();});app.MapGet("/", () => "Hello World!");app.Run();For endpoint-specific configuration in minimal API apps, aWithHttpLogging extension method is available. The following example shows how to configure HTTP logging for one endpoint:
app.MapGet("/response", () => "Hello World! (logging response)") .WithHttpLogging(HttpLoggingFields.ResponsePropertiesAndHeaders);For endpoint-specific configuration in apps that use controllers, the[HttpLogging] attribute is available. The attribute can also be used in minimal API apps, as shown in the following example:
app.MapGet("/duration", [HttpLogging(loggingFields: HttpLoggingFields.Duration)] () => "Hello World! (logging duration)");IHttpLoggingInterceptorIHttpLoggingInterceptor is the interface for a service that can be implemented to handle per-request and per-response callbacks for customizing what details get logged. Any endpoint-specific log settings are applied first and can then be overridden in these callbacks. An implementation can:
Register anIHttpLoggingInterceptor implementation by callingAddHttpLoggingInterceptor inProgram.cs. If multipleIHttpLoggingInterceptor instances are registered, they're run in the order registered.
The following example shows how to register anIHttpLoggingInterceptor implementation:
var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(logging =>{ logging.LoggingFields = HttpLoggingFields.Duration;});builder.Services.AddHttpLoggingInterceptor<SampleHttpLoggingInterceptor>();The following example is anIHttpLoggingInterceptor implementation that:
using Microsoft.AspNetCore.HttpLogging;namespace HttpLoggingSample;internal sealed class SampleHttpLoggingInterceptor : IHttpLoggingInterceptor{ public ValueTask OnRequestAsync(HttpLoggingInterceptorContext logContext) { if (logContext.HttpContext.Request.Method == "POST") { // Don't log anything if the request is a POST. logContext.LoggingFields = HttpLoggingFields.None; } // Don't enrich if we're not going to log any part of the request. if (!logContext.IsAnyEnabled(HttpLoggingFields.Request)) { return default; } if (logContext.TryDisable(HttpLoggingFields.RequestPath)) { RedactPath(logContext); } if (logContext.TryDisable(HttpLoggingFields.RequestHeaders)) { RedactRequestHeaders(logContext); } EnrichRequest(logContext); return default; } public ValueTask OnResponseAsync(HttpLoggingInterceptorContext logContext) { // Don't enrich if we're not going to log any part of the response if (!logContext.IsAnyEnabled(HttpLoggingFields.Response)) { return default; } if (logContext.TryDisable(HttpLoggingFields.ResponseHeaders)) { RedactResponseHeaders(logContext); } EnrichResponse(logContext); return default; } private void RedactPath(HttpLoggingInterceptorContext logContext) { logContext.AddParameter(nameof(logContext.HttpContext.Request.Path), "RedactedPath"); } private void RedactRequestHeaders(HttpLoggingInterceptorContext logContext) { foreach (var header in logContext.HttpContext.Request.Headers) { logContext.AddParameter(header.Key, "RedactedHeader"); } } private void EnrichRequest(HttpLoggingInterceptorContext logContext) { logContext.AddParameter("RequestEnrichment", "Stuff"); } private void RedactResponseHeaders(HttpLoggingInterceptorContext logContext) { foreach (var header in logContext.HttpContext.Response.Headers) { logContext.AddParameter(header.Key, "RedactedHeader"); } } private void EnrichResponse(HttpLoggingInterceptorContext logContext) { logContext.AddParameter("ResponseEnrichment", "Stuff"); }}With this interceptor, a POST request doesn't generate any logs even if HTTP logging is configured to logHttpLoggingFields.All. A GET request generates logs similar to the following example:
info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[1] Request: Path: RedactedPath Accept: RedactedHeader Host: RedactedHeader User-Agent: RedactedHeader Accept-Encoding: RedactedHeader Accept-Language: RedactedHeader Upgrade-Insecure-Requests: RedactedHeader sec-ch-ua: RedactedHeader sec-ch-ua-mobile: RedactedHeader sec-ch-ua-platform: RedactedHeader sec-fetch-site: RedactedHeader sec-fetch-mode: RedactedHeader sec-fetch-user: RedactedHeader sec-fetch-dest: RedactedHeader RequestEnrichment: Stuff Protocol: HTTP/2 Method: GET Scheme: httpsinfo: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[2] Response: Content-Type: RedactedHeader MyResponseHeader: RedactedHeader ResponseEnrichment: Stuff StatusCode: 200info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[4] ResponseBody: Hello World!info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[8] Duration: 2.2778msThe following list shows the order of precedence for logging configuration:
[HttpLogging] attribute or theWithHttpLogging extension method overrides global configuration.IHttpLoggingInterceptor is called with the results and can further modify the configuration per request.HTTP Logging is a middleware that logs information about incoming HTTP requests and HTTP responses. HTTP logging provides logs of:
HTTP Logging is valuable in several scenarios to:
HTTP Loggingcan reduce the performance of an app, especially when logging the request and response bodies. Consider the performance impact when selecting fields to log. Test the performance impact of the selected logging properties.
Warning
HTTP Logging can potentially log personally identifiable information (PII). Consider the risk and avoid logging sensitive information.
HTTP Logging is enabled withUseHttpLogging, which adds HTTP logging middleware.
var builder = WebApplication.CreateBuilder(args);var app = builder.Build();app.UseHttpLogging();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.MapGet("/", () => "Hello World!");app.Run();By default, HTTP Logging logs common properties such as path, status-code, and headers for requests and responses. Add the following line to theappsettings.Development.json file at the"LogLevel": { level so the HTTP logs are displayed:
"Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware": "Information"The output is logged as a single message atLogLevel.Information.

To configure the HTTP logging middleware, callAddHttpLogging inProgram.cs.
using Microsoft.AspNetCore.HttpLogging;var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(logging =>{ logging.LoggingFields = HttpLoggingFields.All; logging.RequestHeaders.Add("sec-ch-ua"); logging.ResponseHeaders.Add("MyResponseHeader"); logging.MediaTypeOptions.AddText("application/javascript"); logging.RequestBodyLogLimit = 4096; logging.ResponseBodyLogLimit = 4096;});var app = builder.Build();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.UseHttpLogging(); app.Use(async (context, next) =>{ context.Response.Headers["MyResponseHeader"] = new string[] { "My Response Header Value" }; await next();});app.MapGet("/", () => "Hello World!");app.Run();Note
In the preceding sample and following samples,UseHttpLogging is called afterUseStaticFiles, so HTTP logging is not enabled for static file. To enable static file HTTP logging, callUseHttpLogging beforeUseStaticFiles.
LoggingFieldsHttpLoggingOptions.LoggingFields is an enum flag that configures specific parts of the request and response to log.HttpLoggingOptions.LoggingFields defaults toRequestPropertiesAndHeaders |ResponsePropertiesAndHeaders.
RequestHeadersHeaders are a set of HTTP Request Headers that are allowed to be logged. Header values are only logged for header names that are in this collection. The following code logs the request header"sec-ch-ua". Iflogging.RequestHeaders.Add("sec-ch-ua"); is removed, the value of the request header"sec-ch-ua" is redacted. The following highlighted code callsHttpLoggingOptions.RequestHeaders andHttpLoggingOptions.ResponseHeaders :
using Microsoft.AspNetCore.HttpLogging;var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(logging =>{ logging.LoggingFields = HttpLoggingFields.All; logging.RequestHeaders.Add("sec-ch-ua"); logging.ResponseHeaders.Add("MyResponseHeader"); logging.MediaTypeOptions.AddText("application/javascript"); logging.RequestBodyLogLimit = 4096; logging.ResponseBodyLogLimit = 4096;});var app = builder.Build();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.UseHttpLogging(); app.Use(async (context, next) =>{ context.Response.Headers["MyResponseHeader"] = new string[] { "My Response Header Value" }; await next();});app.MapGet("/", () => "Hello World!");app.Run();MediaTypeOptionsMediaTypeOptions provides configuration for selecting which encoding to use for a specific media type.
using Microsoft.AspNetCore.HttpLogging;var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(logging =>{ logging.LoggingFields = HttpLoggingFields.All; logging.RequestHeaders.Add("sec-ch-ua"); logging.ResponseHeaders.Add("MyResponseHeader"); logging.MediaTypeOptions.AddText("application/javascript"); logging.RequestBodyLogLimit = 4096; logging.ResponseBodyLogLimit = 4096;});var app = builder.Build();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.UseHttpLogging(); app.Use(async (context, next) =>{ context.Response.Headers["MyResponseHeader"] = new string[] { "My Response Header Value" }; await next();});app.MapGet("/", () => "Hello World!");app.Run();This approach can also be used to enable logging for data that is not logged by default. For example, form data, which might have a media type such asapplication/x-www-form-urlencoded ormultipart/form-data.
MediaTypeOptions methodsRequestBodyLogLimit andResponseBodyLogLimitusing Microsoft.AspNetCore.HttpLogging;var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(logging =>{ logging.LoggingFields = HttpLoggingFields.All; logging.RequestHeaders.Add("sec-ch-ua"); logging.ResponseHeaders.Add("MyResponseHeader"); logging.MediaTypeOptions.AddText("application/javascript"); logging.RequestBodyLogLimit = 4096; logging.ResponseBodyLogLimit = 4096;});var app = builder.Build();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.UseHttpLogging(); app.Use(async (context, next) =>{ context.Response.Headers["MyResponseHeader"] = new string[] { "My Response Header Value" }; await next();});app.MapGet("/", () => "Hello World!");app.Run();Http logging with redaction can be enabled by callingAddHttpLoggingRedaction:
var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(logging =>{ logging.LoggingFields = HttpLoggingFields.Duration;});builder.Services.AddRedaction();builder.Services.AddHttpLoggingRedaction(op => { });For more information about .NET's data redaction library, seeData redaction in .NET.
To configure options for logging with redaction, callAddHttpLoggingRedaction inProgram.cs using the lambda to configureLoggingRedactionOptions:
using Microsoft.Extensions.Compliance.Classification;namespace HttpLoggingSample{ public static class MyTaxonomyClassifications { public static string Name => "MyTaxonomy"; public static DataClassification Private => new(Name, nameof(Private)); public static DataClassification Public => new(Name, nameof(Public)); public static DataClassification Personal => new(Name, nameof(Personal)); }}var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(o => { });builder.Services.AddRedaction();builder.Services.AddHttpLoggingRedaction(op =>{ op.RequestPathParameterRedactionMode = HttpRouteParameterRedactionMode.None; op.RequestPathLoggingMode = IncomingPathLoggingMode.Formatted; op.RequestHeadersDataClasses.Add(HeaderNames.Accept, MyTaxonomyClassifications.Public); op.ResponseHeadersDataClasses.Add(HeaderNames.ContentType, MyTaxonomyClassifications.Private); op.RouteParameterDataClasses = new Dictionary<string, DataClassification> { { "one", MyTaxonomyClassifications.Personal }, }; // Add the paths that should be filtered, with a leading '/'. op.ExcludePathStartsWith.Add("/home"); op.IncludeUnmatchedRoutes = true;});var app = builder.Build();app.UseHttpLogging();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.MapGet("/", () => "Logged!");app.MapGet("/home", () => "Not logged!");app.Run();With the previous redaction configuration, the output is similar to the following:
info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[9] Request and Response: server.address: localhost:61361 Path: / http.request.header.accept: Protocol: HTTP/2 Method: GET Scheme: https http.response.header.content-type: StatusCode: 200 Duration: 8.4684info: Microsoft.AspNetCore.Hosting.Diagnostics[2] Request finished HTTP/2 GET https://localhost:61361/ - 200 - text/plain;+charset=utf-8 105.5334msNote
Request path/home isn't logged because it's included in theExcludePathStartsWith property.http.request.header.accept andhttp.response.header.content-type were redacted byMicrosoft.Extensions.Compliance.Redaction.ErasingRedactor.
RequestPathLoggingModeRequestPathLoggingMode determines how the request path is logged, whetherFormatted orStructured, set byIncomingPathLoggingMode:
Formatted: Logs the request path without parameters.Structured: Logs the request path with parameters included.var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(o => { });builder.Services.AddRedaction();builder.Services.AddHttpLoggingRedaction(op =>{ op.RequestPathParameterRedactionMode = HttpRouteParameterRedactionMode.None; op.RequestPathLoggingMode = IncomingPathLoggingMode.Formatted; op.RequestHeadersDataClasses.Add(HeaderNames.Accept, MyTaxonomyClassifications.Public); op.ResponseHeadersDataClasses.Add(HeaderNames.ContentType, MyTaxonomyClassifications.Private); op.RouteParameterDataClasses = new Dictionary<string, DataClassification> { { "one", MyTaxonomyClassifications.Personal }, }; // Add the paths that should be filtered, with a leading '/'. op.ExcludePathStartsWith.Add("/home"); op.IncludeUnmatchedRoutes = true;});var app = builder.Build();app.UseHttpLogging();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.MapGet("/", () => "Logged!");app.MapGet("/home", () => "Not logged!");app.Run();RequestPathParameterRedactionModeRequestPathParameterRedactionModespecifies how route parameters in the request path should be redacted, whetherStrict,Loose, orNone, set byHttpRouteParameterRedactionMode:
Strict: Request route parameters are considered sensitive, require explicit annotation with a data classification, and are redacted by default.Loose: All parameters are considered as non-sensitive and included as-is by default.None: Route parameters aren't redacted regardless of the presence of data classification annotations.var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(o => { });builder.Services.AddRedaction();builder.Services.AddHttpLoggingRedaction(op =>{ op.RequestPathParameterRedactionMode = HttpRouteParameterRedactionMode.None; op.RequestPathLoggingMode = IncomingPathLoggingMode.Formatted; op.RequestHeadersDataClasses.Add(HeaderNames.Accept, MyTaxonomyClassifications.Public); op.ResponseHeadersDataClasses.Add(HeaderNames.ContentType, MyTaxonomyClassifications.Private); op.RouteParameterDataClasses = new Dictionary<string, DataClassification> { { "one", MyTaxonomyClassifications.Personal }, }; // Add the paths that should be filtered, with a leading '/'. op.ExcludePathStartsWith.Add("/home"); op.IncludeUnmatchedRoutes = true;});var app = builder.Build();app.UseHttpLogging();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.MapGet("/", () => "Logged!");app.MapGet("/home", () => "Not logged!");app.Run();RequestHeadersDataClassesRequestHeadersDataClasses maps request headers to their data classification, which determines how they are redacted:
var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(o => { });builder.Services.AddRedaction();builder.Services.AddHttpLoggingRedaction(op =>{ op.RequestPathParameterRedactionMode = HttpRouteParameterRedactionMode.None; op.RequestPathLoggingMode = IncomingPathLoggingMode.Formatted; op.RequestHeadersDataClasses.Add(HeaderNames.Accept, MyTaxonomyClassifications.Public); op.ResponseHeadersDataClasses.Add(HeaderNames.ContentType, MyTaxonomyClassifications.Private); op.RouteParameterDataClasses = new Dictionary<string, DataClassification> { { "one", MyTaxonomyClassifications.Personal }, }; // Add the paths that should be filtered, with a leading '/'. op.ExcludePathStartsWith.Add("/home"); op.IncludeUnmatchedRoutes = true;});var app = builder.Build();app.UseHttpLogging();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.MapGet("/", () => "Logged!");app.MapGet("/home", () => "Not logged!");app.Run();ResponseHeadersDataClassesResponseHeadersDataClasses, similar toRequestHeadersDataClasses`, but for response headers:
var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(o => { });builder.Services.AddRedaction();builder.Services.AddHttpLoggingRedaction(op =>{ op.RequestPathParameterRedactionMode = HttpRouteParameterRedactionMode.None; op.RequestPathLoggingMode = IncomingPathLoggingMode.Formatted; op.RequestHeadersDataClasses.Add(HeaderNames.Accept, MyTaxonomyClassifications.Public); op.ResponseHeadersDataClasses.Add(HeaderNames.ContentType, MyTaxonomyClassifications.Private); op.RouteParameterDataClasses = new Dictionary<string, DataClassification> { { "one", MyTaxonomyClassifications.Personal }, }; // Add the paths that should be filtered, with a leading '/'. op.ExcludePathStartsWith.Add("/home"); op.IncludeUnmatchedRoutes = true;});var app = builder.Build();app.UseHttpLogging();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.MapGet("/", () => "Logged!");app.MapGet("/home", () => "Not logged!");app.Run();RouteParameterDataClassesRouteParameterDataClasses maps route parameters to their data classification:
var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(o => { });builder.Services.AddRedaction();builder.Services.AddHttpLoggingRedaction(op =>{ op.RequestPathParameterRedactionMode = HttpRouteParameterRedactionMode.None; op.RequestPathLoggingMode = IncomingPathLoggingMode.Formatted; op.RequestHeadersDataClasses.Add(HeaderNames.Accept, MyTaxonomyClassifications.Public); op.ResponseHeadersDataClasses.Add(HeaderNames.ContentType, MyTaxonomyClassifications.Private); op.RouteParameterDataClasses = new Dictionary<string, DataClassification> { { "one", MyTaxonomyClassifications.Personal }, }; // Add the paths that should be filtered, with a leading '/'. op.ExcludePathStartsWith.Add("/home"); op.IncludeUnmatchedRoutes = true;});var app = builder.Build();app.UseHttpLogging();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.MapGet("/", () => "Logged!");app.MapGet("/home", () => "Not logged!");app.Run();ExcludePathStartsWithExcludePathStartsWith specifies paths that should be excluded from logging entirely:
var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(o => { });builder.Services.AddRedaction();builder.Services.AddHttpLoggingRedaction(op =>{ op.RequestPathParameterRedactionMode = HttpRouteParameterRedactionMode.None; op.RequestPathLoggingMode = IncomingPathLoggingMode.Formatted; op.RequestHeadersDataClasses.Add(HeaderNames.Accept, MyTaxonomyClassifications.Public); op.ResponseHeadersDataClasses.Add(HeaderNames.ContentType, MyTaxonomyClassifications.Private); op.RouteParameterDataClasses = new Dictionary<string, DataClassification> { { "one", MyTaxonomyClassifications.Personal }, }; // Add the paths that should be filtered, with a leading '/'. op.ExcludePathStartsWith.Add("/home"); op.IncludeUnmatchedRoutes = true;});var app = builder.Build();app.UseHttpLogging();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.MapGet("/", () => "Logged!");app.MapGet("/home", () => "Not logged!");app.Run();IncludeUnmatchedRoutesIncludeUnmatchedRoutes allows reporting unmatched routes. If set totrue, logs whole path of routes not identified byRouting instead of loggingUnknown value for path attribute:
var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(o => { });builder.Services.AddRedaction();builder.Services.AddHttpLoggingRedaction(op =>{ op.RequestPathParameterRedactionMode = HttpRouteParameterRedactionMode.None; op.RequestPathLoggingMode = IncomingPathLoggingMode.Formatted; op.RequestHeadersDataClasses.Add(HeaderNames.Accept, MyTaxonomyClassifications.Public); op.ResponseHeadersDataClasses.Add(HeaderNames.ContentType, MyTaxonomyClassifications.Private); op.RouteParameterDataClasses = new Dictionary<string, DataClassification> { { "one", MyTaxonomyClassifications.Personal }, }; // Add the paths that should be filtered, with a leading '/'. op.ExcludePathStartsWith.Add("/home"); op.IncludeUnmatchedRoutes = true;});var app = builder.Build();app.UseHttpLogging();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.MapGet("/", () => "Logged!");app.MapGet("/home", () => "Not logged!");app.Run();Was this page helpful?
Need help with this topic?
Want to try using Ask Learn to clarify or guide you through this topic?
Was this page helpful?
Want to try using Ask Learn to clarify or guide you through this topic?