Open.Logging.Extensions.SpectreConsole 2.0.2

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

Open.Logging.Extensions.SpectreConsole

A lightweight integration between Microsoft's logging infrastructure and Spectre.Console for enhanced console logging.

NuGet

Overview

This library bridges the gap between the standard Microsoft.Extensions.Logging framework and Spectre.Console's rich styling capabilities, making it easy to use Spectre.Console as a logging target in your .NET applications. It provides multiple formatter options to display your logs in various styles, from simple one-line outputs to structured multi-line formats.

Installation

dotnet add package Open.Logging.Extensions.SpectreConsole

Basic Usage

Add the Spectre Console logger to your dependency injection container:

using Microsoft.Extensions.Logging;
using Open.Logging.Extensions.SpectreConsole;

// In your Startup.cs or Program.cs
services.AddLogging(builder =>
{
    builder.AddSpectreConsole<SimpleSpectreConsoleFormatter>();
});

Inject and Use

Use the logger as you would any standard ILogger:

public class WeatherService
{
    private readonly ILogger<WeatherService> _logger;
    
    public WeatherService(ILogger<WeatherService> logger)
    {
        _logger = logger;
    }
    
    public void GetForecastAsync()
    {
        using (_logger.BeginScope("Location: {Location}", "Seattle"))
        {
            _logger.LogInformation("Retrieving weather forecast");
            
            try
            {
                // Your code here
                _logger.LogDebug("API request details: {Url}", "api/weather?city=Seattle");
                
                // Success case
                _logger.LogInformation("Forecast: {Temperature}°C", 22.5);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to retrieve forecast");
            }
        }
    }
}

Customization

Available Formatters

The library comes with several pre-built formatters that provide different styles of log output:

  • SimpleSpectreConsoleFormatter: A compact single-line formatter (default)
  • MicrosoftStyleSpectreConsoleFormatter: Multi-line format similar to Microsoft's default console logger
  • CompactSpectreConsoleFormatter: Space-efficient format with icons for log levels
  • CallStackSpectreConsoleFormatter: Structured format with visual frame indicators
  • StructuredMultilineFormatter: Grid-based format with clear labeling

Usage example:

// Choose any of the pre-built formatters
services.AddLogging(builder =>
{
    builder.AddSpectreConsole<MicrosoftStyleSpectreConsoleFormatter>();
});

Creating Your Own Formatter

You can easily create your own custom formatter by implementing the ISpectreConsoleFormatter<T> interface:

public sealed class MyCustomFormatter(
    SpectreConsoleLogTheme? theme = null,
    LogLevelLabels? labels = null,
    bool newLine = false,
    IAnsiConsole? writer = null)
    : SpectreConsoleFormatterBase(theme, labels, newLine, writer)
    , ISpectreConsoleFormatter<MyCustomFormatter>
{
    public static MyCustomFormatter Create(
        SpectreConsoleLogTheme? theme = null,
        LogLevelLabels? labels = null,
        bool newLine = false,
        IAnsiConsole? writer = null)
        => new(theme, labels, newLine, writer);
        
    public override void Write(PreparedLogEntry entry)
    {
        // Your custom formatting logic here
        Writer.WriteLine($"[{entry.Level}] {entry.Message}");
        
        // Handle exceptions
        if (entry.Exception is not null)
        {
            Writer.WriteException(entry.Exception);
        }
    }
}

After creating your formatter, register it with the DI container:

services.AddLogging(builder =>
{
    builder.AddSpectreConsole<MyCustomFormatter>();
});

Interactive Demo

To explore the various formatters with different themes, run the demo:

cd Open.Logging.Extensions.Demo
dotnet run

This will launch an interactive console application that allows you to select different formatters and themes to see how they look with sample log entries. It's a great way to experiment with different combinations before implementing them in your application.

Built-in Themes

The library comes with several pre-configured themes inspired by popular coding editors that you can use immediately:

// In your Startup.cs or Program.cs
services.AddLogging(builder =>
{
    builder.AddSpectreConsole<SimpleSpectreConsoleFormatter>(options =>
    {
        // Choose one of the built-in themes:
        options.Theme = SpectreConsoleLogTheme.TweakedDefaults;
    });
});

Available themes:

  • Default: Uses standard console colors for compatibility with all terminal types
  • ModernColors: Vibrant colors for modern terminals with rich color support
  • TweakedDefaults: Enhanced default theme with improved contrast and readability
  • LightBackground: Colors optimized for light background terminals
  • Dracula: Inspired by the popular Dracula code editor theme
  • Monokai: Inspired by the Monokai code editor theme
  • SolarizedDark: Inspired by the Solarized Dark theme
  • OneDark: Inspired by VS Code's One Dark Pro theme

Custom Theme

If you prefer, you can create your own theme by customizing colors and formatting:

var customTheme = new SpectreConsoleLogTheme
{
    // Styles for log levels
    Trace = new Style(Color.Silver, decoration: Decoration.Dim),
    Debug = new Style(Color.Blue, decoration: Decoration.Dim),
    Information = Color.Green,
    Warning = new Style(Color.Yellow, decoration: Decoration.Bold),
    Error = new Style(Color.Red, decoration: Decoration.Bold),
    Critical = new Style(Color.White, Color.Red, Decoration.Bold),
    
    // Styles for components
    Timestamp = new Style(Color.Grey, decoration: Decoration.Dim),
    Category = new Style(Color.Grey, decoration: Decoration.Italic),
    Scopes = new Style(Color.Blue, decoration: Decoration.Dim),
    Message = Color.Silver,
    Exception = Color.Red
};

// Apply the custom theme
services.AddLogging(builder =>
{
    builder.AddSpectreConsole<SimpleSpectreConsoleFormatter>(options =>
    {
        options.Theme = customTheme;
    });
});

Log Level Labels

You can also customize the text displayed for different log levels:

var customLabels = new LogLevelLabels
{
    Trace = "TRACE",
    Debug = "DEBUG",
    Information = "INFO",
    Warning = "WARN",
    Error = "ERROR",
    Critical = "FATAL"
};

// Apply custom labels
services.AddLogging(builder =>
{
    builder.AddSpectreConsole<SimpleSpectreConsoleFormatter>(options =>
    {
        options.Labels = customLabels;
    });
});

Combined Configuration

You can combine theme and label customization in a single configuration:

services.AddLogging(builder =>
{
    builder.AddSpectreConsole<SimpleSpectreConsoleFormatter>(options =>
    {
        options.Theme = SpectreConsoleLogTheme.Dracula;
        options.Labels = new LogLevelLabels
        {
            Trace = "trace",
            Debug = "debug",
            Information = "info-",
            Warning = "warn!",
            Error = "ERROR",
            Critical = "FATAL"
        };
    });
});

Styling Reference

This integration leverages Spectre.Console's excellent styling system. You can use any style supported by Spectre.Console:

For a complete style reference, see the Spectre.Console documentation.

Requirements

  • .NET 9.0+
  • Microsoft.Extensions.Logging
  • Spectre.Console

License

MIT License - see the LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  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

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2.0.2 133 6/4/2025
2.0.1 126 6/4/2025
2.0.0 136 5/28/2025
1.0.1 147 5/21/2025
1.0.0 132 5/21/2025