向 Python 打印添加日期时间戳

发布于 2024-10-16 04:53:02 字数 437 浏览 4 评论 0原文

我正在尝试调试我所依赖的大型库的行为,该库通过其许多源文件使用分散(不要过多)的调试打印语句。问题是,大多数(如果不是全部)这些调试打印语句不包含日期/时间戳,因此很难将应用程序级别的故障与库代码本身的故障关联起来。

我认为可以暂时修补内置的 Python 打印“功能”,而不是修改所有疑似与我所看到的故障有关的调试打印的源代码。命令所有输出都以时间戳为前缀。

由于 内置 print 不是函数我正在使用Python 2.6环境,我不知道这是否可行。如果有人已经做到了这一点,或者使用 Python 的另一个钩子实现了类似的结果,那么我将不胜感激您的建议,甚至更好的解决此问题的代码。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

兔姬 2024-10-23 04:53:02

由于您无法覆盖 write 函数(它是只读的),一个简单的猴子补丁可能如下所示(将时间戳附加到每个打印行):

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

一个示例如下所示:

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

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]
苦笑流年记忆 2024-10-23 04:53:02

另一种解决方案是时间戳是开始(前置)而不是结束(附加):

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

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()
最丧也最甜 2024-10-23 04:53:02

要向 Python print 添加日期时间戳,您可以覆盖 print

首先,保留原来的 print()

_print=print

然后,定义你的 print 函数并使用 _print 来打印:

from datetime import datetime

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

现在你会得到一些东西类似:

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

注意:这是针对 python3 的,但对于 python2 很容易更改

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

First, keep the original print()

_print=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

翻了热茶 2024-10-23 04:53:02

我不是 100% 清楚 Velizar 的现有答案如何处理使用多个 \n 发送输出的情况。我不确定它是否可靠地工作,如果确实如此,我认为它可能依赖于输出流的潜在未记录的行为。

这是我的解决方案,它将时间戳添加到每个打印行的开头,并可靠地处理多行/行而无需 \n :

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

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()
九命猫 2024-10-23 04:53:02

改进 JosepH 给出的答案:

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

然后使用 _print 而不是 print,瞧。例如:_print(“你好!”)

Improving the answer given by JosepH:

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

Then use _print instead of print, and voila. For instance: _print("Hello!")

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文