BPL*_*BPL 7 python logging python-3.x
假设我有这个logging.logger实例:
import logging
logger = logging.getLogger('root')
FORMAT = "[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
logging.basicConfig(format=FORMAT)
logger.setLevel(logging.DEBUG)
Run Code Online (Sandbox Code Playgroud)
当我尝试使用它时,就像带有动态数量参数的内置打印一样:
>>> logger.__class__
<class 'logging.Logger'>
>>> logger.debug("hello")
[<stdin>:1 - <module>() ] hello
>>> logger.debug("hello","world")
Traceback (most recent call last):
File "c:\Python2711\Lib\logging\__init__.py", line 853, in emit
msg = self.format(record)
File "c:\Python2711\Lib\logging\__init__.py", line 726, in format
return fmt.format(record)
File "c:\Python2711\Lib\logging\__init__.py", line 465, in format
record.message = record.getMessage()
File "c:\Python2711\Lib\logging\__init__.py", line 329, in getMessage
msg = msg % self.args
TypeError: not all arguments converted during string formatting
Logged from file <stdin>, line 1
Run Code Online (Sandbox Code Playgroud)
我怎样才能使用logging.Logger来模拟打印行为?
或者,定义一个接受的函数*args,然后join在调用中接受它们logger:
def log(*args, logtype='debug', sep=' '):
getattr(logger, logtype)(sep.join(str(a) for a in args))
Run Code Online (Sandbox Code Playgroud)
为了灵活性,我logtype在这里添加了一个,但如果不需要,您可以将其删除。