How it works...

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.

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 addon modules are seen by Python as belonging to the odoo.addons Python package. So, if the code of the recipe is in my_module/models/book.py, __name__ will be odoo.addons.my_module.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. 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.

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

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