From 1d104d06b95da36c71cab132c7b6fec52a005e18 Mon Sep 17 00:00:00 2001 From: Sebastiaan Huber Date: Sat, 29 Jun 2024 22:00:24 +0200 Subject: [PATCH] ORM: Cache the logger adapter for `ProcessNode` (#6492) The logger adapter was recreated each time the `logger` property of the `ProcessNode` was invoked. It is now created once in the `logger` property. The created logger adapter is assigned to the `_logger_adapter` attribute such that it can simply be returned at the next invocation. The initialization of the adapter cannot be done in the constructor as that route is not taken if an existing node is loaded from the database. Finally, the `logger` property only creates and returns the adapter when the node is stored. Otherwise it simply returns the base logger instance. This is because the logger adapter only works for stored nodes and if it were instantiated at the point when the node is unstored, it would not be regenerated once the node is stored, and so the `DbLogHandler` will never be able to persist log messages to the database. --- src/aiida/orm/nodes/process/process.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/aiida/orm/nodes/process/process.py b/src/aiida/orm/nodes/process/process.py index a1223a86fb..003aa231e4 100644 --- a/src/aiida/orm/nodes/process/process.py +++ b/src/aiida/orm/nodes/process/process.py @@ -251,7 +251,16 @@ def logger(self): """ from aiida.orm.utils.log import create_logger_adapter - return create_logger_adapter(self._logger, self) + # If the node is not yet stored, there is no point in creating the logger adapter yet, as the ``DbLogHandler`` + # it configures, is only triggered for stored nodes, otherwise it cannot link the log message to the node. + if not self.pk: + return self._logger + + # First time the property is called after the node is stored, create the logger adapter + if not hasattr(self, '_logger_adapter'): + self._logger_adapter = create_logger_adapter(self._logger, self) + + return self._logger_adapter @classmethod def recursive_merge(cls, left: dict[Any, Any], right: dict[Any, Any]) -> None: