Python 记录到控制台

Python logging to console

我正在尝试在 Python 3.x 中创建一个日志,它会写入控制台。这是我的代码:

import logging
import sys

class Temp:
    def __init__(self, is_verbose=False):
        # configuring log
        if (is_verbose):
            self.log_level=logging.DEBUG
        else:
            self.log_level=logging.INFO

        log_format = logging.Formatter('[%(asctime)s] [%(levelname)s] - %(message)s')
        logging.basicConfig(level=self.log_level, format=log_format)
        self.log = logging.getLogger(__name__)

        # writing to stdout
        handler = logging.StreamHandler(sys.stdout)
        handler.setLevel(self.log_level)
        handler.setFormatter(log_format)
        self.log.addHandler(handler)

        # here
        self.log.debug("test")

if __name__ == "__main__":
    t = Temp(True)

如果输入 "here" 之后的行,Python 会引发错误:

[2019-01-29 15:54:20,093] [DEBUG] - test
--- Logging error ---
Traceback (most recent call last):
  File "C:\Programok\Python 36\lib\logging\__init__.py", line 993, in emit
    msg = self.format(record)
  File "C:\Programok\Python 36\lib\logging\__init__.py", line 839, in format
    return fmt.format(record)
  File "C:\Programok\Python 36\lib\logging\__init__.py", line 577, in format
    if self.usesTime():
  File "C:\Programok\Python 36\lib\logging\__init__.py", line 545, in usesTime
    return self._style.usesTime()
  File "C:\Programok\Python 36\lib\logging\__init__.py", line 388, in usesTime
    return self._fmt.find(self.asctime_search) >= 0
AttributeError: 'Formatter' object has no attribute 'find'
...

我的代码中还有其他一些地方打印到日志,但没有任何内容写入标准输出,即使删除了 "here" 之后的行。

可能是什么问题?

问题来自对 basicConfig 的调用,它为 stderr 设置了一个日志处理程序,并且还接受格式字符串,而不是格式化程序。因为后面是你自己做这个工作,所以不需要使用basicConfig函数。可以在 python documentation.

中找到更多信息

删除对 basicConfig 的调用并添加 self.log.setLevel(self.log_level) 将解决您遇到的问题。

工作代码:

import logging                                                                  
import sys                                                                      

class Temp:                                                                     
    def __init__(self, is_verbose=False):                                       
        # configuring log                                                       
        if (is_verbose):                                                        
            self.log_level=logging.DEBUG                                        
        else:                                                                   
            self.log_level=logging.INFO                                         

        log_format = logging.Formatter('[%(asctime)s] [%(levelname)s] - %(message)s')
        self.log = logging.getLogger(__name__)                                  
        self.log.setLevel(self.log_level)                                       

        # writing to stdout                                                     
        handler = logging.StreamHandler(sys.stdout)                             
        handler.setLevel(self.log_level)                                        
        handler.setFormatter(log_format)                                        
        self.log.addHandler(handler)                                            

        # here                                                                  
        self.log.debug("test")                                                  

if __name__ == "__main__":                                                      
    t = Temp(True)

查看 Python 错误跟踪器 (https://bugs.python.org/issue16368) 上的类似问题,您可以看到 formatter 参数应该是一个字符串(因此尝试调用find):

log_format = '[%(asctime)s] [%(levelname)s] - %(message)s'
logging.basicConfig(level=self.log_level, format=log_format)