当我第一次学习Python时,我习惯这样做:
print "text", lineNumber, "some dictionary", my_dict
Run Code Online (Sandbox Code Playgroud)
当我编写自己的日志记录工具时,我自然希望能够提供任意大小的项目列表,所以我这样做:
def error(*args):
print ERR_PREFIX,
for _x in args:
print _x,
print "\r\n",
error("text", lineNumber, "some dictionary", my_dict)
Run Code Online (Sandbox Code Playgroud)
现在我想开始使用日志包,因为它有更多的好东西,我不想复制他们的努力.总的来说,它看起来像一个可以做很多事情的干净设计.但是我因为你不能再使用相同的项目列表来展示它而受到阻碍.相反,我必须将所有调用更改为更像这样的内容:
error("text %d some dictionary %s" % (lineNumber, my_dict))
Run Code Online (Sandbox Code Playgroud)
或者,我可以做一些非常愚蠢的事情:
error(' '.join(map, str(("text", lineNumber, "some dictionary", my_dict))))
Run Code Online (Sandbox Code Playgroud)
问题是,为什么省略这样一个明显的用例?如果您想直接从典型的"打印"声明转到新的日志记录设施,这不应该更容易吗?
作为后续问题,您能想到一种覆盖Logger类来执行此操作的方法吗?
我建议最好将现有的日志消息更新为日志记录模块所期望的样式,因为对于查看代码的其他人来说,更容易,因为日志记录模块将不再按预期运行.
除此之外,以下代码将使日志记录模块按您的需要运行.
import logging
import types
class ExtendedLogRecord(logging.LogRecord):
def getMessage(self):
"""
Return the message for this LogRecord.
Return the message for this LogRecord after merging any user-supplied
arguments with the message.
"""
if not hasattr(types, "UnicodeType"): #if no unicode support...
msg = str(self.msg)
else:
try:
msg = str(self.msg)
except UnicodeError:
msg = self.msg #Defer encoding till later
if self.args:
msg +=' '+' '.join(map(str,self.args))
return msg
#Patch the logging default logging class
logging.RootLogger.makeRecord=lambda self,*args: ExtendedLogRecord(*args)
some_dict={'foo':14,'bar':15}
logging.error('text',15,'some dictionary',some_dict)
Run Code Online (Sandbox Code Playgroud)
输出:
ERROR:root:text 15 some dictionary {'foo': 14, 'bar': 15}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6252 次 |
| 最近记录: |