Logging is generally used to debug our Python code. Many of us (like me) have a habit of using the print() function extensively during the development of a program. Nothing bad in that per se, just that when we want to promote this program to the production environment we must necessarily remove the print() statements.
There are other reasons too why the print statement is not recommended and its better to use the logging module:
- The print statement works only if we have access to the console
- We have no mechanism to write the print statements to a text file for further perusal
Python Logging Levels
Value |
Level |
Logging Function |
Description |
0 |
NOTSET |
logging.notset() |
By default, a
new logger has the NOTSET level (root logger default is WARNING) |
10 |
DEBUG |
logging.debug() |
Providing
information to diagnosing problems. |
20 |
INFO |
logging.info() |
Tracking the
normal operation of a program. |
30 |
WARNING |
logging.warning() |
Although the
code is still working as expected, something unexpected is happening |
40 |
ERROR |
logging.error() |
The code was
unable to run some parts |
50 |
CRITICAL |
logging.critical() |
The code
cannot run. |
logging.basicConfig()
logging.basicConfig(level=50)
INFO:root:Now we are at the INFO level of logging
WARNING:root:and next comes the WARNING level of logging
ERROR:root:now we are at the ERROR level of debugging
CRITICAL:root:OOPS!!! This is the CRITICAL level of logging!!!
WARNING:root:and next comes the WARNING level of logging ERROR:root:now we are at the ERROR level of debugging CRITICAL:root:OOPS!!! This is the CRITICAL level of logging!!!
Formatting the logging messages
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(filename)s - %(message)s',level=logging.ERROR)
2022-11-15 21:26:43,911 - CRITICAL - TestProgram.py - OOPS!!! This is the CRITICAL level of logging!!!
Configuring our own logger
# Handling the Logger logger = logging.getLogger(__name__) # Create the logger logger.setLevel(logging.INFO) # set logger level f = logging.Formatter('%(asctime)s - %(levelname)s - %(filename)s - %(message)s') # define the format fh = logging.FileHandler('saveToFile.log') # Set file handler fh.setFormatter(f) # Set the formatting logger.addHandler(fh) # Add filehandler to logger # Using the logger created logging.info('Now we are at the INFO level of logging')
No comments:
Post a Comment