var/opt/nydus/ops/primordial/log/extra.py000064400000005167147205527260014544 0ustar00# -*- coding: utf-8 -*- import abc import logging.config from typing import Any, Dict, Optional # pylint: disable=W0611 from primordial.log.envelopedata import EnvelopeRole LOG = logging.getLogger(__name__) # Abstract Factory class class LogExtra(metaclass=abc.ABCMeta): """Abstract Base Class that provides a set of methods for extraction, setting and retrieval of 'extra' log data.""" EXTRA_FIELD = 'extra' def __init__(self, **kwargs: str) -> None: self.extra = {} # type: Dict[str, Any] self.set(**kwargs) @staticmethod def getLogExtra(**kwargs: str) -> 'LogExtra': """Factory method to create a new LogExtra instance.""" # Default role to 'DEVELOPMENT' role = EnvelopeRole.DEFAULT_ROLE if EnvelopeRole.ROLE_FIELD in kwargs: role = kwargs[EnvelopeRole.ROLE_FIELD] if role == EnvelopeRole.ROLE_DEVELOPMENT: return DevLogExtra(**kwargs) if role == EnvelopeRole.ROLE_BUSINESS_ANALYTICS: return BALogExtra(**kwargs) if role == EnvelopeRole.ROLE_PERFORMANCE: return PerfLogExtra(**kwargs) raise ValueError("Invalid role " + role) def set(self, **kwargs: str) -> None: """Set fields on a LogExtra instance.""" for k, v in kwargs.items(): if k is not EnvelopeRole.ROLE_FIELD: self.setField(k, v) def setField(self, field: str, value: Any) -> None: """Set an individual field's value. :param field: The field to be set :param value: The value of the field """ self.extra[field] = value def get(self, field: Optional[str] = None) -> Any: if field is None: # Return 'extra' dict in format required for logger return {'extra': self.extra} if field in self.extra: # Return particular field from 'extra' dict return self.extra[field] return None class DevLogExtra(LogExtra): """Log extra data for development.""" def __init__(self, **kwargs: str) -> None: super().__init__(**kwargs) self.extra[EnvelopeRole.ROLE_FIELD] = EnvelopeRole.ROLE_DEVELOPMENT class BALogExtra(LogExtra): """Log extra data for business analytics.""" def __init__(self, **kwargs: str) -> None: super().__init__(**kwargs) self.extra[EnvelopeRole.ROLE_FIELD] = EnvelopeRole.ROLE_BUSINESS_ANALYTICS class PerfLogExtra(LogExtra): """Log extra data for performance data.""" def __init__(self, **kwargs: str) -> None: super().__init__(**kwargs) self.extra[EnvelopeRole.ROLE_FIELD] = EnvelopeRole.ROLE_PERFORMANCE