Skip to main content
 首页 » 编程设计

python之如何使用多个打印参数将打印重定向到日志记录

2025年01月19日10telwanggs

我想将一些任意代码的 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() 的任意数量的参数?

请您参考如下方法:

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 are the arguments which are merged into msg using the string formatting operator. (Note that this means that you can use keywords in the format string, together with a single dictionary argument.)


我建议您不要重新定义 print,而是使用 StreamHandler .