5 – five-minute introduction to the module logging Python

The use of pirnt is suitable for those programmers who have enough time. But it’s better to use logging. In addition, learn to use the Python debugger for debugging errors and Pylint to prevent errors and to make the code more readable.
In order to display the log messages on the screen, use the following code:

import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('This is a log message.')

In order to write logs to a file, this code is suitable (the difference from the previous version is highlighted in bold):

import logging
logging.basicConfig(filename='log_filename.txt',level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('This is a log message.')

The next program start will add log messages to the end of the log file, and not overwrite it.
In order to display messages and write them to a file, use this code:

import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')

fh = logging.FileHandler('log_filename.txt')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logger.addHandler(fh)

ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
logger.addHandler(ch)logger.debug('This is a test log message.')

Make sure that the variable logging is global, so that all functions can be seen by it (gloval logger is not needed, since this variable is read-only, not for writing and changing).
Logging levels, from more urgent to less urgent:

CRITICAL
ERROR
WARNING
INFO
DEBUG

The setLevel () call sets the minimum level of logging you need. For example, if you use fh.setLevel (logging.ERROR), then messages with a level of WARNING, INFO and DEBUG will not be written to the file (since fh is the log file handler in our example, unlike ch, which processes logs For display on the screen).
To record messages of different levels, use:

logger.critical('This is a critical message.')
logger.error('This is an error message.')
logger.warning('This is a warning message.')
logger.info('This is an informative message.')
logger.debug('This is a low-level debug message.')

In fact, you can do much more, but that’s all you need to know to no longer use print to debug programs.
The Python documentation has more information, including the Basic Guide, an advanced guide, and a book of recipes for logging.
In addition, the function pprint.pprint () is good for displaying dictionaries and lists, especially nested ones. Try and see.

Scroll to top