CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-hues

Colored terminal text made easy for Python and happiness.

Pending
Overview
Eval results
Files

console-logging.mddocs/

Console Logging

Configurable console output system with colored labels, timestamps, and themed formatting. Supports both simple and powerline display themes with extensive customization through YAML configuration.

Capabilities

Main Logging Functions

Core logging functions available at the package level, providing convenient access to themed console output.

def log(*args, **kwargs):
    """
    General logging function with optional labels and timestamps.
    
    Args:
        *args: Content to log
        **kwargs: Options including time, info, warn, error, success flags
    """

def info(*args):
    """
    Info-level logging with INFO label.
    
    Args:
        *args: Content to log
    """

def warn(*args):
    """
    Warning-level logging with WARNING label.
    
    Args:
        *args: Content to log
    """

def error(*args):
    """
    Error-level logging with ERROR label.
    
    Args:
        *args: Content to log
    """

def success(*args):
    """
    Success-level logging with SUCCESS label.
    
    Args:
        *args: Content to log
    """

Console Objects

Direct access to console instances for advanced usage and custom formatting.

console: SimpleConsole | PowerlineConsole
"""
Global console instance (type depends on theme configuration).
Can be called directly: console('message')
"""

Configuration Management

Configuration system for customizing colors, labels, and console behavior.

class Config:
    """
    Configuration management class for hues settings.
    
    Args:
        force_default (bool): Use only default config, ignore user configs
    """
    def __init__(self, force_default: bool = False): ...
    
    @staticmethod
    def load_config(force_default: bool = False) -> dict:
        """
        Load configuration from .hues.yml files.
        
        Args:
            force_default (bool): Use only package defaults
            
        Returns:
            dict: Merged configuration
        """
    
    def resolve_config(self) -> None:
        """Resolve configuration to namedtuples."""
    
    # Configuration properties
    hues: object  # Color mappings namedtuple
    opts: object  # Options namedtuple
    labels: object  # Labels namedtuple

Console Classes

Direct console classes for custom implementations. These are imported internally but can be accessed directly if needed.

class SimpleConsole:
    """
    Basic console with colored labels and separators.
    
    Args:
        conf (Config, optional): Configuration object
        stdout: Output stream (default: sys.stdout)
    """
    def __init__(self, conf: Config = None, stdout = None): ...
    
    def log(self, *args, **kwargs): ...
    def info(self, *args): ...
    def warn(self, *args): ...
    def error(self, *args): ...
    def success(self, *args): ...
    def __call__(self, *args): ...

class PowerlineConsole(SimpleConsole):
    """
    Enhanced console with powerline-style connected segments.
    
    Args:
        conf (Config, optional): Configuration object
        stdout: Output stream (default: sys.stdout)
    """
    def __init__(self, conf: Config = None, stdout = None): ...
    # Inherits all methods from SimpleConsole

Exception Classes

class InvalidConfiguration(Exception):
    """Raised when configuration file is invalid."""

Usage Examples

Basic Logging

import hues

# Simple logging with labels
hues.info('Application started')
hues.warn('Low memory warning')
hues.error('Connection failed')
hues.success('Task completed')

# General logging with custom options
hues.log('Custom message', time=True, info=True)

Advanced Logging

# Direct console usage
hues.console('Plain message')
hues.console(('Colored', hues.console.conf.hues.success), 'and plain text')

# Multiple content with colors
hues.console(
    ('Step 1', hues.console.conf.hues.info),
    ('Completed', hues.console.conf.hues.success)
)

Custom Console

from hues.console import Config, SimpleConsole, PowerlineConsole

# Custom configuration
config = Config(force_default=True)

# Custom console instance
console = SimpleConsole(conf=config)
console.info('Custom console message')

# Powerline console
powerline = PowerlineConsole(conf=config)
powerline.success('Powerline style message')

Configuration System

Configuration Loading Order

  1. Package defaults (hues/.hues.yml)
  2. User home directory (~/.hues.yml)
  3. Current working directory (.hues.yml, searched recursively up to root)

