Skip to content

Instantly share code, notes, and snippets.

@alexaleluia12
Last active March 19, 2024 13:49
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save alexaleluia12/e40f1dfa4ce598c2e958611f67d28966 to your computer and use it in GitHub Desktop.
Save alexaleluia12/e40f1dfa4ce598c2e958611f67d28966 to your computer and use it in GitHub Desktop.
Flask Logging (every request)
#/usr/bin/python
# http://exploreflask.com/en/latest/views.html
# https://stackoverflow.com/questions/51691730/flask-middleware-for-specific-route
# https://dev.to/rhymes/logging-flask-requests-with-colors-and-structure--7g1
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, Twenty Thousand Leagues Under The Sea]"}
return jsonify(data_WRONG) # INTENTIONAL ERROR FOR TRACEBACK EVENT
@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
#
@tarskiandhutch
Copy link

This is a really nice example. One note is I would assume you'd want to use a Python Logger method other than error() in the after_request() function. Otherwise, depending on your environment, you'll see ERROR:tdm: prepended to every single log statement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment