使用Python将日志旋转到目录中 [英] Log Rotating into a Directory using Python
问题描述
我有一个名为Poller.log的文件,该文件始终附加在日志详细信息之后.我希望此日志文件每天轮换并限制30天.因此,该代码运行良好.
I have a file called Poller.log and it's appended by log details all the time. I want this log file to be rotated everyday and limited by 30 days. Thus, the code works well.
现在,我希望将此已轮换的日志保存在文件夹中(即logs/poller.log.2011-03-04_15-36).无论如何,可以直接在哪里创建此旋转文件?
Now I want this logs that has been rotated to be in a folder (i.e. logs/poller.log.2011-03-04_15-36). Is there anyway to direct where this rotated file should be created?
此python脚本将由Cron执行.
This python script will be executed by Cron.
import logging
import logging.handlers
LOG_FILENAME = '/home/stackoverflow/snmpdata/poller.log'
# Set up a specific logger with our desired output level
poll_logger = logging.getLogger('pollerLog')
# Add the log message handler to the logger
log_rotator = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when='d', interval=1, backupCount=30, encoding=None, delay=False, utc=False)
poll_logger.addHandler(log_rotator)
# Roll over on application start
poll_logger.handlers[0].doRollover()
推荐答案
Python日志记录处理程序不允许这样做.您可能有两种方法可以实现此目的:
Python logging handler don't allow to do that easily. You might have 2 way of achieve this :
-
最简单的方法是将LOG_FILENAME设置为已经在logs/poller.log中,如果您想在其他任何地方访问poller.log,请使用符号链接:)
The simplest way would to setup LOG_FILENAME to be already in logs/poller.log, and if you want to access to your poller.log anywhere else, use a symlink :)
从TimedRotatingFileHandler开始创建您自己的处理程序,然后从/usr/lib/python2.X/logging/handlers.py中的TimedRotatingFileHandler类复制/粘贴doRollover().并更改:
Create your own handler starting from TimedRotatingFileHandler, and copy/paste the doRollover() from /usr/lib/python2.X/logging/handlers.py, TimedRotatingFileHandler class. And change :
dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple)
到
dfn = os.path.join('logs', os.path.basename(self.baseFilename)) + "." + time.strftime(self.suffix, timeTuple)
这篇关于使用Python将日志旋转到目录中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!