Adding A Logging Middleware To A Robyn App | Python

Photo by Splash Pic on Unsplash

Adding A Logging Middleware To A Robyn App | Python

In this article we are going to build a logging middleware with Robyn. So, every time a request is made to the server, it will show the log in our console.

The scoop of this article is not to create a robust and complete logging system, but a simple logging middleware for learning purpose.

Requirements

  • Python 3 installed

  • Pip installed

Creating the Middleware

We create a new python project as usual:

mkdir robbyn-logging
py -m venv venv
#Windows
cd venv/Scripts
./activate

#Linux
$ source venv/bin/activate

pip install robyn

First, we are going to create a middleware class with the attributes of the request information and the response information.

The request information will show the IP address, path, URL, HTTP method and request time. The response information, will show the status code, and the response type.

Let's start with the middleware that shows the request information.

app.py

from robyn import Robyn, Request, Response
from robyn.logger import Logger
from datetime import datetime
app = Robyn(__file__)

logger = Logger()

class LoggingMiddleware:

    def request_info(request: Request):
        ip_address = request.ip_addr
        request_url = request.url.host
        request_path = request.url.path
        request_method = request.method
        request_time = str(datetime.now())


        return {
            "ip_address": ip_address,
            "request_url": request_url,
            "request_path": request_path,
            "request_method": request_method,
            "request_time": request_time,

        }

In the app.py file, we import and create an instance of the Robyn class. Then, we create the LoggingMiddleware class with the request_info method, which returns the attributes of the request.

Now, let's add a route to make a request. And use before_request() method, which registers a function that runs before each request.

...
@app.before_request()
def log_request(request: Request):

    logger.info(f"Received request: %s", 
        LoggingMiddleware.request_info(request))

    return request

@app.get("/")
def h():
    return "Hello, World!"

app.start(port=8080)

Now, we restart the server and make a request to localhost:8080/ to see the response in the console.

Let's go with response data.

We add another method to the LoggingMiddleware class, but this one is with the response information.

class LoggingMiddleware:

...

    def response_info(response: Response):
        status_code = response.status_code
        response_type = response.response_type

        return {
            "status_code": status_code,
            "response_type": response_type
        }

Next, use the after_request() method to register the log_response() function. This function will show the status code of the response, and the response type.

The after_request() method register a function that runs after a request.

...
@app.after_request()
def log_response(response: Response):

    logger.info(f"Sending response: %s", 
        LoggingMiddleware.response_info(response))
    return response

@app.get("/")
def h():
    return "Hello, World!"

app.start(port=8080)

Now, we restart the server and make a request to localhost:8080/ to see the response in the console.

Complete code

from robyn import Robyn, Request, Response
from robyn.logger import Logger
from datetime import datetime
app = Robyn(__file__)

logger = Logger()

class LoggingMiddleware:

    def request_info(request: Request):
        ip_address = request.ip_addr
        request_url = request.url.host
        request_path = request.url.path
        request_method = request.method
        request_time = str(datetime.now())

        return {
            "ip_address": ip_address,
            "request_url": request_url,
            "request_path": request_path,
            "request_method": request_method,
            "request_time": request_time,

        }

    def response_info(response: Response):
        status_code = response.status_code
        response_type = response.response_type

        return {
            "status_code": status_code,
            "response_type": response_type
        }


@app.before_request()
def log_request(request: Request):

    logger.info(f"Received request: %s", 
        LoggingMiddleware.request_info(request))

    return request

@app.after_request()
def log_response(response: Response):

    logger.info(f"Sending response: %s", 
        LoggingMiddleware.response_info(response))
    return response

@app.get("/")
def h():
    return "Hello, World!"

app.start(port=8080)

Conclusion

My intention in this article was not to make a robust logging system or feature, but to show how to use the middleware feature of Robyn to create a simple logging middleware.

Thank you for taking the time to read this article.

If you have any recommendations about other packages, architectures, how to improve my code, my English, or anything; please leave a comment or contact me through Twitter, or LinkedIn.

Resources

Robyn Documentation