欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Flask學(xué)習(xí)筆記之日志操作配置實(shí)例講解

 更新時(shí)間:2023年11月22日 11:16:42   作者:Hunter  
這篇文章主要為大家介紹了Flask學(xué)習(xí)筆記之日志操作配置實(shí)例講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

引言

之前在 Django 筆記里詳細(xì)介紹了 logging 模塊關(guān)于 formatters,handlers,loggers 等基礎(chǔ)介紹,這里就不做多的介紹了,詳情可以直接跳轉(zhuǎn)查看相應(yīng)文章:Django筆記三十之log日志的記錄詳解

這里直接介紹如何在 Flask 中配置日志信息。

本篇筆記的代碼都已經(jīng)提交到 github 上,可使用下面的操作獲取代碼:

git clone https://github.com/x1204604036/flask_backend.git

1、日志配置

首先,我們創(chuàng)建一些日志輸出的文件地址變量,在 config/config.py 中記錄,根據(jù)環(huán)境判斷來源于測(cè)試環(huán)境變量文件或者生產(chǎn)環(huán)境變量文件,我這里是在 development.py 中,內(nèi)容如下:

LOGGING_PATH = "e:/code/log_file/flask_backend/flask.log"
LOGGING_ERROR_PATH = "e:/code/log_file/flask_backend/flask_error.log"

接著在 app/config/ 文件夾下創(chuàng)建一個(gè)文件 logging_config.py,內(nèi)容如下:

# app/config/logging_config.py
from app.config import config
LoggingConfig = {
    "version": 1,
    "formatters": {
        "verbose": {
            "format": "%(levelname)s %(asctime)s %(filename)s %(lineno)s %(message)s",
        }
    },
    "handlers": {
        "file": {
            "level": "INFO",
            "filename": config.LOGGING_PATH,
            "formatter": "verbose",
            "class": "logging.handlers.RotatingFileHandler",
            'maxBytes': 5 * 1024 * 1024,
            'backupCount': 20,
        },
        "error_handler": {
            "level": "INFO",
            "filename": config.LOGGING_ERROR_PATH,
            "formatter": "verbose",
            "class": "logging.handlers.RotatingFileHandler",
            'maxBytes': 5 * 1024 * 1024,
            'backupCount': 20,
        },
        "email_handler": {
            "level": "WARNING",
            "class": "logging.handlers.SMTPHandler",
            "mailhost": ("smtp.163.com", 25),
            "fromaddr": "hunterxxxxx@163.com",
            "toaddrs": "120xxxx@qq.com",
            "subject": "系統(tǒng)error",
            "credentials": ("hunterxxxx@163.com", "JBDMVIxxxxx"),
            "timeout": 20,
        },
    },
    "root": {
        "handlers": ["file"],
        "level": "INFO",
        "propagate": True,
    },
    "loggers": {
        "error_log": {
            "handlers": ["error_handler", "email_handler"],
            "level": "INFO",
        }
    }
}

這里創(chuàng)建了三個(gè) handler,兩個(gè) FileHandler 將日志以文件形式存儲(chǔ),一個(gè)用于發(fā)送郵件

其下,root 表示用于記錄 Flask 全部信息的輸出,其他的 logger 都在 loggers 下記錄,在這里一個(gè)記錄 error 的 logger 對(duì)應(yīng)有兩個(gè) handler,一個(gè)記錄日志到文件,一個(gè)發(fā)送郵件。

在 app/__init__.py 中引入日志配置:

# app/__init__.py
import logging.config
from app.config import looging_config
def create_app():
    app = Flask(__name__)
    logging.config.dictConfig(looging_config.LoggingConfig)
    return app

2、日志打印示例

這里,我們以上一節(jié)中的異常處理為例進(jìn)行日志記錄,將日志輸出的代碼都放到異常處理中,exception_handler.py 內(nèi)容如下:

from werkzeug.exceptions import HTTPException
from flask import jsonify, request
import logging
import traceback
logger = logging.getLogger("error_log")
ERROR_HTTP_CODE = 417
class UserException(Exception):
    def __init__(self, code=-1, msg="error", http_code=417):
        self.code = code
        self.msg = msg
        self.http_code = http_code
def init_error_exception(app):
    @app.errorhandler(HTTPException)
    def handler_http_exception(exception):
        trace_info = traceback.format_exc()
        log_msg = "request path: %s, traceback info: %s, description: %s" % (
            request.path, trace_info, exception.description
        )
        logger.info(log_msg)
        return jsonify({"code": -1, "msg": exception.description}), exception.code
    @app.errorhandler(Exception)
    def server_exception(exception):
        logger.info("request_path: " + request.path)
        trace_info = traceback.format_exc()
        log_msg = "request path: %s, traceback info: %s" % (request.path, trace_info)
        logger.info(log_msg)
        logger.error("系統(tǒng)報(bào)錯(cuò)信息:%s" % log_msg)
        return jsonify({"code": -1, "msg": "內(nèi)部錯(cuò)誤"}), ERROR_HTTP_CODE
    @app.errorhandler(UserException)
    def user_exception(exception):
        trace_info = traceback.format_exc()
        log_msg = "request path: %s, traceback info: %s, exception msg: %s" % (
            request.path, trace_info, exception.msg
        )
        logger.info(log_msg)
        return jsonify({"code": exception.code, "msg": exception.msg}), exception.http_code

這里,我們將請(qǐng)求路徑,報(bào)錯(cuò)信息等放到 log_msg 中,然后通過 logger.info() 輸出,另外,這里我們還嘗試對(duì)系統(tǒng)異常的處理發(fā)送郵件到指定郵箱。

注意:日志配置中的郵箱信息記得改成自己實(shí)際的,這里我對(duì)我的信息做了模糊處理。

重新運(yùn)行系統(tǒng)后,嘗試觸發(fā)這三種報(bào)錯(cuò),就可以在對(duì)應(yīng)的日志文件里看到錯(cuò)誤信息的輸出了,觸發(fā)了 error 的第二種 exception 異常處理還會(huì)發(fā)送郵件。

以上就是Flask學(xué)習(xí)筆記之日志操作實(shí)例講解的詳細(xì)內(nèi)容,更多關(guān)于Flask日志操作配置的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論