Adding a datetime stamp to Python print

codeasone picture codeasone · Feb 3, 2011 · Viewed 10.8k times · Source

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.

Answer

rumpel picture rumpel · Feb 3, 2011

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]