LowCodeHub.Logging 0.0.12

There is a newer version of this package available.
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
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="LowCodeHub.Logging" Version="0.0.12" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="LowCodeHub.Logging" Version="0.0.12" />
                    
Directory.Packages.props
<PackageReference Include="LowCodeHub.Logging" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add LowCodeHub.Logging --version 0.0.12
                    
#r "nuget: LowCodeHub.Logging, 0.0.12"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package LowCodeHub.Logging@0.0.12
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=LowCodeHub.Logging&version=0.0.12
                    
Install as a Cake Addin
#tool nuget:?package=LowCodeHub.Logging&version=0.0.12
                    
Install as a Cake Tool

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.

NuGet License: MIT

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/Basic credentials and JWTs are masked as well.
  • Exceptions — with MaskExceptions, the event's exception is replaced by a MaskedException whose message and ToString() (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 static Log.Logger; one host per process is assumed.
  • Correlation ids are read from the CorrelationId request header.

Requirements

  • .NET 10
  • Serilog.AspNetCore 10 (dependency)

License

MIT © Ahmed Abuelnour

Product 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.0 103 11/15/2026
0.0.12 118 10/22/2026
0.0.11 277 7/9/2026
0.0.10 174 6/21/2026
0.0.4 193 5/18/2026
0.0.3 142 5/12/2026
0.0.2 167 4/23/2026
0.0.1 176 3/26/2026