2016-09-19 38 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)