Sprint.Shared.Logs
2.3.4
See the version list below for details.
dotnet add package Sprint.Shared.Logs --version 2.3.4
NuGet\Install-Package Sprint.Shared.Logs -Version 2.3.4
<PackageReference Include="Sprint.Shared.Logs" Version="2.3.4" />
<PackageVersion Include="Sprint.Shared.Logs" Version="2.3.4" />
<PackageReference Include="Sprint.Shared.Logs" />
paket add Sprint.Shared.Logs --version 2.3.4
#r "nuget: Sprint.Shared.Logs, 2.3.4"
#:package Sprint.Shared.Logs@2.3.4
#addin nuget:?package=Sprint.Shared.Logs&version=2.3.4
#tool nuget:?package=Sprint.Shared.Logs&version=2.3.4
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 - Dual Logging Pipelines:
AddAppLogging— Captures structured Serilog events (level, message, exception, trace ID, metadata) intologs_apptable.AddHttpLogging— Captures full HTTP pairs (method, URL, headers, body, status code, duration) intologs_httptable.
- Configurable Batch Flush: Flush is triggered when batch reaches
BatchSizeOR whenBatchTimeoutSecondselapses — whichever comes first. - Path Filtering: Both pipelines support
SharedLog:IgnorePathsto 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 requiresapp.UseHttpLogging(...)to be active (it's what pushes the current request's path onto Serilog'sLogContext) —AddAppLoggingalone, without the HTTP middleware, cannot filter by path. - App Log Level Filtering:
AppLogMinimumLevelcontrols the minimum Serilog level stored in MySQL (e.g.Warningto skipInformation/Debugentirely). - Outbound HTTP Tracing:
HttpLoggingHandler(DelegatingHandler) logs outgoing HTTP client calls to a dedicated MySQL table (defaultlogs_http_partner) viaIHttpLogQueue, with table name configurable per deployment. - Multi-table Support:
MySqlHttpLogRepositoryaccepts an optionaltableNameparameter — register separate pipelines for inbound and outbound logs without any code duplication. - Reference Header Indexing: Configure
SharedLog:ReferenceHeadersto extract business-key headers (e.g.x-order-id,x-log-key) into a separatelogs_referencetable, enabling fast reverse lookup from a business key back to the originatingTraceId. - PostgreSQL Weekly Partitioning (PostgreSQL only — see below):
logs_app/logs_http/logs_referenceare created asPARTITION BY RANGE (timestamp)with weekly partitions (each partition's own data stays small), bootstrapped 4 weeks ahead on startup.IPartitionMaintenanceService/AddLogPartitionMaintenancelet 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;
});
IgnorePathshere only takes effect ifapp.UseHttpLogging(...)is also registered (see below) — that middleware is what stamps the current request's path onto every log event forAppLogSinkto 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
_YYYYwWWname 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:
- 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. 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 EXISTSis not atomic against that — the losing session can still get42P07(duplicate_table) (fixed in 2.3.4) even though the table already exists by the time the statement returns. BothEnsureWeeklyPartition/EnsureWeeklyPartitionAsynccatch 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 TABLEin PostgreSQL — it requires creating a new partitioned table, copying data across, then renaming. This only matters if alogs_app/logs_http/logs_referencetable already has rows from before upgrading to2.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+,
PostgreSqlHttpLogRepositoryonly):request_body/response_bodyareJSONB, and Postgres'jsonbtype rejects a raw NUL (\u0000) codepoint even inside a validly-escaped JSON string — logging a binary body (e.g. a file upload captured byHttpLoggingHandler) is all but guaranteed to hit this. Since a batch is one multi-rowINSERT, one bad entry used to fail the whole batch.InsertRequestLogsBatchAsyncnow 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 loggedHttpClientif 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 | 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
- Microsoft.AspNetCore.Http.Abstractions (>= 2.3.9)
- Microsoft.Extensions.Hosting (>= 10.0.5)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.5)
- MySql.Data (>= 9.6.0)
- Npgsql (>= 10.0.3)
- Serilog (>= 4.3.1)
- Serilog.AspNetCore (>= 10.0.0)
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.
| Version | Downloads | Last Updated | |
|---|---|---|---|
| 2.4.0 | 123 | 11/20/2026 | |
| 2.3.4 | 599 | 10/5/2026 | |
| 2.1.0 | 128 | 9/18/2026 | |
| 2.0.0 | 643 | 7/29/2026 | |
| 1.4.4 | 384 | 6/25/2026 | |
| 1.4.3 | 170 | 6/25/2026 | |
| 1.4.2 | 168 | 6/25/2026 | |
| 1.4.1 | 161 | 6/24/2026 | |
| 1.4.0 | 159 | 6/23/2026 | |
| 1.3.2 | 223 | 6/4/2026 | |
| 1.3.1 | 167 | 6/4/2026 | |
| 1.2.4 | 172 | 5/25/2026 | |
| 1.2.3 | 148 | 5/25/2026 | |
| 1.2.2 | 156 | 5/25/2026 |