Having good logs is crucial for monitoring applications, understanding production behavior and catching bugs. Logging in python is well made and well documented. However at times you just need to get things done quickly and you just do not have the time to read the excellent, but quite long official documentation.
Logging is important for your understanding of applications behavior, and to help IT operations to have a dedicated control panel to quickly monitor and analyze application issues.
In this article, we’ll try to figure out quick recipes to get productive with logging. Before we get started, just some basic terminology for python logging:
Without further ado, let’s just dive straight into it and get some quick recipes to get your python application logging in no time.
The fastest way to get logging done for simple applications is to use logging.basicConfig, it will create a StreamHandler (and a FileHandler if we specify the filename) and add it to the ROOT logger.
Configure it as follows:
import logging
logging.basicConfig(filename='my_log_file.log',level=logging.INFO)
Then use it as follows:
import logging
from time import sleep
def setup_logger():
logging.basicConfig(filename='my_log_file.log', level=logging.INFO)
def my_app_logic():
logging.info("Just entered the function")
sleep(0.1)
logging.info("Just after the sleep")
try:
res = 1 / 0
except ZeroDivisionError:
logging.exception("Attempted division by zero")
if __name__ == '__main__':
setup_logger()
my_app_logic()
This will result in the following output on our my_log_file.log file:
INFO:root:Just entered the function
INFO:root:Just after the sleep
ERROR:root:Attempted division by zero
Traceback (most recent call last):
File "/xxxx/simple_application.py", line 14, in my_app_logic
res = 1 / 0
ZeroDivisionError: division by zero
In case you would like to also display the time, simply add the format as follows:
logging.basicConfig(filename='my_log_file.log', format='%(asctime)s - %(message)s', level=logging.INFO)
Which will change the output messages in your log files to:
2020-07-20 17:05:29,686 - Just entered the function
2020-07-20 17:05:29,790 - Just after the sleep
2020-07-20 17:05:29,790 - Attempted division by zero
...
When to use it: Simple applications where you just need to get some logging done without too much fuzz. Minimal usage of external libraries and you do not require too much control on how logging is performed.
When not to use it: When you need fine-grained control on how logging is performed or any multi-process application.
#quick #python #logging #cheatsheet #programming