or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

admin-jmx.mdansi-support.mdaot-native-image.mdapplication-info.mdavailability.mdbootstrap.mdbootstrapping.mdbuilder.mdcloud-platform.mdconfiguration-annotations.mdconfiguration-data.mdconfiguration-properties.mdconversion.mddiagnostics.mdenvironment-property-sources.mdindex.mdjson-support.mdlifecycle-events.mdlogging.mdorigin-tracking.mdresource-loading.mdretry-support.mdssl-tls.mdstartup-metrics.mdsupport.mdsystem-utilities.mdtask-execution.mdthreading.mdutilities.mdvalidation.mdweb-support.md
tile.json

ansi-support.mddocs/

ANSI Terminal Color and Styling Support

Package: org.springframework.boot.ansi

Provides ANSI escape code support for terminal color and styling output. Automatically detects terminal capabilities and conditionally outputs ANSI codes for colored console output in Spring Boot applications.

Overview

The ANSI support package enables colored and styled console output for Spring Boot applications. It includes:

  • Standard and bright color support (foreground and background)
  • Text styling (bold, italic, underline, etc.)
  • 8-bit color support (256 colors)
  • Automatic terminal capability detection
  • Manual enable/disable controls

Core Imports

import org.springframework.boot.ansi.*;

Capabilities

ANSI Element Interface

Base interface for all ANSI elements that can be encoded as escape sequences.

package org.springframework.boot.ansi;

/**
 * An ANSI encodable element.
 *
 * @since 1.0.0
 */
public interface AnsiElement {
    /**
     * @return the ANSI escape code
     */
    String toString();
}

ANSI Output

Main class for generating ANSI encoded output with automatic terminal detection.

package org.springframework.boot.ansi;

/**
 * Generates ANSI encoded output, automatically attempting to detect if the terminal
 * supports ANSI.
 *
 * @since 1.0.0
 */
public abstract class AnsiOutput {

    /**
     * Sets if ANSI output is enabled.
     * @param enabled if ANSI is enabled, disabled or detected
     */
    public static void setEnabled(Enabled enabled);

    /**
     * Returns if ANSI output is enabled
     * @return if ANSI enabled, disabled or detected
     */
    public static Enabled getEnabled();

    /**
     * Sets if the System.console() is known to be available.
     * @param consoleAvailable if the console is known to be available or null to
     * use standard detection logic.
     */
    public static void setConsoleAvailable(Boolean consoleAvailable);

    /**
     * Encode a single AnsiElement if output is enabled.
     * @param element the element to encode
     * @return the encoded element or an empty string
     */
    public static String encode(AnsiElement element);

    /**
     * Create a new ANSI string from the specified elements. Any AnsiElements will
     * be encoded as required.
     * @param elements the elements to encode
     * @return a string of the encoded elements
     */
    public static String toString(Object... elements);

    /**
     * Possible values to pass to setEnabled(). Determines when to output
     * ANSI escape sequences for coloring application output.
     */
    public enum Enabled {
        /**
         * Try to detect whether ANSI coloring capabilities are available. The default
         * value for AnsiOutput.
         */
        DETECT,

        /**
         * Enable ANSI-colored output.
         */
        ALWAYS,

        /**
         * Disable ANSI-colored output.
         */
        NEVER
    }
}

ANSI Colors

Standard ANSI foreground colors including both normal and bright variants.

package org.springframework.boot.ansi;

/**
 * ANSI foreground colors.
 *
 * @since 1.3.0
 */
public enum AnsiColor implements AnsiElement {
    DEFAULT,
    BLACK,
    RED,
    GREEN,
    YELLOW,
    BLUE,
    MAGENTA,
    CYAN,
    WHITE,
    BRIGHT_BLACK,
    BRIGHT_RED,
    BRIGHT_GREEN,
    BRIGHT_YELLOW,
    BRIGHT_BLUE,
    BRIGHT_MAGENTA,
    BRIGHT_CYAN,
    BRIGHT_WHITE
}

ANSI Background Colors

Standard ANSI background colors including both normal and bright variants.

package org.springframework.boot.ansi;

/**
 * ANSI background colors.
 *
 * @since 1.3.0
 */
public enum AnsiBackground implements AnsiElement {
    DEFAULT,
    BLACK,
    RED,
    GREEN,
    YELLOW,
    BLUE,
    MAGENTA,
    CYAN,
    WHITE,
    BRIGHT_BLACK,
    BRIGHT_RED,
    BRIGHT_GREEN,
    BRIGHT_YELLOW,
    BRIGHT_BLUE,
    BRIGHT_MAGENTA,
    BRIGHT_CYAN,
    BRIGHT_WHITE
}

