Detecting problems through logs
For any problem in a running system, there are two kind of errors that can occur: expected and unexpected. In this section, we will see the differences between them in terms of logs and how we handle them.
Detecting expected errors
Expected errors are errors that are detected explicitly by creating an ERROR
log in the code. For example, the following code produces an ERROR
log when the accessed URL returns a status code different from 200 OK
:
import logging
import requests
URL = 'https://httpbin.org/status/500'
response = requests.get(URL)
status_code = response.status_code
if status_code != 200:
logging.error(f'Error accessing {URL} status code {status_code}')
This code, when executed, triggers an ERROR
log:
$ python3 expected_error.py
ERROR:root:Error accessing https://httpbin.org/status/500 status code 500
This is a common pattern to access an external URL and validate that it has been accessed correctly...