Introduction to Logging in Python¶
Medium Link: https://medium.com/p/a1415d0b8141¶
import logging
Logging Levels¶
Level |
Value |
---|---|
CRITICAL |
50 |
ERROR |
40 |
WARNING |
30 |
INFO |
20 |
DEBUG |
10 |
The default level is WARNING
, which means only the events of this level and above will be logged.
import logging
logging.debug('Debug message')
logging.info('Info message')
logging.warning('Warning message')
logging.error('Error message')
logging.critical('Critical message')
Output:
WARNING:root:Warning message
ERROR:root:Error message
CRITICAL:root:Critical message
Change Logging Level¶
To change the level of the logger, pass the level
argument for basicConfig()
import logging
logging.basicConfig(level=logging.INFO)
logging.debug('Debug message')
logging.info('Info message')
logging.error('Error message')
Output:
INFO:root:Info message
ERROR:root:Error message
Log to a file¶
To log the messages to a file, simply pass the name of the file in the filename
parameter of the basicConfig()
import logging
logging.basicConfig(filename='sample.log', level=logging.INFO)
logging.debug('Debug message')
logging.info('Info message')
logging.error('Error message')
The contents of the file would be:
INFO:root:Info message
ERROR:root:Error message
Change logging Format¶
To change the default format, we need to specify the format
parameter in the basicConfig()
FORMAT = '%(asctime)s:%(name)s:%(levelname)s - %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)
logging.info('Info message')
The corresponding output would be:
2020-07-03 00:48:00,106:root:INFO - Info message
Change date format¶
To change the date format displayed in the logs, we need to change the datefmt
parameter
FORMAT = '%(asctime)s:%(name)s:%(levelname)s - %(message)s'
logging.basicConfig(format=FORMAT,
level=logging.INFO,
datefmt='%Y-%b-%d %X%z')
logging.info('Info message')
Output:
2020-Jul-03 00:56:31+0530:root:INFO - Info message
Logging for exceptions¶
Example-1: with logging.error¶
try:
5/0
except:
logging.error('Exception occured')
Output:
ERROR:root:Exception occured
Example-2: with logging.error and exc_info=True¶
try:
5/0
except:
logging.error('Exception occured', exc_info=True)
Output:
ERROR:root:Exception occured
Traceback (most recent call last):
File "<ipython-input-2-933e0f6b1879>", line 11, in <module>
5/0
ZeroDivisionError: division by zero
Example-3: with logging.exception¶
try:
5/0
except:
logging.exception('Exception occured')
Output:
ERROR:root:Exception occured
Traceback (most recent call last):
File "<ipython-input-3-e7d1d57e6056>", line 11, in <module>
5/0
ZeroDivisionError: division by zero