Flask项目log的集成
一、引入log
在项目的init.py文件中:
import logging
from logging.handlers import RotatingFileHandlerfrom flask_wtf.csrf import CSRFProtect
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis
from flask_session import Session
from config import config_dict# 定义redis_store变量
redis_store = Nonedef create_app(config_name):# 调用日志方法,记录程序运行信息log_file()app = Flask(__name__)# 获取config配置config = config_dict.get(config_name)app.config.from_object(config)# 创建数据库关联对象并关联appdb = SQLAlchemy(app)# 创建redis对象# 当 decode_responses 设置为 True 时,Redis 返回的字符串数据将会被解码为 Python 字符串类型。这样可以方便地处理 Redis 中存储的文本数据。# 而当 decode_responses 设置为 False(默认值)时,Redis 返回的字符串数据将会以字节字符串(bytes)的形式返回。# 这在处理二进制数据或者需要与其他 Redis 客户端进行交互时可能更为合适global redis_store # global将局部变量声明为全局变量redis_store = StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT, decode_responses=True)# 创建session对象Session(app)# 使用CSRFProtect保护appCSRFProtect(app)# 注册蓝图from info.modules.index import index_blueapp.register_blueprint(index_blue)return appdef log_file():# 设置日志的记录等级,常见的有四种,DEBUG<INFO<WARNING<ERRORlogging.basicConfig(level=logging.DEBUG) # 调试debug级# 创建日志记录器,指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)# 创建日志记录的格式日志等级输入日志信息的文件名行数日志信息formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')# 为刚创建的日志记录器设置日志记录格式file_log_handler.setFormatter(formatter)# 为全局的日志工具对象(flask app使用的)添加日志记录器logging.getLogger().addHandler(file_log_handler)
这个时候执行的话会报错的,所以需要创建一个logs文件在项目根文件下,至于是不是叫logs取决与你在配置中设置的文件名
二、log的使用
from info.modules.index import index_blue
from flask import current_app # flask中app的原生对象@index_blue.route('/', methods=['GET', 'POST'])
def hello_world():# 因为log_file中的这个 logging.getLogger().addHandler(file_log_handler)将logger挂载到了原生对象中去了current_app.logger.debug('输入详细信息')current_app.logger.info('输入详细信息')current_app.logger.warning('输入详细信息')current_app.logger.error('输入详细信息')return "helloworld"
三、log的抽取,将log等级与环境挂钩
#####################将log的level单独抽取出来并在调用时传入####################
import logging
from logging.handlers import RotatingFileHandlerfrom flask_wtf.csrf import CSRFProtect
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis
from flask_session import Session
from config import config_dict# 定义redis_store变量
redis_store = Nonedef create_app(config_name):app = Flask(__name__)# 获取config配置config = config_dict.get(config_name)# 调用日志方法,记录程序运行信息log_file(config.LEVEL_NAME)app.config.from_object(config)# 创建数据库关联对象并关联appdb = SQLAlchemy(app)# 创建redis对象# 当 decode_responses 设置为 True 时,Redis 返回的字符串数据将会被解码为 Python 字符串类型。这样可以方便地处理 Redis 中存储的文本数据。# 而当 decode_responses 设置为 False(默认值)时,Redis 返回的字符串数据将会以字节字符串(bytes)的形式返回。# 这在处理二进制数据或者需要与其他 Redis 客户端进行交互时可能更为合适global redis_store # global将局部变量声明为全局变量redis_store = StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT, decode_responses=True)# 创建session对象Session(app)# 使用CSRFProtect保护appCSRFProtect(app)# 注册蓝图from info.modules.index import index_blueapp.register_blueprint(index_blue)return appdef log_file(LEVEL_NAME):# 设置日志的记录等级,常见的有四种,DEBUG<INFO<WARNING<ERRORlogging.basicConfig(level=LEVEL_NAME) # 调试debug级# 创建日志记录器,指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)# 创建日志记录的格式日志等级输入日志信息的文件名行数日志信息formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')# 为刚创建的日志记录器设置日志记录格式file_log_handler.setFormatter(formatter)# 为全局的日志工具对象(flask app使用的)添加日志记录器logging.getLogger().addHandler(file_log_handler)
################将log的等级与环境条件挂钩,不用的环境参数绑定不用的log等级##############
import logging
from datetime import timedelta
from redis import StrictRedisclass Config():# 调试信息DEBUG = TrueSECRET_KEY = 'fjsiogkgnmdinging'# 数据库信息SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:123456@localhost:3306/info36'SQLALCHEMY_TRACK_MODIFICATIONS = False# redis配置REDIS_HOST = '127.0.0.1'REDIS_PORT = 6379# session配置SESSION_TYPE = 'redis' # 设置session的存储类型SESSION_REDIS = StrictRedis(host=REDIS_HOST, port=REDIS_PORT) # 指定session存储的服务器# SESSION_USE_SIGNER = True # 设置签名存储PERMANENT_SESSION_LIFETIME = timedelta(days=1) # 设置签名过期时间# 配置默认的log等级LEVEL_NAME = logging.DEBUG# 开发环境配置信息
class DevelopConfig(Config):pass# 生产(线上)环境配置信息
class ProductConfig(Config):DEBUG = FalseLEVEL_NAME = logging.ERROR# 测试环境配置信息
class TestConfig(Config):pass# 提供一个统一的访问入口
config_dict = {"develop": DevelopConfig,"product": ProductConfig,"test": TestConfig
}