High-performance structured logging for .NET 9 — MEL-compatible, async-first, production-grade.
---
| Metric | SinkSharp | Serilog | Result |
|---|---|---|---|
| Hot path no enrichers | 843 ns | 2,672 ns | 3.2× faster |
| Hot path all enrichers | 795 ns | 2,672 ns | 3.0× faster |
| P95 mixed load | 1.82 µs | 3.70 µs | 2.0× lower tail |
| P99 mixed load | 1.33 µs mean | 2.82 µs mean | 2.1× faster |
| Allocation 0 props | 80 B | 161 B | 50% less |
| Allocation 3 props | 341 B | 473 B | 28% less |
| Lock contentions @ 4 threads | ~0 | 1,575 | Near-zero |
| Caller blocked by slow sink | No (715 ns) | Yes | Async isolated |
| Producer scaling 4 threads | 3.2 ms | 31.1 ms | 9.7× faster |
| E2E durability 32 producers | 0 events lost | — | Verified zero loss |
Measured on .NET 9.0.20, Windows 11, X64 RyuJIT AVX2. Comparison vs Serilog buffered file sink. See benchmarks/README.md for full methodology and raw numbers.
| Package | Version | Purpose |
|---|---|---|
| SinkSharp.Core | Core pipeline, enrichers, MEL adapter | |
| SinkSharp.Sinks.Console | Coloured structured console output | |
| SinkSharp.Sinks.File | Rolling JSONL file sink (CLEF format) | |
| SinkSharp.Sinks.Dashboard | Embedded real-time web dashboard | |
| SinkSharp.Sinks.Dashboard.Redis | Shared, persistent dashboard history on Redis Streams | |
| SinkSharp.Enrichers.Azure | Azure context (region, resource group, pod) | |
| SinkSharp.Sinks.OpenTelemetry | OTLP log export + distributed tracing — Jaeger, Grafana Loki, Datadog, New Relic, Azure Monitor |
dotnet add package SinkSharp.Core
dotnet add package SinkSharp.Sinks.Console
dotnet add package SinkSharp.Sinks.Filevar logger = SinkSharpBuilder
.Create()
.MinimumLevel(LogLevel.Information)
.MinimumLevelFor("Microsoft", LogLevel.Warning)
.WithCorrelationId()
.WithEnvironment("MyApp", "Production")
.WithPiiMasking()
.WriteTo(new ColoredConsoleSink(), LogLevel.Debug)
.WriteTo(new RollingFileSink("logs/app.jsonl"), LogLevel.Warning)
.BuildLogger("MyApp");
logger.LogInformation("Order {OrderId} placed by {Customer}", 42, "alice@example.com");
// alice@example.com → automatically PII-masked
// CorrelationId → captured from AsyncLocal, stamped on every eventbuilder.Services.AddSinkSharp(options => options
.MinimumLevel(LogLevel.Information)
.MinimumLevelFor("Microsoft", LogLevel.Warning)
.WithCorrelationId()
.WithEnvironment("MyApp", builder.Environment.EnvironmentName)
.WithPiiMasking()
.WriteTo(new ColoredConsoleSink(), LogLevel.Debug)
.WriteTo(new RollingFileSink("logs/app.jsonl"), LogLevel.Warning));
// Web API / Minimal API: reads X-Correlation-Id header, generates if missing,
// sets CorrelationContext (AsyncLocal), writes response header.
// Worker Service / Console App: use CorrelationContext.Use(id) per job instead.
app.UseSinkSharp();SinkSharp includes an embedded real-time log dashboard — free, included with the package, no separate licence required. Mounts on your existing ASP.NET Core app at the same host and port. No extra process, no extra port.
- ⚡ Real-time event stream via SignalR WebSocket
- 🕑 Buffer replay — last 500 events shown immediately on connect
- 📜 v1.1.0 — Load older: page back through history, with level, search and correlation filters applied on the server
- 🗄️ v1.1.0 — Optional Redis Streams history: shared across pods and preserved across restarts (SinkSharp.Sinks.Dashboard.Redis)
- 🧭 v1.1.0 — Focused, chronological view: events listed in time order, with the dashboard's own traffic kept out of the way
- 🔄 v1.1.0 — Self-healing connection: automatic recovery with a gentle back-off, new events keep appearing on their own while degraded, and the pod's recent events always on hand
- 🩺 v1.1.0 —
GET {dashboard}/healthandAddSinkSharpDashboardHealthCheck(): a reachability check for the history store, independent of whether a dashboard tab is open - 🔍 Filter by level, service, correlation ID, time range (All / 5m / 30m / 1h)
- 🔎 Full-text search (plain text or regex toggle)
- 🔖 v1.0.5 — Pin / bookmark individual events to a sticky
Pinnedsection above the log list - 🏷️ v1.0.5 — Property filter panel: filter by any structured key/value from the current buffer
- 📌 v1.0.5 —
📌 Onlytoolbar button: show only pinned events in the main log list - ⊞ v1.0.5 —
⊞ Pinnedtoolbar button: full-screen pinned view with Unpin all and Back to logs - 📋 Properties tab, stack trace tab, JSON copy, CSV export (UTF-8 BOM)
- 📊 Queue stats — pending / processed / dropped (polled every 2s)
- 🔁 Reconnect indicator — shows retry count during SignalR reconnect
- 🌙 Dark / light theme toggle
- 🔗 Copy correlation ID to clipboard — ⧉ button in detail panel
- 🔗 Shareable URL with active filters
- 🔐 Auth: bearer JWT, named policy, shared token, IP allowlist, Basic auth
dotnet add package SinkSharp.Core
dotnet add package SinkSharp.Sinks.DashboardDashboardSink dashSink = null!;
builder.Services.AddSinkSharp(options => options
.WithDashboard(out dashSink)
.WriteTo(new ColoredConsoleSink(), LogLevel.Debug)
.WriteTo(new RollingFileSink("logs/app.jsonl"), LogLevel.Warning));
builder.Services.AddSinkSharpDashboard(dashSink);
var app = builder.Build();
app.UseSinkSharpDashboard("/sinksharp/dashboard");
// → https://localhost:5001/sinksharp/dashboardvar builder = SinkSharpBuilder.Create()
.WithDashboard(out var dashSink)
.WriteTo(new ColoredConsoleSink());
var logger = builder.BuildLogger("MyApp");
var dashboard = new DashboardServer(dashSink, port: 5341, queue: builder.GetQueue());
await dashboard.StartAsync();
// → http://localhost:5341builder.Services.AddSinkSharpDashboardRedis(dashSink, signalR =>
signalR.AddStackExchangeRedis(
builder.Configuration["Redis:ConnectionString"],
options => options.Configuration.ChannelPrefix =
StackExchange.Redis.RedisChannel.Literal("MyApp.SinkSharp")));
app.UseSinkSharpDashboard("/sinksharp/dashboard"); // unchangeddotnet add package SinkSharp.Sinks.Dashboard.Redisvar redis = builder.Configuration["Redis:ConnectionString"];
builder.Services.AddSinkSharpDashboardRedis(dashSink,
signalR => signalR.AddStackExchangeRedis(redis), // live stream across pods
streams => { streams.ConnectionString = redis; streams.RetentionDays = 7; }); // history across pods and restarts
app.UseSinkSharpDashboard("/sinksharp/dashboard"); // unchangedOpen the dashboard on any pod and it replays the recent events of every pod; Load older pages further back.
| Setup | History on connect | After a restart | Requires |
|---|---|---|---|
| Option 1 / 2 | This instance's recent events | Starts fresh | — |
| Option 3 | This pod's recent events, live stream from every pod | Starts fresh | Redis |
| Option 4 | Recent events from every pod | Preserved | Redis 5.0+ |
Caller thread (your code)
│
▼ Log() ← returns immediately, caller never blocks (~850 ns including enrichment)
Striped async channel queue (1 channel per CPU core, max 16)
│ Bounded (DropOldest) for Info / Debug / Warn
│ Unbounded for Error / Critical — never dropped
│
▼ Background drainer (thread pool)
SinkSharp pipeline
├── Enrichers (CorrelationId, Environment, PII masking, Azure context, user context)
├── Formatter (message template rendering)
└── Sinks (Console, File, Dashboard — all called on drainer thread)
Key properties:
- Zero lock contention on the hot path — caller enqueues and returns immediately
- CorrelationId captured on caller thread — AsyncLocal invisible on drainer thread
- Object pooling — LogEvent objects reused across calls, reducing GC pressure
- MessageTemplate cached after first parse — zero repeated parsing cost
- Sampler runs inside
IsEnabled()— dropped events cost nothing (no allocation)
builder.Services.AddSinkSharp(options => options
// Minimum level for all loggers
.MinimumLevel(LogLevel.Information)
// Override level for a specific category (exact match or dot boundary)
.MinimumLevelFor("Microsoft.AspNetCore", LogLevel.Warning)
.MinimumLevelFor("System", LogLevel.Error)
// Sampling (v1.0.9) — drop Debug / Info before enqueue to reduce noise at scale
// Warning / Error / Critical are never sampled; always pass through
.WithSampling(rate: 0.10, maxLevel: LogLevel.Debug) // keep 10% of Debug
.WithSampling(new SamplingOptions // per-level rates
{
[LogLevel.Debug] = 0.10,
[LogLevel.Information] = 0.50,
})
// Built-in enrichers — all project types
.WithCorrelationId() // AsyncLocal correlation ID
.WithEnvironment("MyApp", "Production") // AppName, Environment, MachineName
.WithMachineName() // MachineName only
.WithPiiMasking() // email / phone / card / SSN masking
// HTTP context enrichers — Web API / Minimal API only
// Option A: fluent builder (no accessor argument — resolved from DI automatically)
.WithUserContext() // UserId (sub), UserName (name), UserRole (role)
.WithUserContext(claims: ["userId", "role", "tenant"]) // custom JWT claim types
// Option B: DI registration (equivalent to Option A)
// builder.Services.AddSinkSharpRequestId();
// builder.Services.AddSinkSharpRequestPath();
// builder.Services.AddSinkSharpElapsedTime();
// builder.Services.AddSinkSharpUserContext(claims: ["userId", "role", "tenant"]);
// Azure enricher — requires SinkSharp.Enrichers.Azure package
.WithAzureContext() // AzureRegion, ResourceGroup, Slot, Pod, etc.
// Event filter — drops events before enqueue, zero allocation for dropped events
.Filter(e => !e.MessageTemplate.Contains("health"))
.Filter(e => e.Level >= LogLevel.Warning || e.Category.StartsWith("MyApp"))
// Conditional enrichment — enricher only runs when predicate is true
.WithEnricher(new MyEnricher(), when: e => e.Level >= LogLevel.Warning)
// Sinks with per-sink minimum level
.WriteTo(new ColoredConsoleSink(), LogLevel.Debug)
.WriteTo(new RollingFileSink("logs/app.jsonl"), LogLevel.Warning)
.WithDashboard(out dashSink, LogLevel.Information)
);
// AddHttpContextAccessor is required for all HTTP context enrichers
builder.Services.AddHttpContextAccessor();
// These are only needed if you did NOT use .WithUserContext() / WithRequestId() etc. above
// builder.Services.AddSinkSharpRequestId();
// builder.Services.AddSinkSharpRequestPath();
// builder.Services.AddSinkSharpElapsedTime();
// builder.Services.AddSinkSharpUserContext(claims: ["userId", "role", "tenant"]);
// Web API / Minimal API: X-Correlation-Id header lifecycle + ElapsedTime stopwatch
app.UseSinkSharp();
// Dynamic level at runtime — no restart needed
SinkSharpLoggerFactory.SetGlobalLevel(LogLevel.Debug); // enable debug temporarily
SinkSharpLoggerFactory.SetGlobalLevel(LogLevel.None); // restore startup level// ── Web API / Minimal API ────────────────────────────────────────────────────
// One line in Program.cs after Build().
// Reads X-Correlation-Id header, generates if missing, sets AsyncLocal,
// starts Stopwatch for ElapsedTime enricher, writes response header.
app.UseSinkSharp();
// ── Worker Service / Console App / Background Job ────────────────────────────
// No HTTP pipeline — set CorrelationContext manually per job or operation.
// AsyncLocal flows through every await boundary automatically.
using var _ = CorrelationContext.Use(Guid.NewGuid().ToString("N")[..12]);
// Every logger.Log*() inside this using block gets the CorrelationId.| Sample | What it shows |
|---|---|
| SinkSharp.AdvancedEnricherSample | Sampling, custom claims, filter, conditional enrichment, runtime level |
| SinkSharp.Sample | Console app, no DI |
| SinkSharp.WebApiSample | Web API with MEL |
| SinkSharp.WorkerSample | Background Worker |
| SinkSharp.MinimalApiSample | Minimal API |
| SinkSharp.MultiPodSample | Redis multi-pod + all auth options |
| SinkSharp.AzureSample | Azure context enricher + AKS deploy |
| SinkSharp.DashboardAuthSample | All dashboard auth modes with working code |
| SinkSharp.MultiSinkSample | Console + File + Dashboard |
| SinkSharp.CustomSinkSample | Custom sink implementation |
| SinkSharp.CustomEnricherSample | Custom enricher |
| SinkSharp.HealthCheckSample | ASP.NET health check integration |
| SinkSharp.ScopedLoggingSample | Scoped logging with ILogger |
Full runnable samples: SinkSharp-Logging-Samples
Ship logs and distributed traces to any OpenTelemetry backend — Jaeger, Grafana Loki, Datadog, New Relic, Honeycomb, Azure Monitor — with one package and a single config object. No OpenTelemetry SDK wiring required for log export.
dotnet add package SinkSharp.Sinks.OpenTelemetryvar otlpOptions = new OtlpLogSinkOptions
{
Endpoint = new Uri("http://localhost:4317"),
Protocol = OtlpProtocol.Grpc,
ServiceName = "MyApp",
ServiceVersion = "1.0.0",
DeploymentEnvironment = env,
};
builder.Services.AddSinkSharp(options => options
.WithCorrelationId()
.WithEnvironment("MyApp", env)
.WithPiiMasking() // masked before OTLP export
.WriteTo(new ColoredConsoleSink(), LogLevel.Debug)
.WriteTo(new OtlpLogSink(otlpOptions), LogLevel.Information));
builder.Services.AddSinkSharpTracing(otlpOptions, tracing => tracing
.AddAspNetCoreInstrumentation(o => o.RecordException = true)
.AddHttpClientInstrumentation()
.AddOtlpExporter(o =>
{
o.Endpoint = otlpOptions.Endpoint;
o.Protocol = OpenTelemetry.Exporter.OtlpExportProtocol.Grpc;
}));Every log record arrives at your backend carrying CorrelationId, UserId, RequestPath, ElapsedMs, Environment, and MachineName as structured OTel attributes — stamped in-process before export. PII masking runs before the sink sees the event, so sensitive data never leaves the application. Ready to query in Grafana, Jaeger, or Datadog without any additional configuration.
See SinkSharp.Sinks.OpenTelemetry for the full reference and SinkSharp.OpenTelemetrySample for a working Docker Compose setup.
| 🌐 Website | https://www.sinksharp.com |
| 📦 NuGet | nuget.org/profiles/sinksharp |
| 🧪 Samples | SinkSharp-Logging-Samples |
| 📋 Changelog | CHANGELOG.md |
| 📧 Support | support@sinksharp.com |
| 📄 Licence | Apache 2.0 |