Coverage for .nox/test-3-9/lib/python3.9/site-packages/nskit/common/logging/library.py: 89%
37 statements
« prev ^ index » next coverage.py v7.4.2, created at 2024-02-25 17:38 +0000
« prev ^ index » next coverage.py v7.4.2, created at 2024-02-25 17:38 +0000
1"""Library Logging Factory."""
2from typing import Any, Dict, Optional, Union
4from nskit.common.logging.config import LoggingConfig
5from nskit.common.logging.formatter import get_library_log_format_string
6from nskit.common.logging.logger import get_logger
9def get_library_logger(library: str, version: str, name: str, config: Optional[Union[LoggingConfig, Dict[str, Any]]] = None, **kwargs):
10 """Get a (sub)logger for a library component, which includes the library and version."""
11 if config is None:
12 config = {'extra': {}}
13 elif isinstance(config, LoggingConfig):
14 config = config.model_dump()
15 formatstr = get_library_log_format_string(library, version)
16 library = {'name': library, 'version': version}
17 config['format_string'] = formatstr
18 config['extra'] = config.get('extra', {})
19 config['extra'].update(kwargs.pop('extra', {}))
20 config = LoggingConfig(**config)
21 if config.json_format:
22 config.extra['library'] = library
23 return get_logger(name, config, **kwargs)
26class LibraryLoggerFactory:
27 """A factory for creating multiple library loggers."""
29 def __init__(self, library: str, version: str, base_config: Optional[Union[LoggingConfig, Dict[str, Any]]] = None):
30 """Initialise the logger factory."""
31 self.__library = library
32 self.__version = version
33 self.__base_config = base_config
35 def get_logger(self, name, config=None, **kwargs):
36 """Get the library logger."""
37 if config is None:
38 config = self.__base_config
39 return get_library_logger(self.library, self.version, name, config, **kwargs)
41 def get(self, name, config=None, **kwargs):
42 """Alias for the get_logger method."""
43 return self.get_logger(name, config, **kwargs)
45 def getLogger(self, name, config=None, **kwargs):
46 """Alias for the get_logger method to provide parity with the standard logging API."""
47 return self.get_logger(name, config, **kwargs)
49 @property
50 def library(self):
51 """Return the library name."""
52 return self.__library
54 @property
55 def version(self):
56 """Return the version name."""
57 return self.__version