溫馨提示×

log函數(shù)python怎樣進(jìn)行日志歸檔

小樊
82
2024-08-24 00:51:34
欄目: 編程語言

在Python中,可以使用logging模塊進(jìn)行日志記錄和歸檔。要實現(xiàn)日志歸檔,可以使用logging模塊中的RotatingFileHandler或TimedRotatingFileHandler類。

下面是一個使用RotatingFileHandler實現(xiàn)日志歸檔的示例代碼:

import logging
from logging.handlers import RotatingFileHandler

# 創(chuàng)建logger對象
logger = logging.getLogger("example")
logger.setLevel(logging.DEBUG)

# 創(chuàng)建RotatingFileHandler對象
handler = RotatingFileHandler("example.log", maxBytes=10000, backupCount=5)
handler.setLevel(logging.DEBUG)

# 設(shè)置日志格式
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# 將handler添加到logger對象中
logger.addHandler(handler)

# 記錄日志
logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")
logger.critical("This is a critical message")

在上面的示例中,創(chuàng)建了一個logger對象,并使用RotatingFileHandler創(chuàng)建了一個RotatingFileHandler對象。這個RotatingFileHandler對象會將日志記錄到example.log文件中,并在文件大小達(dá)到10KB時自動切割文件,最多保留5個舊日志文件。

除了RotatingFileHandler,還可以使用TimedRotatingFileHandler實現(xiàn)按時間歸檔日志文件。示例代碼如下:

import logging
from logging.handlers import TimedRotatingFileHandler

# 創(chuàng)建logger對象
logger = logging.getLogger("example")
logger.setLevel(logging.DEBUG)

# 創(chuàng)建TimedRotatingFileHandler對象
handler = TimedRotatingFileHandler("example.log", when="midnight", interval=1, backupCount=5)
handler.setLevel(logging.DEBUG)

# 設(shè)置日志格式
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# 將handler添加到logger對象中
logger.addHandler(handler)

# 記錄日志
logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")
logger.critical("This is a critical message")

在上面的示例中,創(chuàng)建了一個TimedRotatingFileHandler對象,它會在每天午夜切割日志文件并保留5個舊日志文件。

通過使用RotatingFileHandler或TimedRotatingFileHandler,可以實現(xiàn)日志的自動歸檔,確保日志文件不會無限增長。

0