Python has a logging module in the standard library that provides a compact framework for exhale log messages from python programs.This module is broadly used by many libraries and is the first go-to point for most developers when it comes to logging.
The basic functionality defined by the module are shown in below.
- loggers display the interface that code of application directly uses
- handlers send the log records to the proper destination.
- filters gives a cool facilities like which log records to output.
- formatters define the layout of log records in the final output.
Objects Of Logger
Loggers build Log Record object automatically this objects have all the information related to logged, like the logger name, function, line number, messages, and lot more.
Note: Loggers never instantiated directly, but always over the module-level function logging.getLogger(name)
.
The logging method in Python is a very powerful method that is designed for beginners as well as company developer. It’s used by the third-party Python libraries, so you can integrate your log messages with your code.
Import the python package for log :
import logging
Logging Levels :
- DEBUG
- INFO
- WARNING
- ERROR
- CRITICAL
The logging module gives you a default logger that allows you to create your own log with messages. This methods for every level can be write as shown in the example:
import logging
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')
Output of the above program :
WARNING:root:This is a warning message ERROR:root:This is an error message CRITICAL:root:This is a critical message
here, the debug() and info() messages did not logged. because, by default, the logging module logs the messages with a severity level of warning or above. You can change that by configuring the logging module to log events of all levels if you want. You can also define your own severity levels by changing configurations, but it is generally not recommended as it can cause confusion with logs of some third-party libraries that you might be using.