Skip to content

Instantly share code, notes, and snippets.

@jennyd
Last active February 11, 2024 22:09
Show Gist options
  • Save jennyd/0ac8d38167bdabb9bc07 to your computer and use it in GitHub Desktop.
Save jennyd/0ac8d38167bdabb9bc07 to your computer and use it in GitHub Desktop.
Falcon logging middleware
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())
$ 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
@marians
Copy link

marians commented Aug 8, 2017

With current falcon, it seems the signature for process_response has to be

def process_response(self, req, resp, resource, req_succeeded):

@ranjith1976
Copy link

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~

@davetapley
Copy link

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