每次启动应用程序时旋转日志文件(Python) [英] Rotate logfiles each time the application is started (Python)

查看:145
本文介绍了每次启动应用程序时旋转日志文件(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using the logging module in Python and I would like it to create a new logfile each time my application is started. The older logfiles shoud be rotated (eg: logfile.txt -> logfile1.txt, etc).

我已经找到了:

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

BaseRotatingHandler是基类 对于在以下位置旋转日志文件的处理程序 某一点.这并不意味着 直接实例化.相反,使用 RotatingFileHandler或 TimedRotatingFileHandler.

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则根据when和interval的乘积进行翻转.两者都不是我想要的,我希望轮换能够在我的应用程序启动时立即发生.

The RotatingFileHandler does a rollover at a predetermined size and the TimedRotatingFileHandler does a rollover based on the product of when and interval. Both are not what I want, I want the rotation to happen immediately when my application starts.

推荐答案

我可能足以在没有maxBytes的情况下使用RotatingFileHandler,然后在应用程序启动时调用doRollover().

I might be enough to use RotatingFileHandler without maxBytes, then call doRollover() on application start.

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

Yup, seems to work fine. The code below will create a new log file on each application run, with added timestamps for log start and close times. Running it will print the list of available log files. You can inspect them to check correct behavior. Adapted from the Python docs example:

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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