Logging performance metrics

Inside an application, there could be several steps. Each of these steps can be profiled for their performance through the use of different tools. One of the most basic tools is logging. In this, we collect the execution time of the different methods and keep the entry for it inside the log file.

The following snippet of code shows a small example of how this can be achieved inside the demo application that we built in Chapter 6Example – Building BugZot:

@app.before_request
def before_request_handler():
g.start_time = time.time()

@app.teardown_request
def teardown_request_handler(exception=None):
execution_time = time.time() - g.start_time
app.logger.info("Request URL: {} took {} seconds".format(request.url, str(execution_time)))

This was a simple code and logs the execution time of every API endpoint called in a request. What we do here is very minimalistic. We first create a before_request handler, which initializes a property, start_time, in the flask global namespace. Once this is done, the request is sent to processing. Once the request has been processed, it goes to the teardown handler that we have defined.

Once the request reaches this teardown handler, we calculate the total time it took to process the request and log it inside the application logs.

This kind of approach allows us to query or process our log files to understand how much time every request is taking and which API endpoints are taking the longest amount of time.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.91.254