[英]Custom rotator and namer functions not working with RotatingFileHandler logger handler in python?
I have referred below link for using rotator and namer functions, but they are not working(not making any difference) 我已经在下面提到了使用rotator和namer函数的链接,但是它们不起作用(没有任何区别)
Link: https://docs.python.org/3/howto/logging-cookbook.html#using-a-rotator-and-namer-to-customize-log-rotation-processing 链接: https : //docs.python.org/3/howto/logging-cookbook.html#using-a-rotator-and-namer-to-customize-log-rotation-processing
I want the logs to be compressed and named like system1.log.gz, but they are saving like system.log.1, hence I made below changes, but still, it is not working. 我希望日志被压缩并命名为system1.log.gz,但是它们像system.log.1一样保存,因此我进行了以下更改,但仍然无法正常工作。
Environment: python 2.7.5 环境:python 2.7.5
import logging
import os
import zlib
from logging.handlers import RotatingFileHandler
LOG_PATH = "/tmp"
FILE_NAME = "system.log"
Logger = logging.getLogger()
def namer(name):
orig_name = name.split(".")
return orig_name[0] + orig_name[2] + ".log.gz"
def rotator(source, dest):
with open(source, "rb") as sf:
data = sf.read()
compressed = zlib.compress(data, 9)
with open(dest, "wb") as df:
df.write(compressed)
os.remove(source)
logFormatter = logging.Formatter(
"%(asctime)s %(levelname)s [%(threadName)s] %(filename)s:%(lineno)d %(message)s")
Logger.setLevel(logging.DEBUG)
fileHandler = RotatingFileHandler(
"{0}/{1}".format(LOG_PATH, FILE_NAME), maxBytes=1000, backupCount=10)
fileHandler.setFormatter(logFormatter)
fileHandler.rotator = rotator
fileHandler.namer = name
Logger.addHandler(fileHandler)
Expected compressed log name: system1.log.gz 预期的压缩日志名称:system1.log.gz
Actual non-compressed log name: system.log.1 实际的非压缩日志名称:system.log.1
You are using the cookbook for python 3
, but run your code with python 2.7.5
. 您正在使用适用于python 3
的菜谱,但使用python 2.7.5
运行代码。 The feature you are trying to use simply does not exist in 3. The best solution is to use python 3 as version 2 will retire in a few months . 您尝试使用的功能在3中根本不存在。最好的解决方案是使用python 3,因为版本2将在几个月后退役 。 If that is not an option you can achieve the desired behaviour by creating your own handler class that inherits from RotatingFileHandler
and overwrites the emit
and doRollover
. 如果这不是一个选项,您可以实现通过创建一个从继承自己的处理程序类所需的行为RotatingFileHandler
并覆盖emit
和doRollover
。 emit
needs to do the compression, and doRollover
the naming. emit
需要进行压缩,并命名doRollover
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.