我想将某些任意代码的print()
语句重定向到正确的日志记录功能。
不幸的是,以下代码仅在print()
获得单个参数时起作用。
import logging
logging.basicConfig(filename="logname",
filemode='a',
format='%(asctime)s,%(msecs)03d %(name)s %(levelname)s %(message)s',
datefmt='%D %H:%M:%S',
level=logging.DEBUG)
print = logging.debug
print("hallo")
print("makes", "error")
这会产生以下日志文件:
03/30/18 14:06:11,881 root DEBUG hallo
控制台中出现以下错误:
Connected to pydev debugger (build 173.4674.37)
--- Logging error ---
Traceback (most recent call last):
File "/home/user/anaconda3/lib/python3.6/logging/__init__.py", line 992, in emit
msg = self.format(record)
File "/home/user/anaconda3/lib/python3.6/logging/__init__.py", line 838, in format
return fmt.format(record)
File "/home/user/anaconda3/lib/python3.6/logging/__init__.py", line 575, in format
record.message = record.getMessage()
File "/home/user/anaconda3/lib/python3.6/logging/__init__.py", line 338, in getMessage
msg = msg % self.args
TypeError: not all arguments converted during string formatting
Call stack:
File "/home/user/install_dir/pycharm/2017-12-12-ultimate-edition/pycharm-2017.3/helpers/pydev/pydevd.py", line 1668, in <module>
main()
File "/home/user/install_dir/pycharm/2017-12-12-ultimate-edition/pycharm-2017.3/helpers/pydev/pydevd.py", line 1662, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "/home/user/install_dir/pycharm/2017-12-12-ultimate-edition/pycharm-2017.3/helpers/pydev/pydevd.py", line 1072, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/home/user/install_dir/pycharm/2017-12-12-ultimate-edition/pycharm-2017.3/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/home/user/PycharmProjects/my_project/attic.py", line 12, in <module>
print("makes", "error")
Message: 'makes'
Arguments: ('error',)
Process finished with exit code 0
如何更改代码以使其适用于print()
的任意数量的参数?
答案 0 :(得分:1)
print
不再是自己了,因为您将print
重新定义为logging.debug
,debug
仅将第一个参数作为消息。但是,您可以采用不同的方式定义print
,如下所示:
def print(*args, sep=" ", **kwargs):
return logging.debug(sep.join(map(lambda x: str(x), args)), **kwargs)
这会失去使用debug
*args
格式化字符串的功能。
args
是使用字符串合并到msg
的参数 格式化运算符(请注意,这意味着您可以使用关键字 在格式字符串中,与单个字典参数一起使用。)
我建议您使用StreamHandler而不是重新定义print
。