Skip to content

Instantly share code, notes, and snippets.

@UBarney
Forked from ivanleoncz/flask_app_logging.py
Created June 28, 2017 06:14
Show Gist options
  • Save UBarney/f5ac086d3521b131a0cd0a6ff3bc82f0 to your computer and use it in GitHub Desktop.
Save UBarney/f5ac086d3521b131a0cd0a6ff3bc82f0 to your computer and use it in GitHub Desktop.
Logging every request received from Flask.
#/usr/bin/python
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, request, jsonify
from time import strftime
import traceback
app = Flask(__name__)
@app.route("/")
def get_index():
return "Welcome to the Python Flask's Index! "
@app.route("/hello")
def get_hello():
return "Hello! "
@app.route("/json")
def get_json():
data = {
"Name":"Ivan Leon",
"Age":"27",
"Books":"[Crime and Punishment, The Gambler, The Prophet]"
}
return jsonify(data_WRONG) # Intentional non-existent variable.
@app.after_request
def after_request(response):
timestamp = strftime('[%Y-%b-%d %H:%M]')
logger.error('%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 = 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
if __name__ == '__main__':
handler = RotatingFileHandler('app.log', maxBytes=100000, backupCount=3)
logger = logging.getLogger('tdm')
logger.setLevel(logging.ERROR)
logger.addHandler(handler)
app.run()
#
# app.log
#
# [2016-Sep-02 11:26] 127.0.0.1 GET http /? 200 OK
# [2016-Sep-02 11:26] 127.0.0.1 GET http /hello? 200 OK
# [2016-Sep-02 11:26] 127.0.0.1 GET http /ivan? 404 NOT FOUND
# [2016-Sep-02 11:26] 127.0.0.1 GET http /json? 5xx INTERNAL SERVER ERROR
# Traceback (most recent call last):
# File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
# rv = self.dispatch_request()
# File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request
# return self.view_functions[rule.endpoint](**req.view_args)
# File "run.py", line 25, in get_json
# return jsonify(data_WRONG) # INTENTIONAL ERROR FOR TRACEBACK EVENT
# NameError: global name 'data_WRONG' is not defined
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment