In this section, we will learn about the logging and warnings modules of Python. The logging module will keep a track of events occurring within a program. The warnings module warns the programmers about the changes made in the language as well as the libraries.
Now, we are going to see a simple logging example. We will write a script called logging_example.py and write the following code in it:
import logging
LOG_FILENAME = 'log.txt'
logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG,)
logging.debug('This message should go to the log file')
with open(LOG_FILENAME, 'rt') as f:
prg = f.read()
print('FILE:')
print(prg)
Run the program as follows::
$ python3 logging_example.py
Output:
FILE:
DEBUG:root:This message should go to the log file
Check hello.py and you see the debug message printed in that script:
$ cat log.txt
Output:
DEBUG:root:This message should go to the log file
Now, we will write a script called logging_warnings_codes.py and write the following code in it:
import logging
import warnings
logging.basicConfig(level=logging.INFO,)
warnings.warn('This warning is not sent to the logs')
logging.captureWarnings(True)
warnings.warn('This warning is sent to the logs')
Run the script as follows:
$ python3 logging_warnings_codes.py
Output:
logging_warnings_codes.py:6: UserWarning: This warning is not sent to the logs
warnings.warn('This warning is not sent to the logs')
WARNING:py.warnings:logging_warnings_codes.py:10: UserWarning: This warning is sent to the logs
warnings.warn('This warning is sent to the logs')