LowCodeHub.Logging
0.0.12
See the version list below for details.
dotnet add package LowCodeHub.Logging --version 0.0.12
NuGet\Install-Package LowCodeHub.Logging -Version 0.0.12
<PackageReference Include="LowCodeHub.Logging" Version="0.0.12" />
<PackageVersion Include="LowCodeHub.Logging" Version="0.0.12" />
<PackageReference Include="LowCodeHub.Logging" />
paket add LowCodeHub.Logging --version 0.0.12
#r "nuget: LowCodeHub.Logging, 0.0.12"
#:package LowCodeHub.Logging@0.0.12
#addin nuget:?package=LowCodeHub.Logging&version=0.0.12
#tool nuget:?package=LowCodeHub.Logging&version=0.0.12
LowCodeHub.Logging
Opinionated Serilog setup for ASP.NET Core: one call configures structured console/file logging, HTTP request logging with PII-conscious enrichment, sensitive-data masking (properties, nested objects and exception text), forwarded headers and self-diagnostics — with safe defaults and fail-fast validation.
Installation
dotnet add package LowCodeHub.Logging
Quick Start
using LowCodeHub.Logging.Extensions;
var builder = WebApplication.CreateBuilder(args);
builder.AddEnhancedSerilogLogging(); // binds the "LoggingOptions" section (optional)
var app = builder.Build();
app.UseHttpContextEnricher(); // Serilog request logging + HTTP enrichment
app.MapGet("/", () => "ok");
app.Run();
With no configuration you get: compact-JSON console logging, ServiceName = the application name, one completion log per request (/health excluded), and masking of secrets/PII in properties, nested objects and exception text.
Adjust in code on top of configuration:
builder.AddEnhancedSerilogLogging(o =>
{
o.ServiceName = "orders-api";
o.SensitiveDataMasking.MaskProperties = ["nationalId"];
o.ConfigureSinks = writeTo => writeTo.Seq("http://seq:5341"); // extra sinks also get masked exceptions
});
Overloads (all accept optional exception destructurers as trailing params):
| Call | Behaviour |
|---|---|
AddEnhancedSerilogLogging(string section = "LoggingOptions") |
Bind from configuration |
AddEnhancedSerilogLogging(Action<LoggingOptions>) |
Bind "LoggingOptions", then apply the lambda |
AddEnhancedSerilogLogging(string section, Action<LoggingOptions>) |
Bind a custom section, then apply the lambda |
AddEnhancedSerilogLogging(LoggingOptions) |
Use an options instance as-is |
Options are validated when AddEnhancedSerilogLogging runs; invalid values (bad proxy IPs/CIDRs, depth out of range, file settings) throw InvalidOperationException at startup.
Configuration
Full example
{
"LoggingOptions": {
"ServiceName": "orders-api",
"MinimumLogLevel": "Information",
"LevelOverrides": { "Microsoft": "Warning", "System": "Warning" },
"ExcludedRequestPaths": ["/health"],
"WriteToFile": true,
"WriteToDebug": false,
"ConsoleLogging": { "Enabled": true, "UseCompactJson": true, "Theme": "literate" },
"FileLogging": {
"LogDirectory": "Logs",
"LogFileName": "app.log",
"RollingInterval": "Day",
"RetainedFileCountLimit": 14,
"SharedFile": true
},
"ExceptionHandling": { "MaxDestructuringDepth": 3 },
"RequestEnrichment": {
"IncludeQueryString": false,
"IncludeAuthenticatedUser": false,
"IncludeUserRoles": false,
"IncludeUserAgent": true,
"IncludeReferer": false,
"AllowedQueryKeys": ["page", "pageSize"]
},
"SensitiveDataMasking": {
"Enabled": true,
"MaskValue": "***MASKED***",
"MaskEmailAddresses": true,
"MaskIbanNumbers": true,
"MaskCreditCardNumbers": false,
"MaskSecretPatterns": true,
"MaskExceptions": true,
"IncludeDefaultMaskProperties": true,
"MaskProperties": ["nationalId"],
"ExcludeProperties": []
},
"ForwardedHeaders": {
"Enabled": false,
"ForwardLimit": 1,
"RequireHeaderSymmetry": true,
"KnownProxies": ["10.0.0.10"],
"KnownNetworks": ["10.244.0.0/16"]
},
"SelfLog": { "Enabled": true, "WriteToConsoleError": true, "FilePath": "Logs/serilog-selflog.txt" }
}
}
Logging options
| Option | Default | Description |
|---|---|---|
ServiceName |
application name | Added to every event as ServiceName |
MinimumLogLevel |
Information |
Minimum level |
LevelOverrides |
Microsoft, Microsoft.EntityFrameworkCore, System → Warning |
Per-namespace overrides. Configured values merge on top of the defaults; set a lower level to re-enable a namespace |
ExcludedRequestPaths |
null → ["/health"] |
Drops events whose RequestPath matches a prefix (segment-based: /health matches /health/ready, not /healthcare). A configured list replaces the default; [] in code excludes nothing |
WriteToFile |
false |
Enable the file sink |
WriteToDebug |
false |
Enable the Debug (IDE output) sink |
ConfigureSinks |
null |
Code-only: add sinks; they sit behind exception masking |
ConfigureLogger |
null |
Code-only: any other Serilog configuration, applied last |
Console logging
| Option | Default | Description |
|---|---|---|
Enabled |
true |
Enable the console sink |
UseCompactJson |
true |
Rendered compact JSON (recommended in containers) |
OutputTemplate |
timestamp/level/source template | Text template when compact JSON is off |
Theme |
"literate" |
code, literate, grayscale, sixteen, colored, none |
File logging
Files are written under the application content root.
| Option | Default | Description |
|---|---|---|
LogDirectory |
"Logs" |
Directory, relative to the content root |
LogFileName |
"log.txt" |
File name |
RollingInterval |
Day |
Infinite, Year, Month, Day, Hour, Minute |
RetainedFileCountLimit |
15 |
Rolled files to keep |
SharedFile |
true |
Allow multi-process access |
OutputTemplate |
timestamp/level/source template | Text template |
Request enrichment
| Option | Default | Description |
|---|---|---|
IncludeQueryString |
false |
Log query string (only AllowedQueryKeys; otherwise [redacted]) |
IncludeAuthenticatedUser |
false |
Log user id/name |
IncludeUserRoles |
false |
Log role claims (requires IncludeAuthenticatedUser) |
IncludeUserAgent |
true |
Log User-Agent |
IncludeReferer |
false |
Log Referer |
AllowedQueryKeys |
[] |
Query keys whose values may be logged |
Sensitive data masking
On by default, applied before any sink:
- Property names — a property whose name matches a keyword is replaced with
MaskValue, at any depth (destructured objects, dictionaries,ExceptionDetail). Matching is case-insensitive, ignores-/_/., and matches whole names, word runs (newPassword,X-Api-Key,refresh_token) and, for keywords of 4+ characters, prefixes/suffixes (passwordhash). Default keywords (SensitiveDataMaskingOptions.DefaultMaskProperties):password, passwd, pwd, passphrase, secret, token, apikey, authorization, cookie, connectionstring, privatekey, ssn, creditcard, cardnumber, cvv. - Values — emails and IBANs (credit cards if enabled) are masked in string values and message text. With
MaskSecretPatterns,key=value/"key": "value"pairs whose key contains password/pwd/secret/token/apikey/credential,Bearer/Basiccredentials and JWTs are masked as well. - Exceptions — with
MaskExceptions, the event's exception is replaced by aMaskedExceptionwhose message andToString()(type, inner exceptions, stack trace) have the value masking applied, so connection strings or tokens in exception messages never reach a sink.
| Option | Default | Description |
|---|---|---|
Enabled |
true |
Enable masking |
MaskValue |
"***MASKED***" |
Replacement text |
MaskEmailAddresses |
true |
Mask email addresses |
MaskIbanNumbers |
true |
Mask IBANs |
MaskCreditCardNumbers |
false |
Mask credit card numbers |
MaskSecretPatterns |
true |
Mask key=value secrets, Bearer/Basic credentials and JWTs in text |
MaskExceptions |
true |
Mask exception text before it reaches sinks |
IncludeDefaultMaskProperties |
true |
Include the default keywords; false = only MaskProperties |
MaskProperties |
[] |
Extra keywords, added to the defaults |
ExcludeProperties |
[] |
Property names (exact, case-insensitive) never masked |
CustomOperators |
[] |
Code-only: extra IMaskingOperators (e.g. a RegexMaskingOperator subclass) |
Masking is best-effort pattern matching — still avoid logging secrets in the first place.
Forwarded headers
Off by default. With Enabled: true, UseHttpContextEnricher() runs UseForwardedHeaders() (X-Forwarded-For/Proto) before request logging so ClientIp/Scheme reflect the real client. Enable it only behind a trusted proxy and list that proxy — ASP.NET Core trusts only loopback by default. While disabled, the library does not touch ForwardedHeadersOptions, so your own app.UseForwardedHeaders() setup is unaffected.
| Option | Default | Description |
|---|---|---|
Enabled |
false |
Run UseForwardedHeaders() from UseHttpContextEnricher() with these settings |
ForwardLimit |
1 |
Max hops (null = no limit) |
RequireHeaderSymmetry |
true |
X-Forwarded-For and X-Forwarded-Proto must have the same count |
KnownProxies |
[] |
Trusted proxy IPs |
KnownNetworks |
[] |
Trusted proxy networks (CIDR) |
Self-diagnostics
Serilog's SelfLog is process-global: the first host to configure it wins.
| Option | Default | Description |
|---|---|---|
Enabled |
false |
Enable SelfLog for sink/serialization failures |
WriteToConsoleError |
true |
Write to stderr |
FilePath |
null |
Optional file path |
Exception destructuring
Serilog.Exceptions' default destructurers are always registered. For third-party exception types, pass destructurers from the official satellite packages:
dotnet add package Serilog.Exceptions.Refit
dotnet add package Serilog.Exceptions.EntityFrameworkCore
dotnet add package Serilog.Exceptions.SqlServer
builder.AddEnhancedSerilogLogging(
"LoggingOptions",
new ApiExceptionDestructurer(),
new DbUpdateExceptionDestructurer(),
new SqlExceptionDestructurer());
HTTP request logging
app.UseHttpContextEnricher(); // register early in the pipeline
Wraps UseSerilogRequestLogging(): one event per request — Error for unhandled exceptions and 5xx, Information otherwise (client disconnects are Information). It uses the RequestEnrichment options bound by AddEnhancedSerilogLogging; pass an instance to override.
- Always: method, path, status code, protocol, host, scheme, trace identifier, client IP
- Opt-in: query string (allowlisted keys), authenticated user, roles, Referer; User-Agent is on by default
Notes
UseSerilog()assigns the staticLog.Logger; one host per process is assumed.- Correlation ids are read from the
CorrelationIdrequest header.
Requirements
- .NET 10
- Serilog.AspNetCore 10 (dependency)
License
MIT © Ahmed Abuelnour
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Serilog.AspNetCore (>= 10.0.0)
- Serilog.Enrichers.CorrelationId (>= 3.0.1)
- Serilog.Enrichers.Environment (>= 3.0.1)
- Serilog.Enrichers.Process (>= 3.0.0)
- Serilog.Enrichers.Sensitive (>= 2.1.0)
- Serilog.Exceptions (>= 8.4.0)
- Serilog.Formatting.Compact (>= 3.0.0)
- Serilog.Sinks.Async (>= 2.1.0)
- Serilog.Sinks.Console (>= 6.1.1)
- Serilog.Sinks.File (>= 7.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.