[Python-Dev] Inject some tracing ...

Martin Blais blais at furius.ca
Sat Jun 10 04:42:48 CEST 2006


Hello

I use the code below to inject a tracing function in my builtins that
prints out the file and line number where it occurs, and automatically
nicely formats the objects it receives.  This allows me to get traces
like that in my web server log files, or in my cmdline program
outputs:

[Fri Jun 09 22:44:15 2006]  (TRACE training.cgi:194)  ...

This way I immediately know where to go to remove the debugging
traces, and I don't have to import anything to use them (they are in
the bulitins, no need to import sys; print >> sys.stderr, ...).

Would people think this would be a good idea to add this to the
builtins in the future?

(Implementation follows.)

=============================


#!/usr/bin/env python

"""
Inject some tracing builtins debugging purposes.
"""

__version__ = "$Revision: 1781 $"
__author__ = "Martin Blais <blais at furius.ca>"

import sys, inspect, pprint
from os.path import basename


def trace(*args, **kwds):
    """
    Log the object to the 'outfile' file (keyword argument).  We also insert the
    file and line where this tracing statement was inserted.
    """
    # Get the output stream.
    outfile = kwds.pop('outfile', sys.stderr)

    # Get the parent file and line number.
    try:
        frame, filename, lineno, func, lines, idx = inspect.stack()[1]
        pfx = '(TRACE %s:%d) ' % (basename(filename), lineno)
    finally:
        del frame

    # Nicely format the stuff to be traced.
    pp = pprint.PrettyPrinter(indent=4, width=70, depth=1)
    msg = pfx + pp.pformat(args) + '\n'

    # Output.
    outfile.write(msg)
    outfile.flush()


# Inject into builtins for debugging.
import __builtin__
__builtin__.__dict__['trace'] = trace
__builtin__.__dict__['pprint'] = pprint.pprint
__builtin__.__dict__['pformat'] = pprint.pformat


More information about the Python-Dev mailing list