Logging

Logging (https://docs.python.org/3/library/logging.html) helps with troubleshooting a problem. It helps with determining the root cause of a problem by tracing back through the sequence of events logged by the application. Let's review logging using a simple application. In order to review logging, let's review it by making a POST request:

  1. The first step in logging is setting the log file location and the log level:
       logging.basicConfig(format='%(asctime)s : %(levelname)s :
%(message)s', filename='log_file.log', level=logging.INFO)

While initializing the logging class, we need to specify the format for logging information, errors, and so on to the file. In this case, the format is as follows:

       format='%(asctime)s : %(levelname)s : %(message)s'

The log messages are in the following format:

       2016-10-25 20:28:07,940 : INFO : Starting new HTTPS
connection (1):
maker.ifttt.com

The log messages are saved to a file named log_file.log.

The logging level determines the level of logging needed for our application. The different log levels include DEBUG, INFO, WARN, and ERROR.

In this example, we have set the logging level to INFO. So, any log message belonging to INFO, WARNING, or ERROR levels are saved to the file.

If the logging level is set to ERROR, only those log messages are saved to the file.

  1. Let's log a message based on the outcome of the POST request:
       response = requests.post(IFTTT_URL, json=payload) 
if response.status_code == 200:
logging.info("Notification successfully triggered")
else:
logging.error("POST request failed")
  1. Putting it all together, we have this:
       #!/usr/bin/python3 

import requests
import logging

# find your key from ifttt
IFTTT_URL = "https://maker.ifttt.com/trigger/rf_trigger/
with/key/$key"

if __name__ == "__main__":
# fetch the bike share information
logging.basicConfig(format='%(asctime)s : %(levelname)s
: %(message)s', filename='log_file.log', level=logging.INFO)
payload = {"value1": "Sample_1", "value2": "Sample_2"}
response = requests.post(IFTTT_URL, json=payload)
if response.status_code == 200:
logging.info("Notification successfully triggered")
else:
logging.error("POST request failed")

The preceding code sample (logging_example.py) is available for download along with this chapter. This is a very soft introduction to the concept of logging in Python.