向 Python 打印添加日期时间戳
我正在尝试调试我所依赖的大型库的行为,该库通过其许多源文件使用分散(不要过多)的调试打印语句。问题是,大多数(如果不是全部)这些调试打印语句不包含日期/时间戳,因此很难将应用程序级别的故障与库代码本身的故障关联起来。
我认为可以暂时修补内置的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
由于您无法覆盖
write
函数(它是只读的),一个简单的猴子补丁可能如下所示(将时间戳附加到每个打印行):一个示例如下所示:
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):An example would the look like this:
另一种解决方案是时间戳是开始(前置)而不是结束(附加):
An alternative solution that the timestamp is the beginning (prepended) instead of end (appended):
要向 Python
print
添加日期时间戳,您可以覆盖print
。首先,保留原来的
print()
然后,定义你的
print
函数并使用_print
来打印:from datetime import datetime
现在你会得到一些东西类似:
注意:这是针对
python3
的,但对于python2
很容易更改To add datetime stamp to Python
print
you can overrideprint
.First, keep the original
print()
Then, define your
print
function and use_print
to print:from datetime import datetime
Now you will get something like:
Note: This is for
python3
but it is easy to change forpython2
我不是 100% 清楚 Velizar 的现有答案如何处理使用多个 \n 发送输出的情况。我不确定它是否可靠地工作,如果确实如此,我认为它可能依赖于输出流的潜在未记录的行为。
这是我的解决方案,它将时间戳添加到每个打印行的开头,并可靠地处理多行/行而无需 \n :
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:
改进 JosepH 给出的答案:
然后使用
_print
而不是print
,瞧。例如:_print(“你好!”)
Improving the answer given by JosepH:
Then use
_print
instead ofprint
, and voila. For instance:_print("Hello!")