Last active
February 11, 2024 22:09
-
-
Save jennyd/0ac8d38167bdabb9bc07 to your computer and use it in GitHub Desktop.
Falcon logging middleware
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 | |
logger = logging.getLogger(__name__) | |
logger.addHandler(logging.FileHandler('test.log')) | |
logger.setLevel(logging.INFO) | |
class ResponseLoggerMiddleware(object): | |
def process_response(self, req, resp): | |
logger.info('{0} {1} {2}'.format(req.method, req.relative_uri, resp.status[:3])) | |
class TestResource(object): | |
def on_post(self, req, resp): | |
if req.content_type != 'application/json': | |
raise falcon.HTTPUnsupportedMediaType('JSON please!') | |
else: | |
resp.status = falcon.HTTP_201 | |
application = falcon.API(middleware=[ResponseLoggerMiddleware()]) | |
application.add_route('/test', TestResource()) |
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
$ http POST localhost:8000/test foo=bar Content-Type:application/json | |
HTTP/1.1 201 Created | |
$ http POST localhost:8000/test foo=bar Content-Type:application/xml | |
HTTP/1.1 415 Unsupported Media Type | |
# test.log | |
POST /test 201 | |
POST /test 200 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing 🙏
FYI ⬇️ is better to avoid
logging-not-lazy
.