Skip to main content

Latest release 20191004: @pfx_method: new optional use_str parameter to use str(self) instead of type(self).name; now requires @cs.deco.decorator

Dynamic message prefixes providing execution context.

The primary facility here is Pfx, a context manager which maintains a per thread stack of context prefixes.

Usage is like this:

from cs.pfx import Pfx
...
def parser(filename):
  with Pfx("parse(%r)", filename):
    with open(filename) as f:
      for lineno, line in enumerate(f, 1):
        with Pfx("%d", lineno) as P:
          if line_is_invalid(line):
            raise ValueError("problem!")
          P.info("line = %r", line)

This produces log messages like:

datafile: 1: line = 'foo\n'

and exception messages like:

datafile: 17: problem!

which lets one put just the relevant complaint in exception and log messages and get useful calling context on the output. This does make for wordier logs and exceptions but used with a little discretion produces far more debuggable results.

Function gen(func)

Decorator for generators to manage the Pfx stack.

Before running the generator the current stack height is noted. After yield, the stack above that height is trimmed and saved, and the value yielded. On recommencement the saved stack is reapplied to the current stack (which may have changed) and the generator continued.

Class Pfx

A context manager to maintain a per-thread stack of message prefixes.

Method Pfx.__init__(self, mark, *args, **kwargs)

Initialise a new Pfx instance.

Parameters:

  • mark: message prefix string
  • args: if not empty, apply to the prefix string with %
  • absolute: optional keyword argument, default False. If true, this message forms the base of the message prefixes; existing prefixes will be suppressed.
  • loggers: which loggers should receive log messages.

Note: the mark and args are only combined if the Pfx instance gets used, for example for logging or to annotate an exception. Otherwise, they are not combined. Therefore the values interpolated are as they are when the Pfx is used, not necessarily as they were when the Pfx was created. If args is subject to change and you require the original values, apply them to mark immediately, for example:

with Pfx('message %s ...' % (arg1, arg2, ...)):

This is a bit more expensive, and the common usage is:

with Pfx('message %s ...', arg1, arg2, ...):

Function pfx(func)

Decorator for functions that should run inside:

with Pfx(func_name):

Use:

@pfx
def f(...):

Function pfx_iter(tag, iterable)

Wrapper for iterables to prefix exceptions with tag.

Function pfx_method(*da, **dkw)

Decorator to provide a Pfx context for an instance method prefixing classname.methodname (or str(self).methodname if use_str is true).

Class PfxCallInfo

MRO: Pfx
Subclass of Pfx to insert current function an caller into messages.

Function pfxtag(tag, loggers=None)

Decorator for functions that should run inside:

with Pfx(tag, loggers=loggers):

Use:

@pfxtag(tag)
def f(...):

Function PfxThread(target=None, **kw)

Factory function returning a Thread which presents the current prefix as context.

Function prefix()

Return the current Pfx prefix.

Function PrePfx(tag, *args)

Push a temporary value for Pfx._state._ur_prefix to enloundenify messages.

Function XP(msg, *args, **kwargs)

Variation on cs.x.X which prefixes the message with the current Pfx prefix.

Function XX(prepfx, msg, *args, **kwargs)

Trite wrapper for XP() to transiently insert a leading prefix string.

Example:

XX("NOTE!", "some message")

Release Log

Release 20191004: @pfx_method: new optional use_str parameter to use str(self) instead of type(self).name; now requires @cs.deco.decorator

Release 20190905: Pfx.exit: simplify prefixify_exc() logic, prefixify all suitable attributes. New @pfx_method decorator for instance methods.

Release 20190607: Pfx.exit improved exception attribute handling.

Release 20190403: Debugging aid: Pfx.umark: emit stack traceback on format conversion error.

Release 20190327: @pfx: set name on the wrapper function. Bugfix some references to the internal prefixify function.

Release 20190324: Pfx.exit: apply the prefix to all the standard attributes where present, improves some message behaviour for some exception types.

Release 20181231: Bugfix for an infinite regress.

Release 20181109: Update @contextmanager formalism to use try/finally for the cleanup phase. New decorator @gen to manage Pfx state across generator iterations; pretty clunky. Better fallback handling. Some docstring updates.

Release 20170910: Slight linting.

Release 20170903.1: corrections to the module docstring

Release 20170903: Initial release for PyPI.

Release files for cs-pfx 20191004

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cs-pfx 20191004
File Size Uploaded
cs.pfx-20191004.tar.gz 8.0 kB Details

Release files / cs.pfx-20191004.tar.gz

Download URL cs.pfx-20191004.tar.gz
Size 8.0 kB
Tags Source
SHA-256 checksum
How to use checksums
49270da9576e5c92fb71a5665f45eae48c43b67cc258a8902b1246fb5ee9effb
BLAKE2b-256 checksum
How to use checksums
e6f26699ab8cecf599208a4b9506733184f97992a3e552a6caeb5edaef671f89
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/39.0.1 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.7.4
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page