首页主机资讯log函数python怎样进行日志归档

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

时间2024-08-26 21:14:03发布访客分类主机资讯浏览605
导读:在Python中,可以使用logging模块进行日志记录和归档。要实现日志归档,可以使用logging模块中的RotatingFileHandler或TimedRotatingFileHandler类。 下面是一个使用RotatingFil...

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

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

import logging
from 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 logging
from 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,可以实现日志的自动归档,确保日志文件不会无限增长。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: log函数python怎样进行日志归档
本文地址: https://pptw.com/jishu/695884.html
log函数python中如何实现日志分割 如何通过手机安全地登录到云主机?

游客 回复需填写必要信息