com*_*pie 15 python logging rotation
我在Python中使用日志记录模块,我希望每次启动应用程序时都创建一个新的日志文件.应该旋转较旧的日志文件(例如:logfile.txt - > logfile1.txt等).
我已经发现了这个:
http://docs.python.org/library/logging.html
BaseRotatingHandler是在某个点旋转日志文件的处理程序的基类.它并不意味着直接实例化.而是使用RotatingFileHandler或TimedRotatingFileHandler.
RotatingFileHandler以预定大小进行翻转,TimedRotatingFileHandler根据when和interval的乘积进行翻转.两者都不是我想要的,我希望在我的应用程序启动时立即发生轮换.
Try*_*yPy 31
我可能是足够使用RotatingFileHandler无maxBytes,然后调用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)
Run Code Online (Sandbox Code Playgroud)
最简单的方法是在日志文件名中添加日期标记,因此每次启动应用程序时都会获得新的日志文件.
例如
dateTag = datetime.datetime.now().strftime("%Y-%b-%d_%H-%M-%S")
logging.basicConfig(filename="myapp_%s.log" % dateTag, level=logging.DEBUG)
Run Code Online (Sandbox Code Playgroud)
所以每次你都会像日志一样 myapp_2011-Jan-11_12-27-29.log
另一个好处是,您可以将其与RotatingFileHandler混合,以便为每个应用程序调用分别创建日志,其中每个日志本身进一步划分为多个固定大小的日志.
| 归档时间: |
|
| 查看次数: |
16742 次 |
| 最近记录: |