{site_name}

{site_name}

🌜 搜索

PythonBaseRotatingHandler是Python标准库loggi

Python 𝄐 0
python把series对象等分数据,python把server删了怎么恢复
PythonBaseRotatingHandler是Python标准库logging模块提供的一个日志处理器,用于控制日志文件的轮换(即在达到一定大小或时间后,将当前日志文件重命名并创建新的日志文件)。它是BaseRotatingHandler的抽象基类,要使用它,需要继承该类并实现一些方法。

以下是一个示例代码,展示如何使用PythonBaseRotatingHandler:

python
import logging.handlers

class MyRotatingHandler(logging.handlers.BaseRotatingHandler):
def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0):
super().__init__(filename, mode, encoding, delay)
self.maxBytes = maxBytes
self.backupCount = backupCount

def doRollover(self):
"""Do a rollover, as described in __init__()."""
if self.stream:
self.stream.close()
self.stream = None
# get the next file name
for i in range(self.backupCount - 1, 0, -1):
sfn = "%s.%d" % (self.baseFilename, i)
dfn = "%s.%d" % (self.baseFilename, i + 1)
if os.path.exists(sfn):
if os.path.exists(dfn):
os.remove(dfn)
os.rename(sfn, dfn)
dfn = self.rotation_filename("%s.1" % self.baseFilename)
if not self.delay:
self.stream = self._open()
if self.encoding:
self.stream = codecs.getwriter(self.encoding)(self.stream)
self.emit(logging._StderrHandler.WARNING, 'Log file %s was closed, now using %s' % (self.baseFilename, dfn))
self.stream = self._open()

def shouldRollover(self, record):
"""Check if rollover should occur."""
if self.stream is None:
return False
if self.maxBytes > 0:
msg = "%s\n" % self.format(record)
self.stream.write(msg.encode('utf-8')) # write the message to the stream
self.current_size += len(msg.encode('utf-8'))
if self.current_size >= self.maxBytes:
return True
return False

logger = logging.getLogger(__name__)
handler = MyRotatingHandler('mylogfile.log', maxBytes=1024, backupCount=3)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

# Then use the logger as usual
logger.debug("debug message")


在这个示例中,我们创建了一个名为MyRotatingHandler的子类,并将其继承自PythonBaseRotatingHandler。该子类重写了doRollover()和shouldRollover()方法,以实现日志文件的轮换功能。在使用时,我们可以将该处理器添加到logger对象中,并像往常一样记录日志信息。