API reference

All supported imports below come from traceprint. Signatures and methods are generated from the installed package. The Usage guide explains common combinations and cleanup.

Tracer

class traceprint.Tracer(*, use_colors: bool | None = None, use_tabulation: bool = False, color_scheme: list[str] | None = None, metacolor: str | None = '\x1b[90m', print_transitions: bool = False, filter_levels: range | Iterable[int] | Callable[[int], bool] | None = None, start_enabled: bool = True, output_format: str = '[{timestamp}][{cumulative}][{elapsed}][{label_full}] {original_message}', timestamp_format: str = '%Y-%m-%d %H:%M:%S', stream: TextIO | None = None, error_stream: TextIO | None = None, intercept_stdout: bool = False, intercept_stderr: bool = False)

Format text output with timing, labels, nesting, and optional colors.

property enabled: bool

Return whether formatting is currently enabled.

install(*, stdout: bool = True, stderr: bool = False) → None

Install this tracer as sys.stdout and optionally sys.stderr.

uninstall() → None

Restore streams captured by install().

enable() → None

Enable formatted output and depth tracking.

disable() → None

Disable formatted output and forward text to the underlying stream.

lock() → None

Prevent further depth changes.

unlock() → None

Allow depth changes.

configure(**kwargs: Any) → None

Update tracer configuration after initialization.

add_file_handler(handler: TracerFileHandler) → None

Mirror formatted stream writes to a file handler.

remove_file_handler(handler: TracerFileHandler) → None

Stop mirroring formatted stream writes to a file handler.

format(message: str) → str

Format a single message without writing it.

write(data: str) → int

Write immediately, adding metadata once per nonblank output line.

flush() → None

Flush the underlying stream and attached file handlers.

push(label: str | None = None) → None

Increase depth and optionally record a label.

pop(label: str | None = None) → None

Decrease depth and remove the most recent label.

span(label: str) → Span

Create a context-managed labeled span.

Constructor options

  • stream: text sink; defaults to the current stdout at construction. An implicit sink is refreshed on installation. error_stream is accepted for compatibility but does not currently select a separate intercepted stderr sink.

  • intercept_stdout and intercept_stderr: install on construction when requested; both default to False. Call uninstall() for cleanup.

  • use_colors: TTY detection when None; otherwise an explicit boolean.

  • use_tabulation: four spaces per nesting level; defaults to False.

  • color_scheme: ANSI strings selected cyclically by depth. An empty list or None selects the default palette.

  • metacolor: metadata color; defaults to dark grey. None uses the depth color for the entire line.

  • print_transitions: show entry and exit messages; defaults to False.

  • filter_levels: allowed depths or a depth predicate; None allows all.

  • start_enabled: defaults to True; disabled output is forwarded raw.

  • output_format: Python format string; defaults to timestamp, cumulative time, elapsed time, full label and the original message.

  • timestamp_format: UTC strftime format, default %Y-%m-%d %H:%M:%S.

configure() accepts configuration attributes after construction and raises AttributeError for unknown names. depth and labels describe the shared current context; use spans or push/pop to manage them. write() returns the length of the input even when output is filtered. format() formats a message without writing, advances timing and does not change the current line state.

Global tracer

traceprint.tracer

Format text output with timing, labels, nesting, and optional colors.

The convenience instance is created at import without stream installation. It can be seeded by TRACEPRINT_INITIAL_LABELS; see Usage guide.

Function tracing

traceprint.trace(_func: Callable[[...], Any] | None = None, *, label: str | None = None, force: bool = False, tracer_instance: Tracer | None = None) → Callable[[...], Any]

Decorate a function so calls are reflected in tracer depth and labels.

Supports @trace and @trace(label="name", tracer_instance=target). The wrapped function’s result and exceptions pass through, and context is restored in finally. force is a transition-emission option; emitted writes still obey depth filtering. This decorator targets synchronous functions.

Logging handlers

class traceprint.TracerHandler(level: int = 0, *, tracer_instance: Tracer | None = None)

A logging handler that writes records through a tracer.

Initializes the instance - basically setting the formatter to None and the filter list to empty.

emit(record: LogRecord) → None

Do whatever it takes to actually log the specified logging record.

This version is intended to be implemented by subclasses and so raises a NotImplementedError.

An optional standard logging formatter prepares the record before tracer formatting. Omitting tracer_instance selects the global tracer.

class traceprint.TracerFileHandler(filename: str | PathLike[str], mode: str = 'a', level: int = 0, encoding: str = 'utf-8', *, tracer_instance: Tracer | None = None)

A logging handler that writes trace-formatted records to a file.

Initializes the instance - basically setting the formatter to None and the filter list to empty.

emit(record: LogRecord) → None

Do whatever it takes to actually log the specified logging record.

This version is intended to be implemented by subclasses and so raises a NotImplementedError.

write(data: str) → None

Write already-formatted tracer output directly to the file.

flush() → None

Ensure all logging output has been flushed.

This version does nothing and is intended to be implemented by subclasses.

close() → None

Close the file and release the standard logging handler.

The file opens on construction, creating parent directories. Default mode is append and encoding is UTF-8. Direct write() expects already formatted text; emit() adds tracer formatting. The sink strips terminal escapes. Remove the handler from its logger or tracer and close it when finished.

Logger mixin

class traceprint.LoggerMixin(*, verbose: bool = True, logging_level: int = 20, logging_passthrough: bool = False, lazy_init: bool = False)

Mixin that provides an instance logger exposed as self.log.

property logger: Logger

Return the shared class-named standard logger.

property log: _LoggerProxy

Return the logging proxy gated by this instance’s verbose flag.

verbose controls calls through self.log; accessing self.logger gives the underlying standard logger without that proxy gate. logging_level sets its level. lazy_init delays logger creation until access. logging_passthrough routes through the global tracer and replaces handlers on the shared class-named logger; defaults to False.

Color constants

traceprint.DARK_GREY

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.

traceprint.DEFAULT_COLORS

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

traceprint.RESET

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.

ANSI metadata color, cyclic depth palette and reset sequence, respectively.