简单的旋转Python记录器(RotatingFileHandler)

时间:2012-07-07 23:46:41

标签: python logging

我正在尝试编写一个简单的记录器但是我正在抛出异常。我想要一些关于为什么这个例子被抛出的建议,但也会欣赏一些设计建议(请记住,我想保持这个简单)。

代码:

import logging
import logging.handlers

class Logger:

    @staticmethod
    def log_to_file(logText):

        logFile = logging.handlers.RotatingFileHandler('/var/log/sosms/sosmsd.log', 'a', 1000, 5)
        formatter = logging.Formatter()
        logFile.setFormatter(formatter)

        logFile.emit(logText)

        return

输出:

kyle@boxmunch:/var/log/sosms$ /etc/rc.local
Traceback (most recent call last):
  File "/usr/lib/python2.7/logging/handlers.py", line 77, in emit
     if self.shouldRollover(record):
   File "/usr/lib/python2.7/logging/handlers.py", line 156, in shouldRollover
    msg = "%s\n" % self.format(record)
  File "/usr/lib/python2.7/logging/__init__.py", line 719, in format
    return fmt.format(record)
  File "/usr/lib/python2.7/logging/__init__.py", line 464, in format
    record.message = record.getMessage()
AttributeError: 'str' object has no attribute 'getMessage'
Traceback (most recent call last):
  File "/git/sosms/sosmsd/Main.py", line 10, in <module>
    Logger.Logger.log_to_file('SOSMSD starting..')
  File "/git/sosms/sosmsd/Logger.py", line 14, in log_to_file
    logFile.emit(logText)
  File "/usr/lib/python2.7/logging/handlers.py", line 83, in emit
    self.handleError(record)
  File "/usr/lib/python2.7/logging/__init__.py", line 799, in handleError
    record.filename, record.lineno))
AttributeError: 'str' object has no attribute 'filename'

1 个答案:

答案 0 :(得分:3)

因为处理程序的.emit()采用记录,而不是字符串。

http://docs.python.org/library/logging.handlers.html

您可能不想创建自己的记录器类,只需使用Logging.getLogger(__name__)(或类似的)检索一个,并调用适当的方法(例如.error(logText))。
编辑:你绝对不希望每次登录时都创建一个新的处理程序,通常应该为每个应用程序创建一次。对于简单的情况,您只需使用logging.basicConfig()

请参阅http://docs.python.org/library/logging.html