Logging (After Hooks)

After hooks are defined similarly but are used to modify the response:

Setting Up Logging:

Python
import falcon
import logging 

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
  • This sets up basic logging configuration with the log level set to INFO.
  • logger is an instance of a logger to log messages.

Defining the After Hook:

Python
def add_custom_header(req, resp, resource, req_succeeded):
    logger.info(f"Processing {req.method} request for {req.path}")
    resp.set_header('X-Custom-Header', 'CustomValue')
  • add_custom_header is a function that constructs a log message using the request method, the requested URI, and the response status.
  • The log message is then logged using logger.info.

Creating the Resource with Request Handlers:

Python
class ResourceWithAfterHook:
    @falcon.after(add_custom_header)
    def on_get(self, req, resp):
        logger.info("Handling GET request")
        resp.media = {'message': 'Response with a custom header!'}

    @falcon.after(add_custom_header)
    def on_post(self, req, resp):
        logger.info("Handling POST request")
        resp.media = {'message': 'Data received with a custom header!'}

ResourceWithAfterHook is a resource class with two methods:

  • on_get: Handles GET requests and responds with a JSON message.
  • on_post: Handles POST requests and responds with a JSON message.

The @falcon.after(add_custom_header) decorator applies the add_custom_header hook to both methods.

Setting Up the Falcon API and Adding the Route:

Python
app = falcon.App()
app.add_route('/custom', ResourceWithAfterHook())


Running the Application:

Python
if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    with make_server('', 8000, app) as httpd:
        print('Serving on port 8000...')
        httpd.serve_forever()

This block of code checks if the script is being run directly.

It uses Python’s built-in WSGI server to serve the Falcon application on port 8000.

Testing the After Hook

To test the application and see the logging in action, you can use curl or any other HTTP client:

GET Request

curl -i http://localhost:8000/custom

POST Request

curl -i -X POST http://localhost:8000/custom

Python Falcon – Hooks

In Falcon, hooks are type of callbacks that are defined by the user and are executed before or after a responder method in a particular resource class to process client request. They are useful in as much as they allow a client to add or overwrite request processing functionality at certain predefined stages.

Similar Reads

Understanding Hooks in Python Falcon

Falcon offers two types of hooks:...

Using Hooks

Falcon provides two decorators, @falcon.before and @falcon.after, for hanging callbacks on responder methods, or indeed on whole classes of resources. The arguments passed to hook functions include:...

Example: Authentication Hook

Let’s create a simple example where we use a before hook to check for an authentication token in the request headers....

Testing the Hook

Let’s test our before hook using curl:...

Example: Logging (After Hooks)

After hooks are defined similarly but are used to modify the response:...

Advanced Hook Usage

Multiple Hooks...

Common Use Cases for Falcon Hooks

Authentication and Authorization:...