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 |
Thanks for sharing 🙏
FYI ⬇️ is better to avoid logging-not-lazy
.
logger.info('%s %s %s', req.method, req.relative_uri, resp.status[:3])
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i was trying to add a logger in the process_request method of interceptor. But logger.info() is not writing to the configured log file, but there are no exceptions or errors. Not just that, logger is working perfectly in the rest of the code. Is there any reason or explanation for this? Thanks Ranjith~