Skip to content
ConsoleMonster

Logging

Microsoft.Extensions.Logging, Serilog and NLog adapters with ConsoleMonster's level tags, structured values and exceptions, and plain redirected output.

Add the provider to an existing project:

dotnet add package ConsoleMonster.Extensions.Logging

The provider depends only on Microsoft.Extensions.Logging.Abstractions and ConsoleMonster, and works with trimming and native AOT on .NET 8 and later.

Log entries the ConsoleMonster way

Every level, a scope, a structured message and an exception, through the Microsoft.Extensions.Logging provider.

dotnet run 66×1024-bitFull
dotnet new console -n Shop
cd Shop
dotnet add package ConsoleMonster.Extensions.Logging
dotnet add package Microsoft.Extensions.Logging
PowerShellRun.ps1View on GitHub
# … 9 lines of help in the full program
[CmdletBinding()]
param([string] $Project = '.')

& dotnet run --project $Project -c Release
if ($LASTEXITCODE -ne 0) { throw "The .NET example exited with code $LASTEXITCODE." }
Full program
<#
.SYNOPSIS
Runs the .NET integration project from PowerShell.
.DESCRIPTION
Create the project and save Program.cs from either C# tab first. The .NET host and logging provider own this lifecycle;
there is no separate PowerShell hosting implementation.
.PARAMETER Project
The project file or directory containing the saved C# program (default current directory).
#>
[CmdletBinding()]
param([string] $Project = '.')

& dotnet run --project $Project -c Release
if ($LASTEXITCODE -ne 0) { throw "The .NET example exited with code $LASTEXITCODE." }

Run: ./Run.ps1

PowerShell launches the same .NET project after Program.cs is saved from either C# tab. The generic host and ILogger provider have no separate cmdlet implementation.

Terminal
dotnet new console -n Shop
cd Shop
dotnet add package ConsoleMonster.Extensions.Logging
dotnet add package Microsoft.Extensions.Logging
C#Program.csView on GitHub
// Every level, a scope, a structured message and an exception.
using ILoggerFactory factory = LoggerFactory.Create(
    logging => logging.SetMinimumLevel(LogLevel.Trace)
        .AddConsoleMonster());
ILogger orders = factory.CreateLogger("Shop.Services.Orders");
ILogger cache = factory.CreateLogger("Shop.Infrastructure.Cache");
cache.LogTrace("Probing {Count} cache shards", 4);
cache.LogDebug("Shard {Shard} answered in {Ms} ms", "eu-1", 12);
using (orders.BeginScope("order {Id}", 1042))
{
    orders.LogInformation("Payment accepted: {Amount} EUR", 129.90m);
    orders.LogWarning("Stock is low for {Sku}: {Left} left", "A-17", 3);
}

try
{
    throw new TimeoutException("The payment gateway did not answer within 30 s.");
}
catch (TimeoutException ex)
{
    orders.LogError(ex, "Refund for order {Id} failed", 1038);
}

orders.LogCritical("Queue {Queue} is not draining", "orders-eu");
orders.LogInformation("Done; {Processed} orders processed", 57);
Full program
using ConsoleMonster.Extensions.Logging;
using Microsoft.Extensions.Logging;

// Every level, a scope, a structured message and an exception.
using ILoggerFactory factory = LoggerFactory.Create(
    logging => logging.SetMinimumLevel(LogLevel.Trace)
        .AddConsoleMonster());
ILogger orders = factory.CreateLogger("Shop.Services.Orders");
ILogger cache = factory.CreateLogger("Shop.Infrastructure.Cache");
cache.LogTrace("Probing {Count} cache shards", 4);
cache.LogDebug("Shard {Shard} answered in {Ms} ms", "eu-1", 12);
using (orders.BeginScope("order {Id}", 1042))
{
    orders.LogInformation("Payment accepted: {Amount} EUR", 129.90m);
    orders.LogWarning("Stock is low for {Sku}: {Left} left", "A-17", 3);
}

try
{
    throw new TimeoutException("The payment gateway did not answer within 30 s.");
}
catch (TimeoutException ex)
{
    orders.LogError(ex, "Refund for order {Id} failed", 1038);
}

orders.LogCritical("Queue {Queue} is not draining", "orders-eu");
orders.LogInformation("Done; {Processed} orders processed", 57);

Run: dotnet run

Terminal
dotnet new console -n Shop
cd Shop
dotnet add package ConsoleMonster.Extensions.Logging
dotnet add package Microsoft.Extensions.Logging
C# fluentProgram.cs
// Every level, a scope, a structured message and an exception.
using ILoggerFactory factory = LoggerFactory.Create(
    logging => logging.SetMinimumLevel(LogLevel.Trace)
        .AddConsoleMonster());
ILogger orders = factory.CreateLogger("Shop.Services.Orders");
ILogger cache = factory.CreateLogger("Shop.Infrastructure.Cache");
cache.LogTrace("Probing {Count} cache shards", 4);
cache.LogDebug("Shard {Shard} answered in {Ms} ms", "eu-1", 12);
using (orders.BeginScope("order {Id}", 1042))
{
    orders.LogInformation("Payment accepted: {Amount} EUR", 129.90m);
    orders.LogWarning("Stock is low for {Sku}: {Left} left", "A-17", 3);
}