ANSI Styles

Text styling options for ANSI output.

package org.springframework.boot.ansi;

/**
 * ANSI text styles.
 *
 * @since 1.3.0
 */
public enum AnsiStyle implements AnsiElement {
    NORMAL,
    BOLD,
    FAINT,
    ITALIC,
    UNDERLINE
}

8-Bit Color Support

Support for 256-color ANSI codes (8-bit color).

package org.springframework.boot.ansi;

/**
 * AnsiElement implementation for ANSI 8-bit foreground or background color codes.
 *
 * @since 2.2.0
 */
public final class Ansi8BitColor implements AnsiElement {

    /**
     * Return a foreground ANSI color code instance for the given code.
     * @param code the color code (must be 0-255)
     * @return an ANSI color code instance
     * @throws IllegalArgumentException if code is not between 0 and 255
     */
    public static Ansi8BitColor foreground(int code);

    /**
     * Return a background ANSI color code instance for the given code.
     * @param code the color code (must be 0-255)
     * @return an ANSI color code instance
     * @throws IllegalArgumentException if code is not between 0 and 255
     */
    public static Ansi8BitColor background(int code);
}

ANSI Property Source

PropertySource implementation that resolves ANSI element properties.

package org.springframework.boot.ansi;

import org.springframework.core.env.PropertySource;

/**
 * PropertySource for AnsiStyle, AnsiColor, AnsiBackground and Ansi8BitColor elements.
 * Supports properties of the form "AnsiStyle.BOLD", "AnsiColor.RED" or
 * "AnsiBackground.GREEN". Also supports a prefix of "Ansi." which is an aggregation
 * of everything (with background colors prefixed "BG_").
 *
 * ANSI 8-bit color codes can be used with AnsiColor and AnsiBackground.
 * For example, "AnsiColor.208" will render orange text.
 *
 * @since 1.3.0
 */
public class AnsiPropertySource extends PropertySource<AnsiElement> {

    /**
     * Create a new AnsiPropertySource instance.
     * @param name the name of the property source
     * @param encode if the output should be encoded
     */
    public AnsiPropertySource(String name, boolean encode);

    /**
     * Get an ANSI property by name.
     * Supported prefixes:
     * - "AnsiStyle." (e.g., "AnsiStyle.BOLD")
     * - "AnsiColor." (e.g., "AnsiColor.RED" or "AnsiColor.208")
     * - "AnsiBackground." (e.g., "AnsiBackground.GREEN" or "AnsiBackground.27")
     * - "Ansi." (aggregation prefix, e.g., "Ansi.BOLD", "Ansi.RED", "Ansi.BG_GREEN")
     * @param name the property name
     * @return the AnsiElement or encoded string, or null if not found
     */
    @Override
    public Object getProperty(String name);
}

Usage Examples

Basic Colored Output

import org.springframework.boot.ansi.*;

public class ColoredLogging {

    public void logWithColor() {
        // Simple colored output
        String message = AnsiOutput.toString(
            AnsiColor.GREEN, "SUCCESS: ", AnsiColor.DEFAULT, "Operation completed"
        );
        System.out.println(message);

        // Error message in red
        String error = AnsiOutput.toString(
            AnsiColor.RED, "ERROR: ", AnsiColor.DEFAULT, "Operation failed"
        );
        System.err.println(error);

        // Warning with background color
        String warning = AnsiOutput.toString(
            AnsiBackground.YELLOW, AnsiColor.BLACK, " WARNING ",
            AnsiBackground.DEFAULT, AnsiColor.DEFAULT, " Check configuration"
        );
        System.out.println(warning);
    }
}

Styled Text Output

import org.springframework.boot.ansi.*;

public class StyledOutput {

    public void demonstrateStyles() {
        // Bold text
        System.out.println(AnsiOutput.toString(
            AnsiStyle.BOLD, "Important Message", AnsiStyle.NORMAL
        ));

        // Italic text
        System.out.println(AnsiOutput.toString(
            AnsiStyle.ITALIC, "Emphasized text", AnsiStyle.NORMAL
        ));

        // Underlined text
        System.out.println(AnsiOutput.toString(
            AnsiStyle.UNDERLINE, "Underlined text", AnsiStyle.NORMAL
        ));

        // Combined: bold red text
        System.out.println(AnsiOutput.toString(
            AnsiStyle.BOLD, AnsiColor.RED, "Critical Alert",
            AnsiStyle.NORMAL, AnsiColor.DEFAULT
        ));
    }
}

