在CentOS上配置Python日志,通常涉及以下几个步骤:
选择日志库:
Python的标准库中有一个logging模块,它是配置日志的首选工具。此外,还有第三方库如loguru等,但这里我们主要关注logging模块。
编写Python脚本:
在你的Python脚本中,首先需要导入logging模块,并进行基本的配置。以下是一个简单的示例:
import logging
# 配置日志记录器
logging.basicConfig(
level=logging.DEBUG, # 设置日志级别
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', # 设置日志格式
datefmt='%Y-%m-%d %H:%M:%S' # 设置日期格式
)
# 获取一个日志记录器实例
logger = logging.getLogger(__name__)
# 记录不同级别的日志
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')
basicConfig函数中添加filename参数。例如:logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename='app.log' # 将日志写入app.log文件
)
logging.handlers模块提供了RotatingFileHandler和TimedRotatingFileHandler来实现这一点。例如:from logging.handlers import RotatingFileHandler
# 创建一个日志记录器实例
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# 创建一个处理程序并设置其级别
handler = RotatingFileHandler('app.log', maxBytes=10*1024*1024, backupCount=5)
handler.setLevel(logging.DEBUG)
# 创建一个格式化程序并将其添加到处理程序
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
# 将处理程序添加到记录器
logger.addHandler(handler)
python your_script.py
或者,如果你使用的是Python 3,并且系统中同时安装了Python 2和Python 3,你可能需要使用python3命令来运行脚本:
python3 your_script.py
app.log)中查看生成的日志。以上就是在CentOS上配置Python日志的基本步骤。根据你的具体需求,你可能还需要进行更多的自定义配置。