如何使logging.logger表现得像print

时间:2016-09-19 08:51:34

标签: python python-3.x logging

假设我得到了这个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)

当我尝试使用它时,就像带有动态数量参数的内置打印一样:

>>> 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

我怎样才能使用logging.Logger来模拟打印行为?

3 个答案:

答案 0 :(得分:2)

Wrapper基于@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)

答案 1 :(得分:0)

或者,在您对*args的调用中定义一个接受join然后logger的函数:

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

我在此处添加了logtype以获得灵活性,但如果不需要,您可以删除它。

答案 2 :(得分:-1)

将sys.stdout设置为日志记录的流。

e.g。 logging.basicConfig(level=logging.INFO, stream=sys.stdout