Last active
August 5, 2020 21:46
-
-
Save smoeinbbp/6c2bc462c77e9f227ef27d31247801a6 to your computer and use it in GitHub Desktop.
Logger middleware for Falcon
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import falcon | |
import logging | |
import time | |
import json | |
from uuid import uuid4 | |
logger = logging.getLogger(__name__) | |
logger.setLevel(logging.INFO) | |
handler = logging.FileHandler(filename='app.log', encoding='utf-8') | |
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S') | |
handler.setFormatter(formatter) | |
logger.addHandler(handler) | |
class ResponseLoggerMiddleware(object): | |
def process_response(self, req, resp, resource, req_succeeded): | |
log = { | |
"reqId": str(uuid4()), | |
"time": time.time(), | |
"host": req.host, | |
"method": req.method, | |
"uri": req.relative_uri, | |
"reqHeaders": req.headers, | |
"reqBody": req.media, | |
"respBody": json.loads(resp.body) if resp.body else None, | |
"status": resp.status[:3], | |
} | |
if req_succeeded: | |
logger.info(json.dumps(log, ensure_ascii=False)) | |
else: | |
logger.error(json.dumps(log, ensure_ascii=False)) | |
# Add this middleware to your Falcon app's middlewares | |
app = falcon.API(middleware=[ | |
ResponseLoggerMiddleware(), | |
]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment