# -*- coding: utf-8 -*-
# @Time : 2022/10/01
# @Author : chron
# @FileName: hello_world.py
# @Software: PyCharm
# @E-mail : [email protected]
import logging
from logging.handlers import TimedRotatingFileHandler
from flask import Flask, request, session
app = Flask(__name__)
app.secret_key = "123456"
# 日志信息设置,记录到文件中
server_log = TimedRotatingFileHandler("sever.log", "D")
server_log.setLevel(logging.DEBUG)
server_log.setFormatter(logging.Formatter("%(asctime)s-%(filename)s-%(levelname)s]:%(message)s'"))
error_log = TimedRotatingFileHandler("error.log", "D")
error_log.setLevel(logging.ERROR)
error_log.setFormatter(logging.Formatter("%(asctime)s-%(filename)s-%(levelname)s]:%(message)s'"))
# 将日志处理handler应用到app上
app.logger.addHandler(server_log)
app.logger.addHandler(error_log)
@app.route("/login", methods=["POST"])
def login():
if request.form.get("user") == "admin":
session["user"] = request.form.get("user")
app.logger.warning(f"登录成功:{session['user']}")
return "admin 登录成功"
@app.route("/logout", methods=["POST"])
def logout():
user = session.get("user")
session.pop("user", None)
return f"{user} 注销成功"
@app.route("/error", methods=["POST"])
def error():
app.logger.error("触发error日志")
return "111"
# 启动web服务器 默认运行在5000端口上
# host="0.0.0.0"启用远程调用 port="8888"改变远程端口 debug=True 打开调试模式
if __name__ == '__main__':
app.run(debug=True, host="0.0.0.0", port=8888)
标签:__,logging,log,flask,app,user,error,日志
From: https://www.cnblogs.com/chron/p/16746671.html