Skip to content

Commit 10efe96

Browse files
authored
Merge pull request #731 from DuendeSoftware/filtering-exceptions
Document exception filtering in IdentityServer logging configuration
2 parents 81e4114 + 0f9f0dc commit 10efe96

File tree

1 file changed

+50
-0
lines changed
  • src/content/docs/identityserver/diagnostics

1 file changed

+50
-0
lines changed

src/content/docs/identityserver/diagnostics/logging.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,3 +110,53 @@ Then, in your `appsettings.json` file, you can set the default minimum log level
110110
}
111111
}
112112
```
113+
114+
## Filtering Exceptions
115+
116+
The `LoggingOptions` class allows developers to filter out any exceptions that
117+
could potentially lead to log bloat. For example, in a web application, developers
118+
should expect to see `OperationCanceledException` as clients end HTTP requests
119+
abruptly for many reasons. It's such a common occurrence to see this exception that
120+
the default filter included with IdentityServer excludes it by default.
121+
122+
```csharp
123+
/// <summary>
124+
/// Called when the IdentityServer middleware detects an unhandled exception, and is used to determine if the exception is logged.
125+
/// Returns true to emit the log, false to suppress.
126+
/// </summary>
127+
public Func<HttpContext, Exception, bool> UnhandledExceptionLoggingFilter = (context, exception) =>
128+
{
129+
var result = !(context.RequestAborted.IsCancellationRequested && exception is OperationCanceledException);
130+
return result;
131+
};
132+
```
133+
134+
To apply custom filtering, you can set the `UnhandledExceptionLoggingFilter` property on
135+
the `LoggingOptions` for your `IdentityServerOptions`.
136+
137+
```csharp
138+
var isBuilder = builder.Services.AddIdentityServer(options =>
139+
{
140+
options.Logging.UnhandledExceptionLoggingFilter =
141+
(ctx, ex) => {
142+
if (ctx.User is { Identity.Name: "Jeff" })
143+
{
144+
// Oh Jeff...
145+
return false;
146+
}
147+
148+
if (ex.Message.Contains("Oops"))
149+
{
150+
// ignore this exception
151+
return false;
152+
}
153+
154+
// this is a real exception
155+
return true;
156+
};
157+
})
158+
.AddTestUsers(TestUsers.Users)
159+
.AddLicenseSummary();
160+
```
161+
162+
Returning `true` means the exception will be logged, while returning `false` indicates the exception should not be logged.

0 commit comments

Comments
 (0)