Python Logging Classes and Functions
In our previous tutorials, we have already seen how we can use and configure the default logger named
root, which is mainly used by the logging module whenever we call its functions directly like this:
You can also define your own logger by creating an object of the
Logger class, especially in the case if your application has multiple modules.
Let us look at some of the classes and functions in the logging module.
The most commonly used classes which are already defined in the logging module are given below:
1. Logger class
Logger is the class whose objects will be used in the application code directly to call the functions.
The Logger class automatically create
LogRecord objects which contain the information related to the event being logged, or in simple words the log message. It contains information like the name of the logger, the function, the line number, the message, the process id, etc.
The Handlers are mainly used to send the
LogRecord to the required output destination, it can be console or a file
Handler is the base for subclasses like
HTTPHandler, and more. These subclasses also send the logging outputs to corresponding destinations, like
sys.stdout or a disk file.
The Formatter is a class where you specify the format of the output by specifying a string format that mainly lists out the attributes the output should contain.
Several Logger objects
In Logging Module items with all caps are constant, the capitalize items indicate classes, and the items which start with lowercase letters are methods. Below we have a table consisting of several logger objects offered by the Logging module:
|Logger.info(msg)||This function mainly helps to log a message with level
|Logger.warning(msg)||This function mainly helps to log a message with level WARNING on this logger.|
|Logger.error(msg)||This function mainly helps to log a message with level
|Logger.critical(msg)||This function mainly helps to log a message with level
|Logger.setLevel(lvl)||This function is mainly used to set the threshold of the logger to lvl and that indicates all the messages below this level will be ignored.|
|Logger.exception(msg)||This function mainly helps to log a message with level
|Logger.log(lvl, msg)||This function will Logs a message with integer level lvl on this logger.|
|Logger.filter(record)||This method is mainly used to apply the logger’s filter to the provided record and it will return
|Logger.addFilter(filt)||It is used to adds a specific filter
|Logger.removeFilter(filt)||It is used to adds a specific filter
|Logger.hasHandlers()||This is mainly used to check if the logger has any handler configured or not.|
|Logger.addHandler(hdlr)||In order to add a specific handler
|Logger.removeHandler(hdlr)||In order to remove a specific handler