diff --git a/config.yaml b/config.yaml index addd9d9..e21bb1e 100644 --- a/config.yaml +++ b/config.yaml @@ -10,6 +10,10 @@ app: SQLALCHEMY_DATABASE_URI: sqlite:///sqlite.db # SQLALCHEMY_DATABASE_URI: mysql://username:password@server/db + + # LOGGING_LEVEL: CRITICAL | FATAL | ERROR | WARN | WARNING | INFO | DEBUG | NOTSET + LOGGING_LEVEL: INFO + network: PROXY: http://127.0.0.1:7890 diff --git a/project/__init__.py b/project/__init__.py index 2038057..6e06d3d 100644 --- a/project/__init__.py +++ b/project/__init__.py @@ -1,7 +1,10 @@ -from flask import Flask +from flask import Flask, request from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager import yaml +import logging +import time +import traceback # init SQLAlchemy so we can use it later in our models db = SQLAlchemy() @@ -19,6 +22,7 @@ def create_app(): app.config['OPENAI_API_KEY'] = conf['openai']['API_KEY'] app.config['OPENAI_MODEL_NAME'] = conf['openai']['MODEL_NAME'] app.config['OPENAI_PROMPT'] = conf['openai']['PROMPT'] + app.config['LOGGING_LEVEL'] = conf['app']['LOGGING_LEVEL'] db.init_app(app) login_manager = LoginManager() @@ -48,3 +52,29 @@ def create_app(): app = create_app() +logger = logging.getLogger('waitress') +logger.setLevel(app.config['LOGGING_LEVEL']) + + +@app.before_request +def before_request(): + timestamp = time.strftime('[%Y-%b-%d %H:%M]') + logger.info('%s > %s %s %s %s', timestamp, request.remote_addr, + request.method, request.scheme, request.full_path) + + +@app.after_request +def after_request(response): + timestamp = time.strftime('[%Y-%b-%d %H:%M]') + logger.info('%s < %s %s %s %s %s', timestamp, request.remote_addr, + request.method, request.scheme, request.full_path, response.status) + return response + + +@app.errorhandler(Exception) +def exceptions(e): + tb = traceback.format_exc() + timestamp = time.strftime('[%Y-%b-%d %H:%M]') + logger.error('%s %s %s %s %s 5xx INTERNAL SERVER ERROR\n%s', timestamp, + request.remote_addr, request.method, request.scheme, request.full_path, tb) + return e.status_code