gouge.colourcli

Colourful, human-readable log output for the console.

class gouge.colourcli.Simple(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None, show_exc=False, show_threads=False, force_styling=False, show_pid=False, pre_formatters=None, highlighted_path=None, show_extra=False)

Bases: Formatter

Console formatter which colours the level, logger name and traceback of each record with ANSI escape codes.

Each line holds the time, the level name, the logger name in brackets and the message, optionally preceded by the process ID and thread name and followed by extra attributes.

Parameters:
fmt=None

Passed on to logging.Formatter.

datefmt=None

Passed on to logging.Formatter.

style='%'

Passed on to logging.Formatter.

validate=True

Passed on to logging.Formatter.

defaults=None

Passed on to logging.Formatter.

show_exc=False

Whether to append tracebacks to the message.

show_threads=False

Whether to prefix each line with the thread name.

force_styling=False

Emit colour codes even if NO_COLOR is set (see below).

show_pid=False

Whether to prefix each line with the process ID.

pre_formatters=None

Functions which rewrite the message of records of a given logger, as a mapping of logger name to a sequence of functions. A single function (or path) instead of a sequence is treated as a one-element sequence. Each item is either a callable taking and returning a str, or a dotted path to one, such as "gouge.preformatters.uvicorn_access". Paths are imported once when the formatter is created, which makes this option usable from logging.config.dictConfig() and YAML files. Paths are resolved with pkgutil.resolve_name(), so both "package.module.function" and "package.module:function" work. An invalid path raises ValueError naming it. The pre_formatters attribute always holds callables.

highlighted_path=None

Local filenames below this path are highlighted in tracebacks. An explicitly given path always wins. If it is not given, <cwd>/src is used as the default when that directory exists, otherwise nothing is highlighted.

show_extra=False

Which extra attributes of a record to append to the message, as dimmed key=value pairs. Extra attributes are those passed with extra={...} to a log call or set by a filter. False (the default) shows none. True shows every attribute which is not a standard logging.LogRecord attribute and does not start with _, sorted by name. A sequence of names shows only those, in that order, and skips names the record does not have (a single string is taken as one name). Values are rendered with str, or with repr() if that is empty or contains whitespace, so the pairs stay easy to parse. The OpenTelemetry IDs otelTraceID and otelSpanID are shown as trace_id and span_id when a span is active.

Example, showing a correlation ID which a filter put on the records:

>>> import logging
>>> from gouge.colourcli import Simple
>>> class CorrelationFilter(logging.Filter):
...     def filter(self, record):
...         record.correlation_id = "4bf92f35"
...         return True
>>> handler = logging.StreamHandler()
>>> handler.addFilter(CorrelationFilter())
>>> handler.setFormatter(Simple(show_extra=True))
>>> logging.getLogger().addHandler(handler)
>>> logging.getLogger("app").warning(
...     "Order created", extra={"order.id": 42}
... )
2026-10-27 13:34:48,899 WARNING    [app] Order created
correlation_id=4bf92f35 order.id=42

Colour. Whether colour codes are emitted is decided once, when the formatter is created (the environment is read at that point), in this order:

  1. force_styling is true: colour.

  2. Environment variable FORCE_COLOR set and not empty: colour.

  3. Environment variable NO_COLOR set and not empty (https://no-color.org): no colour. The output then contains no ANSI escape sequences at all, including those emitted by pre-formatters.

  4. Otherwise a directly created formatter emits colour codes, as it cannot know where its output goes. basicConfig() lets colorama strip them when the stream is not a terminal.

With logging.config.dictConfig(), use for example {"()": "gouge.colourcli.Simple", "pre_formatters": {"uvicorn.access": ["gouge.preformatters.uvicorn_access"]}}.

Note

This formatter suppresses tracebacks by default, to keep the output concise. Pass show_exc=True to show them. basicConfig() shows them by default.

static basicConfig(show_exc=True, show_threads=False, force_styling=False, show_pid=False, highlighted_path=None, *, show_extra=False, pre_formatters=None, **kwargs)

Configure logging with logging.basicConfig() and a Simple formatter, in one call.

show_exc, show_threads, show_pid, force_styling, show_extra and pre_formatters are directly passed to Simple. The remaining kwargs are passed on to logging.basicConfig().

If highlighted_path is set, it will highlight local filenames in tracebacks. This is useful if you want to highlight the current working directory. An explicitly given highlighted_path always wins. Only if it is not given and a “src” directory exists in the current working directory, that directory is used as the default.

After returning from logging.basicConfig(), it will fetch the stderr and stdout handlers and replace the formatter.

The function also returns a list of all handlers which have been modified. This is useful if you want to modify the handlers any further (for example using ShiftingFilter).

Colour follows the rules described in Simple: force_styling or FORCE_COLOR switch colorama’s stripping off, NO_COLOR makes it strip everything, and otherwise colorama strips the codes if the stream is not a terminal.

Return type:

list[Handler]

Returns:

The handlers whose formatter was replaced.

format(record)

Format record as one coloured line, followed by its traceback if show_exc is set.

Parameters:
record

The record to format.

Return type:

str

Returns:

The formatted text.

formatException(exc_info, exc_color='')

Format the exception in exc_info as traceback text.

Without exc_color the plain traceback is returned, exactly as logging.Formatter.formatException() does. Otherwise each line is wrapped in exc_color and file names below highlighted_path are shown in yellow.

Parameters:
exc_info

The exception tuple as returned by sys.exc_info().

exc_color=''

The ANSI escape sequence used for the traceback.

Return type:

str