每次启动应用程序时旋转日志文件(Python)

2024-06-01 06:41:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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按预定大小进行滚动,timedrotingfilehandler根据时间和间隔的乘积进行滚动。两者都不是我想要的,我希望在应用程序启动时立即进行轮换。


Tags: 模块文件orggttxt应用程序httpdocs
4条回答

我可能已经足够在没有maxBytes的情况下使用RotatingFileHandler,然后在应用程序启动时调用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)

当应用程序运行很长一段时间(几天)并且您希望日志保持旋转时,日志旋转和RoatatingFileHandler通常是被设计和需要的。在重新启动应用程序时必须旋转日志的情况下,我必须在日志文件处理程序之外执行此操作,这更简单。就像,在第一次调用日志编写器之前,我会查看日志文件是否已经存在,如果存在,则重命名它并创建一个新的日志文件。重命名应该与处理程序的重命名机制不同。

最简单的方法就是在日志文件名中有一个日期标记,所以每次启动应用程序时,都会得到一个新的日志文件。

例如

dateTag = datetime.datetime.now().strftime("%Y-%b-%d_%H-%M-%S")
logging.basicConfig(filename="myapp_%s.log" % dateTag, level=logging.DEBUG)

所以每次你会有像myapp_2011-Jan-11_12-27-29.log这样的日志

另一个好处是,您可以将其与RotatingFileHandler混合使用,为每个应用程序调用提供单独的日志,其中每个日志本身进一步划分为多个固定大小的日志。

当应用程序运行很长一段时间(几天)并且您希望日志保持旋转时,日志旋转和RoatatingFileHandler通常是设计好的并且是理想的。在重新启动应用程序时必须旋转日志的情况下,我必须在日志文件处理程序之外执行此操作,这更简单。就像,在第一次调用日志编写器之前,我会查看日志文件是否已经存在,如果存在,则重命名它并创建一个新的日志文件。重命名应该与处理程序的重命名机制不同。

相关问题 更多 >