Muonroi.Logging
2.0.2
dotnet add package Muonroi.Logging --version 2.0.2
NuGet\Install-Package Muonroi.Logging -Version 2.0.2
<PackageReference Include="Muonroi.Logging" Version="2.0.2" />
<PackageVersion Include="Muonroi.Logging" Version="2.0.2" />
<PackageReference Include="Muonroi.Logging" />
paket add Muonroi.Logging --version 2.0.2
#r "nuget: Muonroi.Logging, 2.0.2"
#:package Muonroi.Logging@2.0.2
#addin nuget:?package=Muonroi.Logging&version=2.0.2
#tool nuget:?package=Muonroi.Logging&version=2.0.2
Muonroi.Logging
High-performance asynchronous structured logging engine for Muonroi. Features zero-allocation log events via
ObjectPool<LogEvent>, asynchronous processing viaSystem.Threading.Channels(MuonroiLogQueue), and aDiskBufferStorefor graceful shutdown and data loss prevention.
Muonroi.Logging provides a robust, opinionated, high-throughput asynchronous logging layer on top of Microsoft.Extensions.Logging. It registers IMLog<T> — a structured logger with Info/Warn/Error/Debug/InfoTrace helpers — and automatically pushes TenantId, UserId, and CorrelationId from the ambient ISystemExecutionContextAccessor into every log scope.
The package is powered by a custom asynchronous logging engine utilizing System.Threading.Channels (MuonroiLogQueue) to offload I/O operations from the calling thread. It utilizes an ObjectPool<LogEvent> to ensure zero-allocation during steady-state logging, and integrates a DiskBufferStore to gracefully handle host shutdown, fallback scenarios, and prevent log data loss. The engine routes log entries to the underlying Microsoft.Extensions.Logging.ILogger, allowing the host application to configure sinks independently.
It also provides IMLogContext for pushing arbitrary key-value properties, IMLogFactory for creating loggers by type or category name, and ILogScopeFactory for building scopes from property dictionaries.
Installation
dotnet add package Muonroi.Logging --prerelease
Quick Start
using Muonroi.Core.Abstractions.Context;
using Muonroi.Logging;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
// Register the high-performance Async Logging Engine:
// IMLogContext, IMLog<T>, IMLogFactory, MuonroiLogQueue, and DiskBufferStore.
builder.Logging.AddMuonroiLogging();
// IMLog<T> auto-enriches log lines with TenantId/UserId/CorrelationId from the
// ambient execution context. AddCoreServices() provides this automatically;
// register the default accessor explicitly when using logging in isolation.
builder.Services.AddSingleton<ISystemExecutionContextAccessor, SystemExecutionContextAccessor>();
builder.Services.AddControllers();
WebApplication app = builder.Build();
app.MapControllers();
await app.RunAsync();
Inject IMLog<T> into any service or controller:
using Muonroi.Logging.Abstractions;
public sealed class OrderService(IMLog<OrderService> log)
{
public void Process(int orderId)
{
log.Debug("Starting order {OrderId}", orderId);
using IMLogContextScope scope = log.BeginProperty("OrderId", orderId);
log.Info("Processing order inside scoped property");
try
{
// ...
}
catch (Exception ex)
{
log.Error(ex, "Order {OrderId} failed", orderId);
}
}
}
Create a logger for an arbitrary category name via IMLogFactory:
public sealed class PaymentProcessor(IMLogFactory logFactory)
{
public void Charge(string provider)
{
IMLog providerLog = logFactory.CreateLogger(provider);
providerLog.Info("Charging via {Provider}", provider);
}
}
Features
- Asynchronous Processing (
MuonroiLogQueue): Offloads log formatting and emission from caller threads usingSystem.Threading.Channelsfor maximum application throughput. - Zero-Allocation Logging: Uses
ObjectPool<LogEvent>to reuse log event objects and eliminate GC pressure during heavy logging. - Disk Buffering (
DiskBufferStore): Ensures logs are safely written to a disk buffer during unexpected outages or when the application is gracefully shutting down, preventing data loss. IMLog<T>— category-typed structured logger withInfo,Warn,Error,Debug, andInfoTracehelper methods, all delegating to the innerILogger<T>- Automatic ambient enrichment — every log call acquires a scope carrying
TenantId,UserId, andCorrelationIdfromISystemExecutionContextAccessor IMLogContext.PushProperty/PushProperties— push arbitrary key-value pairs as structured log scopes that are removed onDisposeIMLog.BeginProperty— shorthand onIMLogforIMLogContext.PushPropertyIMLogFactory— createsIMLog<T>orIMLogby category name; useful for dynamic or per-provider loggersILogScopeFactory— creates scopes fromIReadOnlyDictionary<string, object?>for bulk property injectionLogPropertyConventions— well-known property key constants (TenantId,UserId,CorrelationId,TraceSessionId,RuleCode,RequestName)- Trace session integration — when
IMTraceContextis present,Info/Warn/Error/Debug/InfoTracealso record messages to the active trace session
Configuration
Call AddMuonroiLogging() on the ILoggingBuilder (typically builder.Logging):
builder.Logging.AddMuonroiLogging();
This registers the high-performance async logging engine and the following singletons:
| Registration | Implementation |
|---|---|
IMLogContext |
MLogContext |
IMLog<> (open generic) |
MLog<> |
IMLogFactory |
MLogFactory |
ILogScopeFactory |
MLogScopeFactory |
No appsettings.json section is required for the engine itself. Log level filtering and routing are controlled by the standard Microsoft.Extensions.Logging configuration already present in your host (e.g. configuring the console sink, application insights, etc. independently).
MLog<T> requires ISystemExecutionContextAccessor to be registered. When using Muonroi.Core in the same host, AddCoreServices() registers it automatically. For isolated setups (tests, samples), register the default implementation manually:
builder.Services.AddSingleton<ISystemExecutionContextAccessor, SystemExecutionContextAccessor>();
Architecture Details
- Serilog Replacement: Previous versions relied on Serilog internals. The package now utilizes a pure
Microsoft.Extensions.Loggingarchitecture combined with a custom high-performance async logging engine. - MuonroiLogQueue: A background service that listens to
System.Threading.Channelsto batch and process log events off the main application threads. - DiskBufferStore: In high-load scenarios or during shutdown,
DiskBufferStorecatches un-drained log events and flushes them to local storage, ensuring that no logs are lost.
API Reference
| Type | Purpose |
|---|---|
IMLog |
Base structured logger: Info, Warn, Error, Debug, InfoTrace, BeginProperty |
IMLog<T> |
Category-typed variant of IMLog; extends ILogger<T> |
IMLogFactory |
Creates IMLog<T> or IMLog by category name |
IMLogContext |
Pushes properties into the ambient log scope via PushProperty / PushProperties |
IMLogContextScope |
Disposable scope returned by PushProperty; removes the property on Dispose |
ILogScopeFactory |
Creates scopes from a property dictionary via BeginScope |
LogPropertyConventions |
String constants for TenantId, UserId, CorrelationId, TraceSessionId, RuleCode, RequestName |
MLogServiceCollectionExtensions |
ILoggingBuilder.AddMuonroiLogging() extension method |
Samples
- Quickstart.Logging — ASP.NET Core API demonstrating
IMLog<T>emit,BeginPropertyscoped logging, andIMLogFactorycategory-name creation
Compatibility
- Target framework:
net8.0 - License: Apache-2.0 (OSS)
Related Packages
Muonroi.Logging.Abstractions— contracts only (IMLog,IMLog<T>,IMLogFactory,IMLogContext,IMLogContextScope,ILogScopeFactory,LogPropertyConventions); reference this instead ofMuonroi.Loggingin library projects that only consume the interfacesMuonroi.Core.Abstractions— providesISystemExecutionContextAccessorandISystemExecutionContextused for ambient context enrichment
Ecosystem Combinations
+ Tenancy.Core → Tenant-Enriched Logs
ContextMirrorScope automatically enriches every log entry with tenantId, userId, correlationId from the ambient ISystemExecutionContext — no manual log scope setup:
_log.Info("Order processed"); // automatically tagged with tenantId + traceId
+ Observability → Unified Logs + Traces + Metrics
When both packages are registered, log entries are correlated to OTel trace spans via TraceId/SpanId. Logs appear as events on their parent span in Jaeger/Grafana Tempo.
+ Mediator → Pipeline Behavior Logging
Request/response logging behavior wraps every IMediator.Send() with structured entry/exit logs including request type, duration, and success/failure.
+ Diagnostics → Logs Inside Trace Nodes
Log entries emitted within a diagnostic session are attached to the current trace node, creating a combined log+trace view.
Full Logging Stack
builder.Services
.AddMuonroiLogging(config) // IMLog<T> + structured Serilog
.AddTenantContext(config) // auto-enrich with tenantId
.AddMuonroiObservability(config); // correlate logs to OTel traces
Samples
License
Apache-2.0. See LICENSE-APACHE.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. 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. |
-
net8.0
- Microsoft.Extensions.Logging (>= 10.0.3)
- Muonroi.Core.Abstractions (>= 2.0.2)
- Muonroi.Logging.Abstractions (>= 2.0.2)
NuGet packages (3)
Showing the top 3 NuGet packages that depend on Muonroi.Logging:
| Package | Downloads |
|---|---|
|
Muonroi.Core
Core services implementation: datetime, JSON serialization, logging wrappers, and system execution context for Muonroi applications. |
|
|
Muonroi.Mediator
Mediator pattern implementation for Muonroi: command/query dispatching, pipeline behaviors, and validation integration. |
|
|
Muonroi.Pdf
HTML/CSS to PDF layout engine: box-tree construction, pagination, and rendering coordination for Muonroi applications. |
GitHub repositories
This package is not used by any popular GitHub repositories.