8-Bit Color Support

import org.springframework.boot.ansi.*;

public class ExtendedColors {

    public void use8BitColors() {
        // Use 256-color palette (0-255)

        // Foreground color code 208 (orange)
        String orange = AnsiOutput.toString(
            Ansi8BitColor.foreground(208), "Orange text", AnsiColor.DEFAULT
        );
        System.out.println(orange);

        // Background color code 27 (deep blue)
        String highlighted = AnsiOutput.toString(
            Ansi8BitColor.background(27), "Highlighted text", AnsiBackground.DEFAULT
        );
        System.out.println(highlighted);

        // Combining foreground and background
        String colorful = AnsiOutput.toString(
            Ansi8BitColor.foreground(226), // Yellow
            Ansi8BitColor.background(21),  // Blue
            " Colorful Text ",
            AnsiColor.DEFAULT,
            AnsiBackground.DEFAULT
        );
        System.out.println(colorful);
    }
}

Controlling ANSI Output

import org.springframework.boot.ansi.*;

@Configuration
public class AnsiConfiguration {

    @PostConstruct
    public void configureAnsi() {
        // Force enable ANSI output (even if not detected)
        AnsiOutput.setEnabled(AnsiOutput.Enabled.ALWAYS);

        // Or disable completely
        AnsiOutput.setEnabled(AnsiOutput.Enabled.NEVER);

        // Or use automatic detection (default)
        AnsiOutput.setEnabled(AnsiOutput.Enabled.DETECT);

        // Check current setting
        AnsiOutput.Enabled current = AnsiOutput.getEnabled();
        System.out.println("ANSI output: " + current);
    }

    @Bean
    @Profile("production")
    public CommandLineRunner disableAnsiInProduction() {
        return args -> {
            // Disable colors in production logs
            AnsiOutput.setEnabled(AnsiOutput.Enabled.NEVER);
        };
    }
}

Custom Banner with Colors

import org.springframework.boot.Banner;
import org.springframework.boot.ansi.*;
import org.springframework.core.env.Environment;

public class ColoredBanner implements Banner {

    @Override
    public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) {
        out.println(AnsiOutput.toString(
            AnsiColor.GREEN, AnsiStyle.BOLD,
            " ███████╗██████╗ ██████╗ ██╗███╗   ██╗ ██████╗ ",
            AnsiStyle.NORMAL, AnsiColor.DEFAULT
        ));
        out.println(AnsiOutput.toString(
            AnsiColor.GREEN,
            " ██╔════╝██╔══██╗██╔══██╗██║████╗  ██║██╔════╝ ",
            AnsiColor.DEFAULT
        ));
        out.println(AnsiOutput.toString(
            AnsiColor.BRIGHT_GREEN,
            " ███████╗██████╔╝██████╔╝██║██╔██╗ ██║██║  ███╗",
            AnsiColor.DEFAULT
        ));
        out.println(AnsiOutput.toString(
            AnsiColor.CYAN,
            " ╚════██║██╔═══╝ ██╔══██╗██║██║╚██╗██║██║   ██║",
            AnsiColor.DEFAULT
        ));
        out.println(AnsiOutput.toString(
            AnsiColor.BRIGHT_CYAN,
            " ███████║██║     ██║  ██║██║██║ ╚████║╚██████╔╝",
            AnsiColor.DEFAULT
        ));
        out.println(AnsiOutput.toString(
            AnsiColor.BLUE,
            " ╚══════╝╚═╝     ╚═╝  ╚═╝╚═╝╚═╝  ╚═══╝ ╚═════╝ ",
            AnsiColor.DEFAULT
        ));

        String version = environment.getProperty("spring.application.version", "unknown");
        out.println(AnsiOutput.toString(
            AnsiStyle.FAINT, " Version: ", version, AnsiStyle.NORMAL
        ));
    }
}

Property-Based ANSI Configuration

import org.springframework.boot.ansi.*;

// In application.properties or application.yml:
// spring.output.ansi.enabled=always
// spring.output.ansi.enabled=detect
// spring.output.ansi.enabled=never

@Component
public class AnsiPropertyConfiguration {

