Python allows decent built-in logging. As I am going to explain in the video below, the built-in logging is actually rather neat – it allows everyone to log into a file or into the console within minutes – just the time needed to write a few lines of code.
Now, the MCE for logging looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import logging logger = logging.getLogger("__name__") logger.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s [%(levelname)s] - %(name)s - %(message)s") file_handler = logging.FileHandler("file.log") file_handler.setFormatter(formatter) logger.addHandler(file_handler) def log_some_records(): logger.info("App is strating...") logger.error("Failed to save to the db...") logger.debug("User is username") logger.warning("Just a warning!") logger.info("Created task") log_some_records() |
With the code above, we create a logger object and we ask it to kindly format the output as per the formatter. Then it is forced to write into a file.log, that is created (if not present) in the same folder, as the file in which the code is written. This is how the logfile looks like, if you are using fancy editor like PyCharm Community:
In general, we have 5 types of common handlers, that can be attached to a logger:
- StreamHandler
- Send events to the console.
- FileHandler
- Save events to a file.
- SMTPHandler
- Send events to an email address.
- HTTPHandler
- Send events to a web server.
- QueueHandler
- Send events to a different thread.
Additionally, there are 5 different levels of logging with different usage. The idea is that you can select which level you are interested in. In that case it only logs events for that level and above:
- CRITICAL – 50 – Serious errors in core functionalities
- ERROR – 40 – Errors in some functionalities
- WARNING – 30 – Unexpected behaviors that can lead to errors, (usually an information for usage of an old, obsolete library)
- INFO – 20 – Informational for expected behaviors
- DEBUG – 10 – For diagnosis of problem, turn this one on to see everything
The rest of the code that I have used for the YouTube video is this one:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import logging class Task: def __init__(self, title): self.title = title def remove_from_db(self): task_removed = True return task_removed logger = logging.getLogger(__name__) file_handler = logging.FileHandler("file.log") logger.addHandler(file_handler) task = Task("Laundry") if task.remove_from_db(): logger.warning(f"removed the task {task.title} from the db") # print(f"removed the task {task.title} from the db") def check_log_content(filename): with open(filename) as file: return file.read() stream_handler = logging.StreamHandler() logger.addHandler(stream_handler) logger.warning("Just a random event") log_records = check_log_content(filename="file.log") # print(log_records) logger.setLevel(logging.WARNING) # print(logger.level, logging._levelToName[logger.level]) logger.setLevel(logging.DEBUG) print(logger.level, logging._levelToName[logger.level]) logger.handlers = [] |
The YouTube video is below. The most of the code, came from the book: “Python How-To 63 techniques to improve your Python code” https://www.manning.com/books/python-… (http://mng.bz/XNO6) If you are interested in the books, then discount code for all manning books (40%) is here: watchcui40.
Enjoy! 🙂