Logs are very important when debugging any issue. So, how do you do it in Python correctly?
First off, there are multiple log levels that you need to know.
There are 5 different log levels, we’ll go through them in increasing order of severity.
Debug - Imported Pandas module
Info - “Connection successfully established!”
Warning - This version of module - 1.01 has been deprecated. Please use version 1.02"
Error - Failed to establish connection. Rolling back to previous snapshot 1.4"
Critical - Failed to establish a connection. Rolling back to the previous snapshot 1.4 FAILED. Exiting program"
There are some powerful modules that deal with logging in python. In this shot, we’ll look at the
logging module from python. Its simple to use the logging module:
import logging logging.debug("debug statement") logging.info("info statement") logging.warning("warning statement") logging.error("error statement") logging.critical("critical statement")
But, for a more pythonic way, use the
basicConfig() function like this:
import logging logging.basicConfig(level=logging.DEBUG) logging.debug('Define your debug statement here')
Next, if you are working on huge server workloads, I would suggest using the log handlers from python. Here is a snippet that will help you to write the logs to a different file after it reaches a max capacity of 20 bytes.
import logging from logging.handlers import RotatingFileHandler logger = logging.getLogger("Rotating Log") log_handler = RotatingFileHandler(path, maxBytes=20, backupCount=5) logger.addHandler(log_handler)
Until next time! Cheers. :)
View all Courses