Python RotatingFileHandler 不旋转

Python RotatingFileHandler not rotating

我尝试使用 RotatingFileHandler 在 Python 中限制日志文件的大小。

我正在使用以下代码:

logger = logging.getLogger(logging.basicConfig(
    filename = log_filename,
    handlers = [logging.handlers.RotatingFileHandler(filename=log_filename, maxBytes=1024, backupCount=20)],
    format = "%(asctime)s %(message)s",
    level = logging.DEBUG))

我去过here and 。我同时使用了 maxBytes 和 backupCount 参数,但它仍然无法正常工作。 知道为什么日志文件没有轮换吗?

Python 2.7 不支持 logging.basicConfig() 函数中的 handlers 参数。 因此,您必须将处理程序移出 basicConfig 参数,如下所示:

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
handler = logging.handlers.RotatingFileHandler(filename=log_filename, maxBytes=1024, backupCount=20)
handler.setFormatter("%(asctime)s %(message)s")
logger.addHandler(handler)