Skip to content

Commit

Permalink
✨ add requests to logging messages
Browse files Browse the repository at this point in the history
  • Loading branch information
bunop committed Jun 20, 2024
1 parent a5701d8 commit 04170f3
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions flask-data/smarter/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from logging.handlers import SMTPHandler

from decouple import config
from flask import Flask, redirect, url_for
from flask import Flask, redirect, url_for, has_request_context, request
from flask_restful import Api
from flask.json import JSONEncoder
from flask_cors import CORS
Expand Down Expand Up @@ -57,9 +57,24 @@
secure=()
)
mail_handler.setLevel(logging.ERROR)
mail_handler.setFormatter(logging.Formatter(
'[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
))


class RequestFormatter(logging.Formatter):
def format(self, record):
if has_request_context():
record.url = request.url
record.remote_addr = request.remote_addr
else:
record.url = None
record.remote_addr = None

return super().format(record)

formatter = RequestFormatter(
'[%(asctime)s] %(remote_addr)s requested %(url)s\n'
'%(levelname)s in %(module)s: %(message)s'
)
mail_handler.setFormatter(formatter)


class CustomJSONEncoder(JSONEncoder):
Expand Down Expand Up @@ -90,6 +105,7 @@ def create_app():

# check debug mode
if config('DEBUG', cast=bool, default=True):
# in debug mode, the default logging will be set to DEBUG level
app.debug = True

# deal with ObjectId in json responses
Expand Down

0 comments on commit 04170f3

Please sign in to comment.