Later configurations override earlier ones using deep dictionary merging.

Configuration Structure

hues:
  default: defaultfg      # Default text color
  time: magenta          # Timestamp color
  label: blue            # General label color
  info: cyan             # Info label color
  success: green         # Success label color
  error: red             # Error label color
  warn: yellow           # Warning label color

labels:
  info: INFO             # Info label text
  warn: WARNING          # Warning label text
  error: ERROR           # Error label text
  success: SUCCESS       # Success label text

options:
  show_time: yes         # Show timestamps by default
  time_format: '%H:%M:%S'  # Timestamp format
  add_newline: yes       # Add newline after each message
  theme: simple          # Console theme: 'simple' or 'powerline'

Theme Differences

Simple Theme: Basic colored labels with dash separators

[12:34:56] INFO - Application started
[12:34:56] WARNING - Low disk space

Powerline Theme: Connected segments with background colors and arrows

12:34:56  INFO Application started
 12:34:56  WARNING Low disk space

Log Message Formatting

Content Processing

  • Multiple arguments are joined with spaces
  • Tuples of (content, color) are rendered with specified colors
  • Colors are resolved from configuration or direct color codes
  • Time stamps are automatically formatted and colored

Label Behavior

  • Labels are added based on method called (info, warn, error, success)
  • log() method can add labels via keyword arguments
  • Each label has configurable text and color from configuration
  • Labels are separated from content with dashes (simple) or styling (powerline)

Advanced Usage

Configuration File Resolution

The configuration loading process follows a specific hierarchy with deep merging:

from hues.console import Config

# Force use of defaults only (ignore user configs)
config = Config(force_default=True)

# Load with full hierarchy (default behavior)
config = Config()

# Access resolved configuration
print(config.hues.info)    # Color code for info messages
print(config.labels.info)  # Label text for info messages
print(config.opts.theme)   # Active theme name

Custom Output Streams

Console classes support custom output streams for testing or redirection:

import io
from hues.console import SimpleConsole, Config

# Redirect to string buffer
buffer = io.StringIO()
console = SimpleConsole(stdout=buffer)
console.info('Test message')

# Get output
output = buffer.getvalue()
print(repr(output))  # Includes ANSI codes

Raw Logging Interface

Direct access to internal logging methods for custom formatting:

from hues import console
from hues.huestr import HueString

# Build custom colored components
time_component = HueString('12:34:56', hue_stack=(console.conf.hues.time,))
label_component = HueString('CUSTOM', hue_stack=(console.conf.hues.success,))
content_component = HueString('Message text', hue_stack=(console.conf.hues.default,))

# Use raw logging
console._raw_log(time_component, label_component, content_component)

Exception Handling

Configuration errors are handled with specific exceptions:

from hues.console import Config, InvalidConfiguration

try:
    config = Config()
except InvalidConfiguration as e:
    print(f"Config error: {e}")
    # Falls back to default configuration

Common causes of InvalidConfiguration:

  • Malformed YAML syntax in .hues.yml files
  • Configuration root is not a dictionary
  • Invalid color names in hues section

Powerline Theme Implementation

The PowerlineConsole uses background colors and Unicode arrows for connected segments:

  • Text is rendered with background colors matching the segment color
  • Foreground color is automatically chosen (black/white) based on background brightness
  • Arrow characters (►) connect segments using foreground colors
  • Final segment ends without an arrow

Internal Configuration Structure

After loading, configuration is converted to namedtuples for efficient access:

# Configuration structure after resolve_config()
config.hues     # Namedtuple with color codes (not names)
config.labels   # Namedtuple with label text strings  
config.opts     # Namedtuple with boolean/string options

This allows dot notation access while preventing accidental modification of the configuration during runtime.

Install with Tessl CLI

npx tessl i tessl/pypi-hues

docs

color-constants.md

console-logging.md

index.md

optimization.md

string-coloring.md

tile.json