How it works...

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.

The __name__ variable is set automatically by the Python interpreter at module-import time, and its value is the full name of the module. Since Odoo does a little trick with the imports, the add-on modules are seen by Python as belonging to the odoo.addons Python package. So, if the code of the recipe is in my_library/models/book.py, the __name__ will be odoo.addons.my_library.models.book.

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset