1. Application Endpoints and Logging
Note
Make sure you have prepared the environment for this task.
Solution 1.1 - Extend Application Endpoints
To extend Python Flask application with /status
and /metrics
endpoints, follow these steps:
Open
app.py
file inexercises/python-helloworld
folder.Register routes
"/status"
and"/metrics"
to the app route.Add the logic to those routes, according to the examples below:
@app.route("/status")
def status():
response = app.response_class(
response=json.dumps({"result": "OK - healthy"}),
status=200,
mimetype="application/json"
)
return response
@app.route("/metrics")
def metrics():
response = app.response_class(
response=json.dumps(
{
"status": "success",
"code": 0,
"data": {"UserCount": 140, "UserCountActive": 23}
}
),
status=200,
mimetype="application/json"
)
return response
Watch the video to understand the API Endpoints solution in more detail.
Solution 1.2 - Implement Application Logging
For log messages Flask uses standard Python logging
library. In Flask it implemented within app.logger
method,
which can be used in the same way and allow you to handle your own masseges.
To add basic logging functionality to your Flask application follow the next steps:
Open
app.py
file inexercises/python-helloworld
folder.Import
logging
library.Add log collection logic for each route you want to track:
@app.route("/metrics")
def metrics():
...
app.logger.info("Metrics request successfull.")
Add logging configuration to main function to save the logs in a file:
if __name__ == "__main__":
logging.basicConfig(
filename="app.log",
level=logging.DEBUG,
format="%(levelname)s:%(asctime)s:%(name)s:%(message)s",
)
app.run(host="0.0.0.0")
Watch the video to understand the logging basics in more detail.
Note
In this tutorial, we discover the very basics of logging. The complete solution code is in solutions/python-helloworld/app.py. To improve the app logging facility and create a more sophisticated solution explore the additional materials for the exercise.