一、视频教程
14_Flask日志
通过本节课程的学习,你将学会使用Flask提供的内置日志工具,可以帮助开发者记录应用程序的运行状态、调试信息以及错误报告等。配置和使用 Flask 的日志工具,使得可以灵活地设置日志级别、格式以及输出位置。《Flask快速入门教程》,人人都能学,小白看得懂学得会,跟我学编程,免费领取配套学习资料。
二、初始代码
Ctrl + C 拷贝 02-start-params,粘贴到 flask-study 目录,然后命名为 11-logging-config
三、日志配置使用
Flask 提供了一个内置的日志工具,基于 Python 的标准库 logging。这个工具可以帮助开发者记录应用程序的运行状态、调试信息以及错误报告等。下面介绍如何配置和使用 Flask 的日志工具,使得可以灵活地设置日志级别、格式以及输出位置。
3.1 创建日志处理器
# 参数:app.log 为日志文件名,maxBytes文件的最大大小为5MB(以字节为单位),backupCount保留日志文件备份的数量
file_handler = RotatingFileHandler('app.log', maxBytes=1024 * 1024 * 5, backupCount=2)
console_handler = logging.StreamHandler()
-
RotatingFileHandler:当文件达到一定大小时会自动轮转,并保留一定数量的旧文件。
-
StreamHandler:将日志输出到控制台。
3.2 设置日志级别
file_handler.setLevel(logging.ERROR)
console_handler.setLevel(logging.DEBUG)
-
设置日志级别:如 DEBUG, INFO, WARNING, ERROR, CRITICAL。
-
file_handler 只记录错误及以上的日志。
-
console_handler 记录所有级别的日志。
3.3 定义日志格式
formatter = logging.Formatter(
'%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s'
)
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
-
%asctime%:日志记录的时间。
-
%levelname%:日志级别。
-
%filename%:产生日志的文件名。
-
%lineno%:产生日志的行号。
-
%message%:日志消息。
3.4 将处理器添加到应用的日志记录器
app.logger.addHandler(file_handler)
app.logger.addHandler(console_handler)
3.5 路由处理函数中添加日志记录
@app.route('/')
def index():
app.logger.debug('Handling request to the root URL.')
return 'Hello, World!'
@app.route('/info')
def info():
app.logger.info('Handling request to the /info URL.')
return 'Info Page'
@app.route('/warning')
def warning():
app.logger.warning('Handling request to the /warning URL.')
return 'Warning Page'
@app.route('/error')
def error():
try:
raise Exception("An example exception")
except Exception as e:
app.logger.error(f"Exception occurred: {e}", exc_info=True)
return "Error occurred", 500
-
在每个路由处理函数中,根据需要记录不同级别的日志。
-
exc_info=True 参数会在日志中包含完整的堆栈跟踪信息。