flask 日志集成

 

日志配置:

import os
import time
import logging


# log配置,实现日志自动按日期生成日志文件
def make_dir(make_dir_path):
    """
    文件生成
    :param make_dir_path:
    :return:
    """
    path = make_dir_path.strip()
    if not os.path.exists( path ):
        os.makedirs( path )
    return path


log_dir_name = "logs"
log_file_name = 'logger-' + time.strftime( '%Y-%m-%d', time.localtime( time.time() ) ) + '.log'
log_file_folder = os.path.abspath(
    os.path.join( os.path.dirname( __file__ ), os.pardir, os.pardir ) ) + os.sep + log_dir_name
make_dir( log_file_folder )
log_file_str = log_file_folder + os.sep + log_file_name
log_level = logging.DEBUG

handler = logging.FileHandler( log_file_str, encoding='UTF-8' )
handler.setLevel( log_level )
logging_format = logging.Formatter(
    '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s' )
handler.setFormatter( logging_format )

日志集成:

 

# coding=utf-8
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_cors import *
from config import config
from app.util.my_log import handler
db = SQLAlchemy()


def create_app(config_name):
    """
    初始化app
    :param config_name:
    :return:
    """

    app = Flask(__name__)
    CORS(app, supports_credentials=True)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    db.init_app(app)
    db.app = app

    # 日志
    app.logger.addHandler(handler)

    return app


app = create_app(os.getenv('development') or 'default')

使用

from app import app

 app.logger.error(str(e))

 

你可能感兴趣的:(python_flask)