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:
FormatterConsole 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_COLORis 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 fromlogging.config.dictConfig()and YAML files. Paths are resolved withpkgutil.resolve_name(), so both"package.module.function"and"package.module:function"work. An invalid path raisesValueErrornaming it. Thepre_formattersattribute 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>/srcis 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=valuepairs. Extra attributes are those passed withextra={...}to a log call or set by a filter.False(the default) shows none.Trueshows every attribute which is not a standardlogging.LogRecordattribute 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 withstr, or withrepr()if that is empty or contains whitespace, so the pairs stay easy to parse. The OpenTelemetry IDsotelTraceIDandotelSpanIDare shown astrace_idandspan_idwhen a span is active.
- fmt=
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=42Colour. Whether colour codes are emitted is decided once, when the formatter is created (the environment is read at that point), in this order:
force_styling is true: colour.
Environment variable
FORCE_COLORset and not empty: colour.Environment variable
NO_COLORset 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.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=Trueto 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 aSimpleformatter, 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 tologging.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 orFORCE_COLORswitch colorama’s stripping off,NO_COLORmakes it strip everything, and otherwise colorama strips the codes if the stream is not a terminal.
-
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.