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.
We can convert a datetime object into a timestamp using the timestamp() method. If the datetime object is UTC aware, then this method will create a UTC timestamp. If the object is naive, we can assign the UTC value to the tzinfo parameter of the datetime object and then call the timestamp() method.
Timestamp is the pandas equivalent of python's Datetime and is interchangeable with it in most cases. It's the type used for the entries that make up a DatetimeIndex, and other timeseries oriented data structures in pandas. Parameters: ts_input : datetime-like, str, int, float. Value to be converted to Timestamp.
The print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen.
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]
An alternative solution that the timestamp is the beginning (prepended) instead of end (appended):
from datetime import datetime as dt
old_out = sys.stdout
class StAmpedOut:
"""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 = StAmpedOut()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With