Python日志记录和旋转文件 [英] Python logging and rotating files
本文介绍了Python日志记录和旋转文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个python程序正在写入由Linux的logrotate命令旋转的日志文件.发生这种情况时,我需要通知我的程序停止写入旧文件,并开始写入新文件.我可以处理信号,但是如何告诉python写入新文件?
I have a python program that is writing to a log file that is being rotated by Linux's logrotate command. When this happens I need to signal my program to stop writing to the old file and start writing to the new one. I can handle the signal but how do I tell python to write to the new file?
我正在这样打开文件:
logging.basicConfig(format='%(asctime)s:%(filename)s:%(levelname)s:%(message)s',filename=log_file, level=logging.INFO)
并像这样写:
logging.log(level,"%s" % (msg))
日志记录模块看起来非常强大,但也很庞大.谢谢.
The logging modules look very powerful but also overwhelming. Thanks.
推荐答案
不要使用logging.basicConfig
,请使用WatchedFileHandler
.这是使用方法.
Don't use logging.basicConfig
, use WatchedFileHandler
. Here's how to use it.
import time
import logging
import logging.handlers
def log_setup():
log_handler = logging.handlers.WatchedFileHandler('my.log')
formatter = logging.Formatter(
'%(asctime)s program_name [%(process)d]: %(message)s',
'%b %d %H:%M:%S')
formatter.converter = time.gmtime # if you want UTC time
log_handler.setFormatter(formatter)
logger = logging.getLogger()
logger.addHandler(log_handler)
logger.setLevel(logging.DEBUG)
log_setup()
logging.info('Hello, World!')
import os
os.rename('my.log', 'my.log-old')
logging.info('Hello, New World!')
这篇关于Python日志记录和旋转文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文