Skip to content

Commit

Permalink
ORM: Cache the logger adapter for ProcessNode
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
sphuber committed Jun 28, 2024
1 parent 737da38 commit ea88d34
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/aiida/orm/nodes/process/process.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
###########################################################################
"""Module with `Node` sub class for processes."""

from __future__ import annotations

import enum
import logging
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, Union

from plumpy.process_states import ProcessState
Expand Down Expand Up @@ -163,6 +166,11 @@ class ProcessNode(Sealable, Node):

_unstorable_message = 'only Data, WorkflowNode, CalculationNode or their subclasses can be stored'

# This is set on the instance the first time the ``logger`` property is called. It cannot be initialized in the
# constructor because that would not go for instances that are loaded from the database which do not pass through
# the constructor.
_logger_adapter: logging.LoggerAdapter | None = None

def __str__(self) -> str:
base = super().__str__()
if self.process_type:
Expand Down Expand Up @@ -251,7 +259,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 only is 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 self._logger_adapter is None:
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:
Expand Down

0 comments on commit ea88d34

Please sign in to comment.