Muonroi.Logging 2.0.2

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

Muonroi.Logging

High-performance asynchronous structured logging engine for Muonroi. Features zero-allocation log events via ObjectPool<LogEvent>, asynchronous processing via System.Threading.Channels (MuonroiLogQueue), and a DiskBufferStore for graceful shutdown and data loss prevention.

NuGet License: Apache 2.0

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 using System.Threading.Channels for 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 with Info, Warn, Error, Debug, and InfoTrace helper methods, all delegating to the inner ILogger<T>
  • Automatic ambient enrichment — every log call acquires a scope carrying TenantId, UserId, and CorrelationId from ISystemExecutionContextAccessor
  • IMLogContext.PushProperty / PushProperties — push arbitrary key-value pairs as structured log scopes that are removed on Dispose
  • IMLog.BeginProperty — shorthand on IMLog for IMLogContext.PushProperty
  • IMLogFactory — creates IMLog<T> or IMLog by category name; useful for dynamic or per-provider loggers
  • ILogScopeFactory — creates scopes from IReadOnlyDictionary<string, object?> for bulk property injection
  • LogPropertyConventions — well-known property key constants (TenantId, UserId, CorrelationId, TraceSessionId, RuleCode, RequestName)
  • Trace session integration — when IMTraceContext is present, Info/Warn/Error/Debug/InfoTrace also 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.Logging architecture combined with a custom high-performance async logging engine.
  • MuonroiLogQueue: A background service that listens to System.Threading.Channels to batch and process log events off the main application threads.
  • DiskBufferStore: In high-load scenarios or during shutdown, DiskBufferStore catches 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, BeginProperty scoped logging, and IMLogFactory category-name creation

Compatibility

  • Target framework: net8.0
  • License: Apache-2.0 (OSS)
  • Muonroi.Logging.Abstractions — contracts only (IMLog, IMLog<T>, IMLogFactory, IMLogContext, IMLogContextScope, ILogScopeFactory, LogPropertyConventions); reference this instead of Muonroi.Logging in library projects that only consume the interfaces
  • Muonroi.Core.Abstractions — provides ISystemExecutionContextAccessor and ISystemExecutionContext used 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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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.

Version Downloads Last Updated
2.0.2 632 8/26/2026
2.0.1 534 8/26/2026
2.0.0 540 8/14/2026