问题
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.
回答1:
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]
回答2:
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()
回答3:
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:
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()
来源:https://stackoverflow.com/questions/4883789/adding-a-datetime-stamp-to-python-print