开发者

Adding a datetime stamp to Python print

开发者 https://www.devze.com 2023-02-08 11:43 出处:网络
I am trying to debug the behaviour of a large libra开发者_运维技巧ry I depend on, which uses a scattering (no make that plethora) of debug print statements through its many source files. Trouble is, m

I am trying to debug the behaviour of a large libra开发者_运维技巧ry 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.


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()


To add datetime stamp to Python print you can override print.

First, keep the original print()

keep the original print()

Then, define your print function and use _print to print:

from datetime import datetime

def print(*args, **kw):
    _print("[%s]" % (datetime.now()),*args, **kw)

Now you will get something like:

>>> print("hi")
[2022-03-08 23:53:48.258767] hi

Note: This is for python3 but it is easy to change for python2


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()
0

精彩评论

暂无评论...
验证码 换一张
取 消