    public AnsiPropertyConfiguration(Environment environment) {
        String ansiProperty = environment.getProperty("spring.output.ansi.enabled", "detect");

        switch (ansiProperty.toLowerCase()) {
            case "always":
                AnsiOutput.setEnabled(AnsiOutput.Enabled.ALWAYS);
                break;
            case "never":
                AnsiOutput.setEnabled(AnsiOutput.Enabled.NEVER);
                break;
            case "detect":
            default:
                AnsiOutput.setEnabled(AnsiOutput.Enabled.DETECT);
                break;
        }
    }
}

Terminal Detection

AnsiOutput automatically detects terminal capabilities:

  1. Detection Process:

    • Checks if System.console() is available
    • On Java 22+, checks if console is a terminal using Console.isTerminal()
    • Disables ANSI on Windows by default
    • Can be overridden with setEnabled(Enabled.ALWAYS)
  2. Detection Modes:

    • DETECT (default): Automatic terminal capability detection
    • ALWAYS: Force enable ANSI output regardless of terminal
    • NEVER: Force disable ANSI output
  3. Manual Override:

    // Override console detection
    AnsiOutput.setConsoleAvailable(true);  // Force console available
    AnsiOutput.setConsoleAvailable(false); // Force console unavailable
    AnsiOutput.setConsoleAvailable(null);  // Use automatic detection

Color Reference

Standard Colors (16 colors)

ColorForegroundBackground
BlackAnsiColor.BLACKAnsiBackground.BLACK
RedAnsiColor.REDAnsiBackground.RED
GreenAnsiColor.GREENAnsiBackground.GREEN
YellowAnsiColor.YELLOWAnsiBackground.YELLOW
BlueAnsiColor.BLUEAnsiBackground.BLUE
MagentaAnsiColor.MAGENTAAnsiBackground.MAGENTA
CyanAnsiColor.CYANAnsiBackground.CYAN
WhiteAnsiColor.WHITEAnsiBackground.WHITE

Bright Colors (8 colors)

ColorForegroundBackground
Bright BlackAnsiColor.BRIGHT_BLACKAnsiBackground.BRIGHT_BLACK
Bright RedAnsiColor.BRIGHT_REDAnsiBackground.BRIGHT_RED
Bright GreenAnsiColor.BRIGHT_GREENAnsiBackground.BRIGHT_GREEN
Bright YellowAnsiColor.BRIGHT_YELLOWAnsiBackground.BRIGHT_YELLOW
Bright BlueAnsiColor.BRIGHT_BLUEAnsiBackground.BRIGHT_BLUE
Bright MagentaAnsiColor.BRIGHT_MAGENTAAnsiBackground.BRIGHT_MAGENTA
Bright CyanAnsiColor.BRIGHT_CYANAnsiBackground.BRIGHT_CYAN
Bright WhiteAnsiColor.BRIGHT_WHITEAnsiBackground.BRIGHT_WHITE

Extended 8-Bit Colors (256 colors)

Use Ansi8BitColor.foreground(code) or Ansi8BitColor.background(code) with codes 0-255:

  • 0-15: Standard and bright colors
  • 16-231: 6×6×6 RGB color cube
  • 232-255: Grayscale colors

Thread Safety

  • AnsiOutput uses static state and is thread-safe for configuration methods
  • Encoding methods (encode(), toString()) are stateless and thread-safe
  • Enum types (AnsiColor, AnsiBackground, AnsiStyle) are immutable and thread-safe

Common Pitfalls

ANSI Codes in Log Files

Problem: ANSI escape codes appear as gibberish in log files

Solution: Disable ANSI when logging to files:

if (loggingToFile) {
    AnsiOutput.setEnabled(AnsiOutput.Enabled.NEVER);
}

Or configure conditionally based on environment:

# application.properties
spring.output.ansi.enabled=detect  # Development
# application-prod.properties
spring.output.ansi.enabled=never   # Production (file logging)

Windows Console Support

Problem: ANSI colors not working on Windows

Solution:

  • Use Windows Terminal or ConEmu (built-in ANSI support)
  • Enable ANSI on Windows 10+ console
  • Or force enable: AnsiOutput.setEnabled(Enabled.ALWAYS)

IDE Console Compatibility

Problem: Colors not showing in IDE console

Solution: Most modern IDEs support ANSI:

  • IntelliJ IDEA: Enabled by default
  • Eclipse: Install ANSI Console plugin
  • VS Code: Built-in support
  • Force enable if needed: AnsiOutput.setEnabled(Enabled.ALWAYS)