简体   繁体   English

使用Python的日志记录模块记录错误

[英]Problem logging errors with Python's logging module

I'm logging an error with python's logging module. 我正在使用python的日志记录模块记录错误。 I made a logger object inside my class, as follows: 我在我的课程中创建了一个logger对象,如下所示:

self.my_logger = logging.getLogger('my_logger')
self.my_logger.setLevel(logging.ERROR)

when I try to log an error later in the code, as: 当我尝试在代码中稍后记录错误时,如下所示:

self.my_logger.error("My error")

then I get the error: 然后我得到错误:

AttributeError: FileHandler instance has no attribute 'filters'

The more detailed error log is: 更详细的错误日志是:

  File "/lib/python2.6/logging/__init__.py", line 1047, in error
    self._log(ERROR, msg, args, **kwargs)
  File "/lib/python2.6/logging/__init__.py", line 1129, in _log
    self.handle(record)
  File "/lib/python2.6/logging/__init__.py", line 1139, in handle
    self.callHandlers(record)
  File "/lib/python2.6/logging/__init__.py", line 1176, in callHandlers
    hdlr.handle(record)
  File "/lib/python2.6/logging/__init__.py", line 658, in handle
    rv = self.filter(record)
  File "/lib/python2.6/logging/__init__.py", line 558, in filter
    for f in self.filters:
AttributeError: FileHandler instance has no attribute 'filters'

Upstream of this, here is how I set the file handler: 在上游,这是我设置文件处理程序的方式:

 if self.log_dir != None:
    self.log_filename = os.path.join(self.log_dir, 'run.%s' \
                                     %(time.strftime("%m-%d-%y_%H:%M:%S")))

 ch_file = logging.FileHandler(self.log_filename,
                                  delay=True)
 ch_file.setLevel(logging.ERROR)
 ch_file.setFormatter(formatter)
 self.my_logger.addHandler(ch_file)

 ch_stream = logging.StreamHandler()
 ch_stream.setLevel(logging.INFO)

 # add formatter to ch
 ch_stream.setFormatter(formatter)

 # add ch to logger
 self.my_logger.addHandler(ch_stream)
 self.my_logger.info("Ready.")

Any idea what is happening here? 知道这里发生了什么吗? thanks. 谢谢。

Check that you haven't defined any modules whose names clash with standard ones. 检查您是否未定义任何名称与标准名称冲突的模块。 The slightly modified script below runs on my system without error. 下面稍加修改的脚本在我的系统上运行而没有错误。 Try it on yours and if it works, double check that you are not redefining any classes with the same names. 尝试使用它,如果它有效,请仔细检查您是否重新定义了具有相同名称的任何类。

import logging
import os
import time

class SomeClass:
    def __init__(self):
        self.log_dir = os.getcwd()
        formatter = logging.Formatter('%(asctime)s %(message)s')
        self.my_logger = logging.getLogger('my_logger')
        self.my_logger.setLevel(logging.INFO)

        if self.log_dir != None:
            self.log_filename = os.path.join(self.log_dir, 'run.log')

        ch_file = logging.FileHandler(self.log_filename, 'w')
        ch_file.setLevel(logging.ERROR)
        ch_file.setFormatter(formatter)
        self.my_logger.addHandler(ch_file)

        ch_stream = logging.StreamHandler()
        ch_stream.setLevel(logging.INFO)

        # add formatter to ch
        ch_stream.setFormatter(formatter)

        # add ch to logger
        self.my_logger.addHandler(ch_stream)
        self.my_logger.info("Ready.")

        self.my_logger.error("My error")


def main():
    SomeClass()

if __name__ == '__main__':
    main()

By the way - I know you didn't ask about this, but it's not recommended practice to store loggers as instance variables - there's no point, as they're singletons anyway. 顺便说一下 - 我知道你没有问过这个问题,但是不建议将记录器存储为实例变量 - 没有意义,因为他们无论如何都是单身人士。 The normal approach for most users is to have a single 大多数用户的正常方法是拥有一个

logger = logging.getLogger(__name__)

at module level, and use that throughout the module. 在模块级别,并在整个模块中使用它。 If you need more granularity, create a child logger of the logger using __name__ as a prefix (eg '%s.detail' % __name__ ) 如果需要更多粒度,请使用__name__作为前缀创建记录器的子记录器(例如'%s.detail' % __name__

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM