This page looks best with JavaScript enabled

Python Log Files

 ·  🎃 kr0m

When programming in Python, it is very important to be able to save information in log files, whether it is debug information from the script itself or information that we want to preserve to be consulted later. In this article, I will explain how to generate log files using logging.

Let’s write a small script as an example. First, we will enable the log, then disable it, and finally log a couple of variables to make the example more complete:

import logging
logging.basicConfig(filename='app.log', filemode='w', format='%(asctime)s - %(levelname)s - %(message)s')

logger = logging.getLogger()
logger.warning('This will get logged to a file')

logger.disabled = True
logger.warning('Disabled message')

logger.disabled = False
logger.warning('Renabled message')

var = 'AAA'
var2 = 'BBB'
logger.error('Variable values: %s - %s', var, var2)

We can see the log file:

cat app.log

2019-10-23 22:58:53,030 - WARNING - This will get logged to a file
2019-10-23 22:58:53,031 - WARNING - Renabled message
2019-10-23 22:58:54,040 - ERROR - Variable values: AAA - BBB
If you liked the article, you can treat me to a RedBull here