如何使用Flask dictConfig将消息记录到文件

时间:2018-03-05 06:54:20

标签: python flask

我无法使用以下代码将消息记录到Flask中的文件:

from flask import Flask,request,jsonify
import requests
import logging
from logging.config import dictConfig

app = Flask(__name__)
app.config['SECRET_KEY'] = "Secret!"

dictConfig(
            {
    'version': 1,
    'formatters': {
            'default': {
                        'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
                       },
            'simpleformatter' : {
                        'format' : '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
            }
    },
    'handlers': 
    {
        'wsgi': {
        'class': 'logging.StreamHandler',
        'formatter': 'default'
                },
        'custom_handler': {
        'class' : 'logging.FileHandler',
        'formatter': 'simpleformatter',
        'filename' : 'WARN.log'
        }
    },
    'root': {
        'level': 'INFO',
        'handlers': ['wsgi']
    },
    'MyExample': {
        'level': 'WARN',
        'handlers' : 'custom_handler'
    }
})

class InvalidUsage(Exception):
    status_code = 400

    def __init__(self, message, status_code=None, payload=None):
        Exception.__init__(self)
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_dict(self):
        rv = dict(self.payload or ())
        rv['message'] = self.message
        rv['status_code'] = self.status_code
        return rv

@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response

@app.route('/test',methods=["GET","POST"])
def test():
    url = "https://httpbin.org/status/404"
    try:
        response = requests.get(url)
        if response.status_code != 200:
            try:
                response.raise_for_status()
            except requests.exceptions.HTTPError:
                status = response.status_code
                print status
                raise InvalidUsage("An HTTP exception has been raised",status_code=status)
    except requests.exceptions.RequestException as e:
        app.logger.info("An exception has been raised")
        app.logger.info(e)
        raise InvalidUsage("request exception has been raised")

if __name__ == "__main__":
    app.run(debug=True)
    app.logger.getLogger('MyExample')

最后一行:app.logger.getLogger(' MyExample')发出错误信息说app.logger.getLogger(' MyExample')。

由于我在我的应用程序根目录和MyExample中配置了两种不同类型的记录器,我如何确保Flask应该使用MyExample记录器来记录消息。

提前感谢您的任何答案。

0 个答案:

没有答案