try
{
    throw new TimeoutException("The payment gateway did not answer within 30 s.");
}
catch (TimeoutException ex)
{
    orders.LogError(ex, "Refund for order {Id} failed", 1038);
}

orders.LogCritical("Queue {Queue} is not draining", "orders-eu");
orders.LogInformation("Done; {Processed} orders processed", 57);
Full program
using ConsoleMonster.Extensions.Logging;
using Microsoft.Extensions.Logging;

// Every level, a scope, a structured message and an exception.
using ILoggerFactory factory = LoggerFactory.Create(
    logging => logging.SetMinimumLevel(LogLevel.Trace)
        .AddConsoleMonster());
ILogger orders = factory.CreateLogger("Shop.Services.Orders");
ILogger cache = factory.CreateLogger("Shop.Infrastructure.Cache");
cache.LogTrace("Probing {Count} cache shards", 4);
cache.LogDebug("Shard {Shard} answered in {Ms} ms", "eu-1", 12);
using (orders.BeginScope("order {Id}", 1042))
{
    orders.LogInformation("Payment accepted: {Amount} EUR", 129.90m);
    orders.LogWarning("Stock is low for {Sku}: {Left} left", "A-17", 3);
}

try
{
    throw new TimeoutException("The payment gateway did not answer within 30 s.");
}
catch (TimeoutException ex)
{
    orders.LogError(ex, "Refund for order {Id} failed", 1038);
}

orders.LogCritical("Queue {Queue} is not draining", "orders-eu");
orders.LogInformation("Done; {Processed} orders processed", 57);

Run: dotnet run

What it writes

  • The level tag and colour that Write-ConsoleLogEntry and the dashboard log region use: ◆ CRIT for Critical in the Critical style, ✗ ERR for Error, ▲ WARN for Warning, DBG and VERB muted for Debug and Trace, and no tag for Information.
  • With Words markers, the level appears once as [FAIL], [WARN] or [OK]. ASCII logs retain their short level words.
  • A timestamp (TimestampFormat, default HH:mm:ss; null leaves it out), then the category (the last part by default, Full or None) and the scopes in brackets.
  • An exception's type and message under the entry, with up to MaxExceptionLines lines of details.
  • While a ConsoleMonster dashboard or AddConsoleDashboard shows, entries go into its log region, so they never print over the view.
  • With output redirected, plain lines without escape codes.

Options

OptionDefaultMeaning
MinimumLevelTraceThe lowest level written; the logging builder's filters apply first.
TimestampFormatHH:mm:ssA .NET date format, or null for no timestamp.
UseUtcTimestampfalseUTC instead of local time.
CategoryShortShort, Full or None.
IncludeScopestrueShows the scopes after the category.
IncludeEventIdfalseShows the event id.
MaxExceptionLines12Lines of exception details; 0 for the type and message only.
LogRegion$logThe live log region to write into while one runs; null always prints.

Without dependency injection, use loggerFactory.AddConsoleMonster(). The provider is added once: a second AddConsoleMonster keeps the first call's options. It is thread-safe.

Native Serilog and NLog

These adapters use the logging framework's own events and event timestamps. Neither requires Microsoft.Extensions.Logging. Both target .NET Standard 2.0, .NET Framework 4.7.2, .NET 8 and .NET 10. All three logging adapters share ConsoleMonster's internal formatter; the core library remains dependency-free.

Serilog

dotnet add package ConsoleMonster.Extensions.Serilog
using Serilog;

using var logger = new LoggerConfiguration()
    .WriteTo.ConsoleMonster(options => options.TimestampFormat = "HH:mm:ss")
    .CreateLogger();
var log = logger.ForContext("SourceContext", "Shop.Orders");
log.Information("Order {OrderId} for {Customer}", 1042, "Ada");

The extension is in the Serilog namespace. The sink's restrictedToMinimumLevel defaults to Verbose; Serilog's own minimum level and filters apply first.

NLog

dotnet add package ConsoleMonster.Extensions.NLog
using ConsoleMonster.Extensions.NLog;
using NLog;
using NLog.Config;

var configuration = new LoggingConfiguration();
var target = new ConsoleMonsterTarget { Name = "consolemonster" };
configuration.AddRule(LogLevel.Trace, LogLevel.Fatal, target);

using var factory = new LogFactory { Configuration = configuration };
var log = factory.GetLogger("Shop.Orders");
log.Info("Order {OrderId} for {Customer}", 1042, "Ada");

For XML configuration, register <add assembly="ConsoleMonster.Extensions.NLog" /> inside <extensions>, then use a target with xsi:type="ConsoleMonster". NLog's usual name and rules select the target.

What the native adapters write

The category is the last part of Serilog's SourceContext or NLog's logger name (Orders here). String values in the template print without quotes; numbers and dates are highlighted. Unused properties follow as muted key=value fields, and Serilog structures use compact JSON. Other sinks and targets retain the native structured events.

Both adapters accept TimestampFormat (HH:mm:ss), UseUtcTimestamp (false), IncludeCategory (true), MaxExceptionLines (12), LogRegion ($log), and optional Profile and Writer overrides. Set TimestampFormat to null to omit timestamps, or LogRegion to null to always print. NLog also accepts empty strings for these two settings, including timestampFormat="" and logRegion="" in XML. Exceptions use ExceptionView. During a live session, entries print above the view unless the configured log region exists, in which case they post there. Redirected output stays plain and append-only.

Next

Edit this page on GitHub