2016-09-19 39 views
3

比方说,我得到这个logging.logger实例:如何让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的打印行为?

+1

只是附上PARAMS像logger.debug括号(( “你好”, “世界”)),例如 – Andrey

+0

安德烈:嗯,好吧,我可以让快速搜索和替换我的所有打印后,您的模式,欢呼声;-) – BPL

回答

0

另外,定义接受*args一个函数,然后join他们在您的来电logger

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

我加了logtype灵活性在这里,但如果不需要的话,你可以将其删除。根据@

+0

非常好!我已经根据你的代码添加了我的答案,谢谢;) – BPL

+1

...'“{}”。格式(a)'实际上只是一种丑陋而复杂的写作方式'str(a)'...另外' (f(x)为顺序x)'只是'map(f,sequence)'如果你喜欢功能风格。 – Bakuriu

-1

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

例如 logging.basicConfig(level=logging.INFO, stream=sys.stdout

+0

我已经试过了与python 3.5.1,仍然崩溃'TypeError:不是所有参数在字符串格式转换过程中转换' – BPL

+0

如果有这发生在我面前,导致它的行做了如下操作:'('{} {}',variable1,variable2)'。当改为“{} {}'。格式(变量1,变量2)'为我修好了。 – vds

2

包装吉姆的原来的答案:

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)