python - 每次启动应用程序时轮换日志文件 (Python)

标签 python logging rotation

我在 Python 中使用日志记录模块,我希望它在我的应用程序每次启动时创建一个新的日志文件。应该轮换较旧的日志文件(例如:logfile.txt -> logfile1.txt 等)。

我已经找到了:

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

BaseRotatingHandler is the base class for handlers that rotate log files at a certain point. It is not meant to be instantiated directly. Instead, use RotatingFileHandler or TimedRotatingFileHandler.

RotatingFileHandler 以预定大小进行翻转,TimedRotatingFileHandler 根据时间和间隔的乘积进行翻转。两者都不是我想要的,我希望在我的应用程序启动时立即进行轮换。

最佳答案

我可能足以使用没有 maxBytesRotatingFileHandler,然后在应用程序启动时调用 doRollover()

是的,似乎工作正常。下面的代码将在每次应用程序运行时创建一个新的日志文件,并为日志开始和关闭时间添加时间戳。运行它将打印可用日志文件的列表。您可以检查它们以检查正确的行为。改编自 Python 文档示例:

import os
import glob
import logging
import logging.handlers
import time

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)

# Check if log exists and should therefore be rolled
needRoll = os.path.isfile(LOG_FILENAME)

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

my_logger.addHandler(handler)

# This is a stale log, so roll it
if needRoll:    
    # Add timestamp
    my_logger.debug('\n---------\nLog closed on %s.\n---------\n' % time.asctime())

    # Roll over on application start
    my_logger.handlers[0].doRollover()

# Add timestamp
my_logger.debug('\n---------\nLog started on %s.\n---------\n' % time.asctime())

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

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

print '\n'.join(logfiles)

关于python - 每次启动应用程序时轮换日志文件 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4654915/

相关文章:

python - 满足条件时停止应用

python - 检查re.sub中是否发生修改

javascript - 三个js平面几何体旋转时消失

javascript - 创建旋转矩阵

matlab - Matlab中矩阵在空间中的旋转会导致移动而不是旋转到放置位置

python - Django 1.6.5 和 1.5.4 Tango 与 django

python - 从同级目录导入

c++ - 窗口上 C/C++ 的自动记录器

python - 如何在python中检测断开连接,而不发送数据

logging - Logstash 输入插件 : Redis vs Elasticsearch