Skip to content

Colored Terminal Output

RAprogramm edited this page Oct 20, 2025 · 1 revision

Colored Terminal Output

Professional CLI error visibility with automatic TTY detection

The colored feature enhances error output in terminal applications with intelligent color coding that respects user preferences and terminal capabilities.

Table of Contents

Overview

Colored terminal output makes errors immediately recognizable and easier to debug:

  • Critical errors (5xx) appear in red for immediate attention
  • Client errors (4xx) appear in yellow for user-facing issues
  • Error codes in cyan for easy reference lookup
  • Messages in bright white for emphasis
  • Source chains dimmed as secondary context
  • Metadata keys in green for structured data

Benefits

  1. Faster debugging - Visual hierarchy helps identify critical issues instantly
  2. Better UX - Professional appearance in CLI tools
  3. Smart defaults - Respects user environment (NO_COLOR, TERM=dumb, piped output)
  4. Zero overhead - No performance impact when disabled
  5. Wide compatibility - Works on Linux, macOS, Windows 10+

Quick Start

Installation

Add the feature to your Cargo.toml:

[dependencies]
masterror = { version = "0.24", features = ["colored"] }

Basic Usage

Colors are applied automatically to Display output:

use masterror::AppError;

fn main() {
    let err = AppError::internal("Database connection failed");

    // When stderr is a TTY, this will show colored output
    eprintln!("{}", err);
}

Output (when TTY detected):

Error: Internal server error    ← Red (5xx)
Code: INTERNAL                   ← Cyan
Message: Database connection failed  ← Bright white

With Error Context

use std::io::Error as IoError;
use masterror::AppError;

let root = IoError::other("Connection timeout");
let err = AppError::network("Failed to fetch data")
    .with_context(root);

eprintln!("{}", err);

Output:

Error: Network error             ← Red (5xx)
Code: NETWORK                    ← Cyan
Message: Failed to fetch data    ← Bright white

  Caused by: Connection timeout  ← Dimmed

With Structured Metadata

use masterror::{AppError, field};

let err = AppError::database_with_message("Query failed")
    .with_field(field::str("query", "SELECT * FROM users"))
    .with_field(field::u64("duration_ms", 5432));

eprintln!("{}", err);

Output:

Error: Database error            ← Red (5xx)
Code: DATABASE                   ← Cyan
Message: Query failed            ← Bright white

Context:
  query: SELECT * FROM users     ← Green key, white value
  duration_ms: 5432              ← Green key, white value

Color Scheme

Error Severity

HTTP Status Color Rationale
5xx (500-599) Red Critical server errors requiring immediate attention
4xx (400-499) Yellow Client errors, often recoverable

Error Components

Component Color Purpose
Error code Cyan Easy to scan and reference in docs
Message Bright white Primary information, maximum visibility
Source chain Dimmed Important but secondary context
Metadata keys Green Distinguishes structured field names

See Color Scheme Reference for complete details.

Automatic Detection

Colors are automatically disabled when:

  1. Output is piped: cargo run | less
  2. NO_COLOR environment variable is set: NO_COLOR=1 cargo run
  3. TERM=dumb: Common in CI environments
  4. Terminal doesn't support ANSI colors

See Terminal Detection Guide for technical details.

Zero-Cost Abstraction

When the colored feature is disabled, the code compiles to the minimal non-colored version with:

  • No runtime overhead - No conditional checks
  • No binary size increase - owo-colors dependency excluded
  • Same API - Code remains compatible
[dependencies]
# Without colored feature - zero overhead
masterror = "0.24"

The Display implementation automatically switches between colored and non-colored variants at compile time using #[cfg(feature = "colored")].

Related Pages

Examples

Run the comprehensive demo:

# With colors (interactive terminal)
cargo run --example colored_cli --features colored

# Without colors (piped output)
cargo run --example colored_cli --features colored | cat

# Disable via environment
NO_COLOR=1 cargo run --example colored_cli --features colored

Platform Support

Platform Support Notes
Linux ✅ Full ANSI color support via terminal emulators
macOS ✅ Full Native Terminal.app and iTerm2 support
Windows 10+ ✅ Full Native ANSI support in Windows Terminal
Windows 7/8 ⚠️ Limited Falls back to monochrome automatically
SSH/Docker ✅ Full TTY detection works correctly
CI/CD ✅ Auto-disabled Respects NO_COLOR and TERM=dumb

Performance

  • TTY detection: Cached per-process, < 1μs overhead
  • Color application: Only when terminal supports colors
  • Memory: No heap allocations for non-colored output
  • Binary size: +~50KB when feature enabled (owo-colors dependency)

Next: Learn about Terminal Detection Guide

Clone this wiki locally