Step 1 imports the module logging 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 a common idiom in Odoo using the __name__ automatic variable for the logger name and calling the logger _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. 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 only if the log has to be produced. If you are running with log level of INFO, then DEBUG logs will avoid doing the substitution that is CPU consuming in the long run.
Another useful method shown in the 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.