Step 1 imports the logging module from the Python standard library. Odoo uses this module to manage its logs.
Step 2 sets up a logger for the Python module. We use the common idiom __name__ in Odoo as an automatic variable for the name of the logger and to call the logger by _logger.
By doing this, we get two benefits:
- The global logging configuration set on the odoo logger is applied to our logger because of the hierarchical structure of loggers in the logging module.
- The logs will be prefixed with the full module path, which is a great help when trying to find where a given log line is produced.
Step 3 uses the logger to produce log messages. The available methods for this are (by increasing log level) debug, info, warning, error, and critical. All these methods accept a message in which you can have % substitutions and additional arguments to be inserted into the message. You should not do the % substitution yourself; the logging module is smart enough to perform this operation if the log has to be produced. If you are running with a log level of INFO, then DEBUG logs will avoid substitutions that will consume CPU in the long run.
Another useful method shown in this recipe is _logger.exception(), which can be used in an exception handler. The message will be logged with a level of ERROR, and the stack trace is also printed in the application log.