Python Cherrypy 访问日志轮换

4 投票
4 回答
2598 浏览
提问于 2025-04-15 15:15

如果我想让Cherrypy的访问日志保持在一个固定的大小,我该如何使用轮转日志文件呢?

我已经尝试过http://www.cherrypy.org/wiki/Logging,但感觉上面的内容有点过时,或者缺少一些信息。

4 个回答

3

CherryPy的文档里有关于自定义日志处理器的例子。

下面是我在我的应用中使用的稍微修改过的版本:

import logging
from logging import handlers

def setup_logging():

    log = cherrypy.log

    # Remove the default FileHandlers if present.
    log.error_file = ""
    log.access_file = ""

    maxBytes = getattr(log, "rot_maxBytes", 10000000)
    backupCount = getattr(log, "rot_backupCount", 1000)

    # Make a new RotatingFileHandler for the error log.
    fname = getattr(log, "rot_error_file", "log\\error.log")
    h = handlers.RotatingFileHandler(fname, 'a', maxBytes, backupCount)
    h.setLevel(logging.DEBUG)
    h.setFormatter(cherrypy._cplogging.logfmt)
    log.error_log.addHandler(h)

    # Make a new RotatingFileHandler for the access log.
    fname = getattr(log, "rot_access_file", "log\\access.log")
    h = handlers.RotatingFileHandler(fname, 'a', maxBytes, backupCount)
    h.setLevel(logging.DEBUG)
    h.setFormatter(cherrypy._cplogging.logfmt)
    log.access_log.addHandler(h)

setup_logging()
3

我已经试过了这个链接 http://www.cherrypy.org/wiki/Logging,感觉里面的信息有点过时,或者缺少了一些内容。

可以试着添加:

import logging
import logging.handlers
import cherrypy # you might have imported this already

然后把这个换成

log = app.log

也许可以试试

log = cherrypy.log
4

可以看看这个链接:http://docs.python.org/library/logging.html

你可能想要设置一个叫做 RotatingFileHandler 的东西。

详细信息可以查看这个链接:http://docs.python.org/library/logging.html#rotatingfilehandler

撰写回答