如何进行日志记录.日志记录器的行为类似于打印



假设我得到了这个日志。logger实例:

import logging
logger = logging.getLogger('root')
FORMAT = "[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
logging.basicConfig(format=FORMAT)
logger.setLevel(logging.DEBUG)

问题来了,当我试图使用它像内置打印动态数量的参数:

>>> logger.__class__
<class 'logging.Logger'>
>>> logger.debug("hello")
[<stdin>:1 -             <module>() ] hello
>>> logger.debug("hello","world")
Traceback (most recent call last):
  File "c:Python2711Liblogging__init__.py", line 853, in emit
    msg = self.format(record)
  File "c:Python2711Liblogging__init__.py", line 726, in format
    return fmt.format(record)
  File "c:Python2711Liblogging__init__.py", line 465, in format
    record.message = record.getMessage()
  File "c:Python2711Liblogging__init__.py", line 329, in getMessage
    msg = msg % self.args
TypeError: not all arguments converted during string formatting
Logged from file <stdin>, line 1

我怎么能模拟打印行为仍然使用logging.Logger?

基于@Jim原始答案的包装器:

import logging
import sys
_logger = logging.getLogger('root')
FORMAT = "[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
logging.basicConfig(format=FORMAT)
_logger.setLevel(logging.DEBUG)

class LogWrapper():
    def __init__(self, logger):
        self.logger = logger
    def info(self, *args, sep=' '):
        self.logger.info(sep.join("{}".format(a) for a in args))
    def debug(self, *args, sep=' '):
        self.logger.debug(sep.join("{}".format(a) for a in args))
    def warning(self, *args, sep=' '):
        self.logger.warning(sep.join("{}".format(a) for a in args))
    def error(self, *args, sep=' '):
        self.logger.error(sep.join("{}".format(a) for a in args))
    def critical(self, *args, sep=' '):
        self.logger.critical(sep.join("{}".format(a) for a in args))
    def exception(self, *args, sep=' '):
        self.logger.exception(sep.join("{}".format(a) for a in args))
    def log(self, *args, sep=' '):
        self.logger.log(sep.join("{}".format(a) for a in args))
logger = LogWrapper(_logger)

或者,在调用logger时定义一个接受*argsjoin的函数:

def log(*args, logtype='debug', sep=' '):
    getattr(logger, logtype)(sep.join(str(a) for a in args))

我在这里添加了logtype以保持灵活性,但如果不需要,您可以删除它。

设置sys。标准输出作为日志记录的流。

logging.basicConfig(level=logging.INFO, stream=sys.stdout)

相关内容

  • 没有找到相关文章

最新更新