Sprint.Shared.Logs 2.4.0

dotnet add package Sprint.Shared.Logs --version 2.4.0
                    
NuGet\Install-Package Sprint.Shared.Logs -Version 2.4.0
                    
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="Sprint.Shared.Logs" Version="2.4.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Sprint.Shared.Logs" Version="2.4.0" />
                    
Directory.Packages.props
<PackageReference Include="Sprint.Shared.Logs" />
                    
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 Sprint.Shared.Logs --version 2.4.0
                    
#r "nuget: Sprint.Shared.Logs, 2.4.0"
                    
#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 Sprint.Shared.Logs@2.4.0
                    
#: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=Sprint.Shared.Logs&version=2.4.0
                    
Install as a Cake Addin
#tool nuget:?package=Sprint.Shared.Logs&version=2.4.0
                    
Install as a Cake Tool

Shared.Logs

High-performance structured logging library designed for the Sprint ecosystem (.NET 10+). Provides two independent logging pipelines — Application Event Logging (via Serilog Sink) and HTTP Request/Response Logging (via Middleware) — both using asynchronous batch writes to MySQL or PostgreSQL.


Key Features

  • Non-blocking Architecture: All log entries are queued in-memory (ConcurrentQueue) and flushed to the database by a background worker — zero impact on request latency.
  • Requires .NET 10.0+
  • Dual Database Provider: เลือกระหว่าง LogProvider.MySql (default) และ LogProvider.PostgreSql ผ่าน SharedLog:Provider ใน config — โค้ดเดียวกัน ไม่ต้องเปลี่ยน Program.cs
  • LogProvider.None (2.4.0+): ปิดการเก็บ log ลง DB ไปเลย ไม่มีการต่อ connection เลยสักครั้ง ใช้เมื่อตั้งใจไม่ใช้ DB pipeline นี้ (เช่น ย้ายไปใช้ Elasticsearch/OTel แทน)
  • Fail-safe startup (2.4.0+): ไม่มีทางที่ logging pipeline จะทำให้ host application ของคุณ start ไม่ขึ้น — ไม่ตั้ง connection string, connection string ผิด, หรือต่อ database ไม่ติด (ทุก repository เปิด connection จริงและรัน DDL ใน constructor) ทั้งสามเคสจะ log คำเตือนออก Console แล้ว fallback ไปใช้ no-op repository โดยอัตโนมัติ แทนที่จะ throw ออกมาเหมือนเวอร์ชันก่อนหน้า
  • Dual Logging Pipelines:
    • AddAppLogging — Captures structured Serilog events (level, message, exception, trace ID, metadata) into logs_app table.
    • AddHttpLogging — Captures full HTTP pairs (method, URL, headers, body, status code, duration) into logs_http table.
  • Configurable Batch Flush: Flush is triggered when batch reaches BatchSize OR when BatchTimeoutSeconds elapses — whichever comes first.
  • Path Filtering: Both pipelines support SharedLog:IgnorePaths to skip health checks, metrics endpoints, etc. — HTTP logging skips the request/response row outright; App logging drops every log line (framework or application code) emitted while handling a request on an ignored path. The app-log side of this requires app.UseHttpLogging(...) to be active (it's what pushes the current request's path onto Serilog's LogContext) — AddAppLogging alone, without the HTTP middleware, cannot filter by path.
  • App Log Level Filtering: AppLogMinimumLevel controls the minimum Serilog level stored in MySQL (e.g. Warning to skip Information/Debug entirely).
  • Outbound HTTP Tracing: HttpLoggingHandler (DelegatingHandler) logs outgoing HTTP client calls to a dedicated MySQL table (default logs_http_partner) via IHttpLogQueue, with table name configurable per deployment.
  • Multi-table Support: MySqlHttpLogRepository accepts an optional tableName parameter — register separate pipelines for inbound and outbound logs without any code duplication.
  • Reference Header Indexing: Configure SharedLog:ReferenceHeaders to extract business-key headers (e.g. x-order-id, x-log-key) into a separate logs_reference table, enabling fast reverse lookup from a business key back to the originating TraceId.
  • PostgreSQL Weekly Partitioning (PostgreSQL only — see below): logs_app/logs_http/logs_reference are created as PARTITION BY RANGE (timestamp) with weekly partitions (each partition's own data stays small), bootstrapped 4 weeks ahead on startup. IPartitionMaintenanceService / AddLogPartitionMaintenance let a scheduled job keep future partitions created ahead of time, however far out you want that buffer — monthsAhead (2.3.2+) still creates weekly partitions, just expressed as "how many months should this reach."

Installation & Setup

1. Register Services in Program.cs

App Event Logging (Serilog → MySQL)
using Shared.Logs.Extensions;

// Option 1: Automatic from Configuration (reads ConnectionStrings:LogEvent by default)
builder.AddAppLogging(builder.Configuration);

// Option 1b: Automatic from Configuration, but read the connection string from a different key
builder.AddAppLogging(builder.Configuration, connectionStringName: "MyCustomLogEventKey");

// Option 2: Manual setup via Action
builder.AddAppLogging(options => {
    options.ConnectionString = "Server=localhost;Database=logs_db;...";
    options.ServiceName = "Order-Core-API";
    options.IgnorePaths = new List<string> { "/health", "/metrics" };
    options.BatchSize = 200;
    options.BatchTimeoutSeconds = 10;
});

IgnorePaths here only takes effect if app.UseHttpLogging(...) is also registered (see below) — that middleware is what stamps the current request's path onto every log event for AppLogSink to check.

HTTP Request/Response Logging
// Option 1: Automatic from Configuration (reads ConnectionStrings:LogRequest by default)
builder.AddHttpLogging(builder.Configuration);

// Option 1b: Automatic from Configuration, but read the connection string from a different key
builder.AddHttpLogging(builder.Configuration, connectionStringName: "MyCustomLogRequestKey");

// Option 2: Manual setup via Action
builder.AddHttpLogging(options => {
    options.ConnectionString = "Server=localhost;Database=logs_db;...";
    options.ServiceName = "Order-Core-API";
    options.IgnorePaths = new List<string> { "/health", "/metrics" };
});

2. Enable Middleware in Program.cs

var app = builder.Build();

// Enable HTTP logging middleware (must be registered early in the pipeline)
app.UseHttpLogging("Order-Core-API");

app.Run();

3. Configuration Template (appsettings.json)

{
  "ConnectionStrings": {
    "LogEvent":   "Server=localhost;Port=3306;Database=sprint_logs;Uid=root;Pwd=secret;",
    "LogRequest": "Server=localhost;Port=3306;Database=sprint_logs;Uid=root;Pwd=secret;"
  },
  "SharedLog": {
    "ServiceName":          "Sprint-OMS-Order-API",
    "BatchSize":            100,
    "BatchTimeoutSeconds":  5,
    "AppLogMinimumLevel":   "Warning",
    "Provider":               "MySql",
    "IgnorePaths": [
      "/health",
      "/favicon.ico",
      "/metrics"
    ],
    "ReferenceHeaders": [
      "x-log-key",
      "x-order-id"
    ]
  }
}

App Log Minimum Level

Control which Serilog levels get persisted to MySQL via SharedLog:AppLogMinimumLevel. Accepts any Serilog LogEventLevel value:

Value Stored levels
Verbose All
Debug Debug and above
Information Information and above (default)
Warning Warning, Error, Fatal only
Error Error and Fatal only
Fatal Fatal only

Serilog console output is unaffected — this filter applies only to MySQL storage.


Outbound HTTP Client Tracing

HttpLoggingHandler is a DelegatingHandler that logs every outgoing HTTP call to MySQL. It requires an IHttpLogQueue instance — register a keyed "outbound" queue pointing to a separate table:

// In your integration DI registration:
var connStr = configuration.GetConnectionString("LogRequest") ?? string.Empty;
var serviceName = configuration["SharedLog:ServiceName"] ?? "unknown";
var outboundTable = configuration["SharedLog:OutboundTableName"] ?? "logs_http_partner";

services.AddKeyedSingleton<IHttpLogQueue, HttpLogQueueService>("outbound");
services.AddHostedService(sp => new HttpLogProcessingWorker(
    sp.GetRequiredKeyedService<IHttpLogQueue>("outbound"),
    new MySqlHttpLogRepository(new HttpLogOptions { ConnectionString = connStr, ServiceName = serviceName }, outboundTable),
    sp.GetRequiredService<ILogger<HttpLogProcessingWorker>>(),
    sp.GetRequiredService<HttpLogOptions>()
));

services.AddTransient<HttpLoggingHandler>(sp => new HttpLoggingHandler(
    sp.GetRequiredService<ILogger<HttpLoggingHandler>>(),
    sp.GetRequiredKeyedService<IHttpLogQueue>("outbound"),
    sp.GetRequiredService<HttpLogOptions>(),
    sp.GetRequiredService<IHttpContextAccessor>()
));

// Attach to Refit/HttpClient:
services.AddRefitClient<IMyClient>()
    .AddHttpMessageHandler<HttpLoggingHandler>();

Outbound rows are distinguishable by IpAddress IS NULL in the logs_http_partner table.

Config (appsettings.json):

"SharedLog": {
  "OutboundTableName": "logs_http_partner"
}

PostgreSQL Table Schema

logs_app — Application Event Log

Partitioned weekly by timestamp (see PostgreSQL Partitioning above) — the primary key is composite (id, timestamp), not id alone (PostgreSQL requires the partition key in the primary key).

Column Type Description
id BIGINT GENERATED ALWAYS AS IDENTITY Primary key (with timestamp)
timestamp TIMESTAMPTZ UTC event time — partition key
service_name VARCHAR(100) Name of the originating service
trace_id VARCHAR(100) Distributed trace correlation ID
level VARCHAR(20) Serilog log level
message TEXT Rendered log message
exception TEXT Full exception string (nullable)
source_context VARCHAR(255) Class/namespace origin (nullable)
metadata JSONB Additional log properties (nullable)

logs_http / logs_http_partner — HTTP Request/Response Log

Partitioned weekly by timestamp, same as logs_app above.

Column Type Description
id BIGINT GENERATED ALWAYS AS IDENTITY Primary key (with timestamp)
timestamp TIMESTAMPTZ UTC request time — partition key
service_name VARCHAR(100) Name of the originating service
trace_id VARCHAR(100) Distributed trace correlation ID
method VARCHAR(10) HTTP method
url TEXT Full request URL
request_headers JSONB Captured request headers (nullable)
request_body JSONB Request body (nullable)
status_code INT HTTP response status code
response_headers JSONB Captured response headers (nullable)
response_body JSONB Response body (nullable)
duration_ms BIGINT Request duration in milliseconds
ip_address VARCHAR(50) Client IP — NULL for outbound
source_context VARCHAR(255) Class/namespace origin (nullable)

logs_reference — Request Header Reference Index

Partitioned weekly by timestamp, same as logs_app above.

Column Type Description
id BIGINT GENERATED ALWAYS AS IDENTITY Primary key (with timestamp)
timestamp TIMESTAMPTZ UTC request time — partition key
trace_id VARCHAR(100) Distributed trace correlation ID
reference_key VARCHAR(100) Header name (เช่น x-order-id)
reference_value VARCHAR(512) Raw header value

PostgreSQL tables are partitioned weekly — see the "PostgreSQL Partitioning" section below. MySQL tables are plain (not partitioned) — MySQL's own partition support was deliberately removed in 2.0.0; set up partitioning/retention separately at the DB level for MySQL if needed.


PostgreSQL Partitioning

logs_app, logs_http, and logs_reference are created as PARTITION BY RANGE (timestamp) when using LogProvider.PostgreSql, with one partition per Monday-start week, named as an inclusive date range rather than an ISO week number (2.3.2+; e.g. logs_app_20260701_20260707 — was logs_app_2026w27) so the covered dates read at a glance. This keeps each physical partition small (fast inserts/index maintenance) and lets old weeks be archived or dropped by detaching a partition instead of a slow bulk DELETE.

Partitions created by an older library version keep their _YYYYwWW name forever — this only changes the name given to newly created partitions going forward. Rename an existing one yourself if you want it consistent: ALTER TABLE "logs_app_2026w27" RENAME TO "logs_app_20260701_20260707"; (safe — a rename doesn't touch the data or the parent table's routing).

Postgres rejects an INSERT whose timestamp falls outside every existing partition (ERROR: no partition of relation "..." found for row) — and this library's repositories catch that error silently (same as any other insert failure, see Resilience Design), so a missing partition means log entries silently stop being persisted, not a crash. Two things guard against that:

  1. Startup bootstrap: EnsureTableExists() creates the current week + 3 weeks ahead (4 total) every time a repository is constructed — a normal app (re)start refreshes this automatically.
  2. IPartitionMaintenanceService: register it once, in whichever service owns partition upkeep, and call it from a scheduled job (a daily or weekly Hangfire recurring job, a Kubernetes CronJob, etc.) so partitions keep getting created ahead of time for long-running processes that outlive the bootstrap's 4-week buffer.
// In the service responsible for partition maintenance (e.g. Master.API) — registers
// IPartitionMaintenanceService in DI, reading the Postgres connection string from
// ConnectionStrings:LogEvent by default.
builder.AddLogPartitionMaintenance(builder.Configuration);

// Or with an explicit connection string key / table list:
builder.AddLogPartitionMaintenance(builder.Configuration, connectionStringName: "LogEvent", "logs_app", "logs_http", "logs_reference");
// From a Hangfire recurring job (or any IHostedService/CronJob) — partitions stay weekly, but how
// far ahead to create them ("weeksAhead" pre-2.3.2) is now expressed in months instead:
public class PartitionMaintenanceJob(IPartitionMaintenanceService maintenance)
{
    public Task RunAsync(CancellationToken ct) => maintenance.EnsureUpcomingPartitionsAsync(monthsAhead: 4, ct);
}

Creating a new partition acquires a SHARE UPDATE EXCLUSIVE lock on the parent table (PostgreSQL 11+) — it does not block concurrent SELECT/INSERT/UPDATE/DELETE, so the maintenance job is safe to run at any time, including while the app is actively writing logs.

Multiple instances pointed at the same database (e.g. two app instances starting at once, or a locally-run instance sharing a non-prod database with the real deployed one) can race to bootstrap the same week's partition concurrently. CREATE TABLE IF NOT EXISTS is not atomic against that — the losing session can still get 42P07 (duplicate_table) (fixed in 2.3.4) even though the table already exists by the time the statement returns. Both EnsureWeeklyPartition/EnsureWeeklyPartitionAsync catch and swallow that specific error, since the end state ("the partition exists") is the same either way.

Converting an existing, already-populated plain table to partitioned is not a plain ALTER TABLE in PostgreSQL — it requires creating a new partitioned table, copying data across, then renaming. This only matters if a logs_app/logs_http/logs_reference table already has rows from before upgrading to 2.1.0; a fresh table (new environment, or one with no data yet) is created partitioned from the start with no extra steps.


MySQL Table Schema

logs_app — Application Event Log

Column Type Description
Id BIGINT AUTO_INCREMENT Primary key
Timestamp DATETIME(6) UTC event time
ServiceName VARCHAR(100) Name of the originating service
TraceId VARCHAR(100) Distributed trace correlation ID
Level VARCHAR(20) Serilog log level (Information, etc.)
Message LONGTEXT Rendered log message
Exception LONGTEXT Full exception string (nullable)
SourceContext VARCHAR(255) Class/namespace origin (nullable)
Metadata JSON Additional log properties (nullable)

logs_http / logs_http_partner — HTTP Request/Response Log

Column Type Description
Id BIGINT AUTO_INCREMENT Primary key
Timestamp DATETIME(6) UTC request time
ServiceName VARCHAR(100) Name of the originating service
TraceId VARCHAR(100) Distributed trace correlation ID
Method VARCHAR(10) HTTP method (GET, POST, etc.)
Url TEXT Full request URL
RequestHeaders JSON Captured request headers (nullable)
RequestBody LONGTEXT Request body (nullable)
StatusCode INT HTTP response status code
ResponseHeaders JSON Captured response headers (nullable)
ResponseBody LONGTEXT Response body (nullable)
DurationMs BIGINT Request duration in milliseconds
IpAddress VARCHAR(50) Client IP address — NULL for outbound calls

logs_reference — Request Header Reference Index

ใช้สำหรับ trace ย้อนกลับจาก business key (เช่น x-order-id: 12345) ไปยัง trace_id ของ HTTP request ที่ส่ง header นั้นเข้ามา ตารางจะถูกสร้างโดยอัตโนมัติเช่นเดียวกับตารางอื่น เมื่อ SharedLog:ReferenceHeaders ถูกกำหนดอย่างน้อยหนึ่งค่า

Column Type Description
id BIGINT AUTO_INCREMENT Primary key
timestamp DATETIME(6) UTC request time (ตรงกับ logs_http.timestamp)
trace_id VARCHAR(100) Distributed trace correlation ID
reference_key VARCHAR(100) Header name (เช่น x-order-id)
reference_value VARCHAR(512) Raw header value

มี composite index (reference_key, reference_value) สำหรับ reverse lookup:

-- หา trace_id ทั้งหมดที่ผูกกับ order 12345
SELECT trace_id FROM logs_reference
WHERE reference_key = 'x-order-id' AND reference_value = '12345';

-- join กลับไปดู request log
SELECT h.*
FROM logs_http h
JOIN logs_reference r ON r.trace_id = h.trace_id
WHERE r.reference_key = 'x-order-id' AND r.reference_value = '12345';

ถ้า request ไม่มี header ที่กำหนดใน ReferenceHeaders → ไม่บันทึก row ถ้า ReferenceHeaders ว่าง → ไม่สร้างตาราง ไม่เปิด worker (no-op)


Resilience Design

  • Zero-loss on insert failure: errors are caught silently — a failed batch does not crash the worker or the application.
  • Postgres HTTP-log body fallback (2.3.1+, PostgreSqlHttpLogRepository only): request_body/response_body are JSONB, and Postgres' jsonb type rejects a raw NUL (\u0000) codepoint even inside a validly-escaped JSON string — logging a binary body (e.g. a file upload captured by HttpLoggingHandler) is all but guaranteed to hit this. Since a batch is one multi-row INSERT, one bad entry used to fail the whole batch. InsertRequestLogsBatchAsync now retries once with both body fields stripped (NULL) on failure, so every entry's metadata (url/method/status_code/duration_ms/trace_id) still persists — only the body is lost, not the row. Don't route large/binary request bodies through the logged HttpClient if you need the body itself preserved; log those calls by hand with the body omitted instead.
  • Self-sealing loop: The background worker catches all unhandled exceptions, logs them, and retries after 1 second.
  • Graceful shutdown: When Kubernetes sends SIGTERM, both workers drain all remaining queue items to MySQL before the process exits. No log entries are lost during rolling deploys or scale-down events.
  • Manual flush for batch jobs: For CronJobs or short-lived processes that exit immediately after finishing work, call FlushAsync() explicitly before the process exits:
// At the end of a batch job
await httpLogQueue.FlushAsync();
await appLogQueue.FlushAsync();

© 2026 Sprint-OMS Development Team

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 (1)

Showing the top 1 NuGet packages that depend on Sprint.Shared.Logs:

Package Downloads
Sprint.Shared.Infrastructure

Shared infrastructure library for Sprint OMS services (.NET 10+): base handlers/entities, repositories and unit of work, FastEndpoints/OpenAPI helpers, caching (Redis + output cache), gRPC interceptors, observability (OpenTelemetry), Hangfire scheduling, adaptive concurrency, column encryption and HTTP client helpers.

GitHub repositories

This package is not used by any popular GitHub repositories.