15
votes

I am trying to debug the behaviour of a large library I depend on, which uses a scattering (no make that plethora) of debug print statements through its many source files. Trouble is, most if not all of these debug print statements do not contain a date/time stamp so it is hard to associate failures at the application level with failures within the library code itself.

Rather than modifying the source code for all the debug prints suspected to be involved in the failure I am seeing, I thought it may be possible to monkey patch the built-in Python print "function" temporarily, in order that all output is prefixed with a timestamp.

Since the built-in print is not a function in the Python 2.6 environment I am working with, I don't know if this is possible. If anyone has done this or achieved a similar result using another hook into Python then I would be grateful for your advice, or even better the code for a solution to this problem.

3
What's wrong with changing the scattered prints to proper logging requests? Why not just fix this library on which you depend? It would be (a) less of your time and (b) a permanent solution. Why not change the source? - S.Lott
From my point of view its simply a matter of the time required. Politically, the code base is "owned" by a number of different people and no standard for managing DEBUG output is evident. Not everyone may appreciate my proposal to adopt the logging module approach, however much of a good idea that may seem to me and you. - codeasone

3 Answers

25
votes

As you can’t override the write function (it's read-only) a simple monkey-patch could look like this (appending the timestamp to every printed line):

old_f = sys.stdout
class F:
    def write(self, x):
        old_f.write(x.replace("\n", " [%s]\n" % str(datetime.now())))
sys.stdout = F()

An example would the look like this:

>>> print "foo"
foo [2011-02-03 09:31:05.226899]
9
votes

Alternative solution that the time stamp is the begining (prepended) instead of end (appended):

old_out = sys.stdout


class St_ampe_dOut:
    """Stamped stdout."""

    nl = True

    def write(self, x):
        """Write function overloaded."""
        if x == '\n':
            old_out.write(x)
            self.nl = True
        elif self.nl:
            old_out.write('%s> %s' % (str(dt.now()), x))
            self.nl = False
        else:
            old_out.write(x)

sys.stdout = St_ampe_dOut()
0
votes

I'm not 100% clear how the existing answer from Velizar handles cases where the output is sent with multiple \n. I'm not sure if it works reliably, and if it does I think it may be relying on potentially undocumented behaviour of output streams.

Here's my solution that adds a timestamp to the start of every printed line, and handles multiple lines / lines without \n reliably:

import time
import sys

class TimestampFilter:
    # pending_output stores any output passed to write where a \n has not yet been found
    pending_output = ''
    def write(self, message):
        output = self.pending_output + message
        (output, not_used, self.pending_output) =  output.rpartition('\n')
        if output != '':
            timestamp = time.strftime("%Y-%m-%d %X")
            output = timestamp + " " + output.replace("\n", "\n"+timestamp+" ")
            print(output, file=sys.__stdout__)
            sys.__stdout__.flush()

sys.stdout = TimestampFilter()