简体   繁体   English

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

[英]Simple Rotating Python Logger (RotatingFileHandler)

I'm trying to write a simple logger but I'm getting an exception thrown. 我正在尝试编写一个简单的记录器,但抛出异常。 I'd like some advice on why this exception's getting thrown, but will also appreciate some design suggestions (keeping in mind that i'd like to keep this simple). 我想就为何引发此异常的问题提供一些建议,但也希望获得一些设计建议(请记住,我想保持这种简单性)。

Code: 码:

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

Output: 输出:

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'

Because the handler's .emit() takes a record , not a string. 因为处理程序的.emit()需要记录 ,而不是字符串。

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

You probably don't want to create your own logger class, just retrieve one using Logging.getLogger(__name__) (or similar) and call the appropriate method ( .error(logText) for example). 您可能不想创建自己的记录器类,只需使用Logging.getLogger(__name__) (或类似名称)检索一个记录器类,然后调用适当的方法(例如.error(logText) )。
EDIT: And you definitely don't want to create a new handler every time you log something, it normally should be created once per application. 编辑:并且您绝对不希望每次登录时都创建一个新的处理程序,通常应该为每个应用程序创建一次。 For simple cases, you're can simply use logging.basicConfig() . 对于简单的情况,您可以简单地使用logging.basicConfig()

See http://docs.python.org/library/logging.html 参见http://docs.python.org/library/logging.html

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

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