Python日志输出到控制台

10
我正在尝试在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”后面的行被删除,就不会输出到标准输出。可能的问题是什么?

请点击这里查看:https://dev59.com/1lsX5IYBdhLWcg3wB7r3 - Joshua Nixon
OP 的代码已经实现了链接问题中提出的答案建议。 - GPhilo
虽然相关 - Mad Physicist
是的,我在发布之前已经检查过了。不过还是谢谢。 - GregT
3个回答

19
问题出在调用basicConfig函数上,该函数为stderr设置了一个日志处理器,还接受一个格式字符串,而不是格式化程序。由于您稍后自己完成此工作,因此不需要使用basicConfig函数。有关更多信息,请参见Python文档。 移除对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)

绝对比我建议的更好。+1 - Mad Physicist

2

在 Python bug 追踪器上查看类似问题(https://bugs.python.org/issue16368),您会发现 formatter 参数应该是字符串(因此尝试调用 find):

最初的回答来源于 Python bug 追踪器,formatter 参数需要是字符串类型,因此才会尝试使用 find 方法。

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

这是设置日志记录到控制台的最简单选项。 - Jonathan B.

0
如果您只需要使用控制台日志并使用任何日志代理收集日志,您也可以使用 print("我的日志信息在这里")
这适用于像JS中的console.log()一样的快速故障排除。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接