log函数python怎样进行日志归档

   2024-10-01 9300
核心提示:在Python中,可以使用logging模块进行日志记录和归档。要实现日志归档,可以使用logging模块中的RotatingFileHandler或TimedRota

在Python中,可以使用logging模块进行日志记录和归档。要实现日志归档,可以使用logging模块中的RotatingFileHandler或TimedRotatingFileHandler类。

下面是一个使用RotatingFileHandler实现日志归档的示例代码:

import loggingfrom logging.handlers import RotatingFileHandler# 创建logger对象logger = logging.getLogger("example")logger.setLevel(logging.DEBUG)# 创建RotatingFileHandler对象handler = RotatingFileHandler("example.log", maxBytes=10000, backupCount=5)handler.setLevel(logging.DEBUG)# 设置日志格式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")

在上面的示例中,创建了一个logger对象,并使用RotatingFileHandler创建了一个RotatingFileHandler对象。这个RotatingFileHandler对象会将日志记录到example.log文件中,并在文件大小达到10KB时自动切割文件,最多保留5个旧日志文件。

除了RotatingFileHandler,还可以使用TimedRotatingFileHandler实现按时间归档日志文件。示例代码如下:

import loggingfrom logging.handlers import TimedRotatingFileHandler# 创建logger对象logger = logging.getLogger("example")logger.setLevel(logging.DEBUG)# 创建TimedRotatingFileHandler对象handler = TimedRotatingFileHandler("example.log", when="midnight", interval=1, backupCount=5)handler.setLevel(logging.DEBUG)# 设置日志格式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")

在上面的示例中,创建了一个TimedRotatingFileHandler对象,它会在每天午夜切割日志文件并保留5个旧日志文件。

通过使用RotatingFileHandler或TimedRotatingFileHandler,可以实现日志的自动归档,确保日志文件不会无限增长。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号