Python 的记录器能够轮换日志文件吗?

Ale*_*lex 2 python logging

有没有办法使用 python 中附带的日志记录模块来轮换日志文件?就像 logrotate 中那样?

我使用了 logrotate 但它给出了一些奇怪的结果。

har*_*rry 6

我想可以帮助你。

是的,您也可以类似于logrotate在 Linux 中在 Python 中旋转日志文件。以下是上面链接中的一个小示例:

import glob
import logging
import logging.handlers

LOG_FILENAME = 'logging_rotatingfile_example.out'

# Set up a specific logger with our desired output level
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)

# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(
              LOG_FILENAME, maxBytes=20, backupCount=5)

my_logger.addHandler(handler)

# Log some messages
for i in range(20):
    my_logger.debug('i = %d' % i)

# See what files are created
logfiles = glob.glob('%s*' % LOG_FILENAME)

for filename in logfiles:
    print(filename)
Run Code Online (Sandbox Code Playgroud)

脚本的输出是:

logging_rotatingfile_example.out
logging_rotatingfile_example.out.1
logging_rotatingfile_example.out.2
logging_rotatingfile_example.out.3
logging_rotatingfile_example.out.4
logging_rotatingfile_example.out.5
Run Code Online (Sandbox Code Playgroud)

最新文件始终是logging_rotatingfile_example.out每次达到大小限制时都会使用后缀重命名.i。每个现有备份文件都被重命名以增加后缀(.1 变为 .2 等)。

这只是一个展示示例。在现实生活场景中,您应该将 设定maxBytes为适当的值。

来源:Python 文档(上面列出的文章,以防链接损坏)