Overview:
- The Logger class in Python implements logging functions, which can be used by Python Developers.
- There are methods in Logger class for most common severity levels of log entries used by developers. They are
debug()
info()
warning()
error()
critical()
- The logger class can be instantiated using the
getlogger()
method of logging module.
- Python using names given by developers maintains the logger instances.
- When no name is passed to the
getlogger()
method, a logger object with name root is returned.
- Though any meaningful name can be passed inside the
getlogger()
method, the recommended way is to pass the current module name by callinggetLogger()
with the parameter__name__
. This will create loggers with the Python package hierarchy and the module name.
- To set the log level the
logging.basicConfig
method to be used passing the log level constants defined.
- The log levels defined in Python are given in the below table:
Log level |
Numeric value |
NOTSET |
0 |
DEBUG |
10 |
INFO |
20 |
WARNING |
30 |
ERROR |
40 |
CRITICAL |
50 |
Example – Logging using logger class in Python:
import logging
# Set log level to DEBUG logging.basicConfig(level=logging.DEBUG) logr = logging.getLogger(__name__)
# All the messages will be logged as log level is DEBUG logr.debug("Debug Msg") logr.info("Info Msg") logr.warning("Warning Msg") logr.error("Error Msg") logr.critical("Critical Msg") |
Output – Sample log printed to stderr – i.e., Console:
DEBUG:__main__:Debug Msg INFO:__main__:Info Msg WARNING:__main__:Warning Msg ERROR:__main__:Error Msg CRITICAL:__main__:Critical Msg |