diff --git a/testing/mozbase/docs/mozlog.rst b/testing/mozbase/docs/mozlog.rst index 7c02ae0ccf59..db26c78b03d7 100644 --- a/testing/mozbase/docs/mozlog.rst +++ b/testing/mozbase/docs/mozlog.rst @@ -210,6 +210,33 @@ StructuredLogger Objects .. autoclass:: StructuredLogFileLike :members: +ProxyLogger Objects +------------------- + +Since :func:`mozlog.structuredlog.get_default_logger` return None when +the default logger is not initialized, it is not possible to directly +use it at the module level. + +With ProxyLogger, it is possible to write the following code: :: + + from mozlog import get_proxy_logger + + LOG = get_proxy_logger('component_name') + + + def my_function(): + LOG.info('logging with a module level object') + + +.. note:: + + mozlog still needs to be initialized before the first call occurs + to a ProxyLogger instance, for example with + :func:`mozlog.commandline.setup_logging`. + +.. automodule:: mozlog.proxy + :members: get_proxy_logger, ProxyLogger + Handlers -------- diff --git a/testing/mozbase/mozlog/mozlog/__init__.py b/testing/mozbase/mozlog/mozlog/__init__.py index 6d4f48817190..fbf82a9feebf 100644 --- a/testing/mozbase/mozlog/mozlog/__init__.py +++ b/testing/mozbase/mozlog/mozlog/__init__.py @@ -19,6 +19,7 @@ from . import commandline from . import structuredlog from . import unstructured from .structuredlog import get_default_logger, set_default_logger +from .proxy import get_proxy_logger # Backwards compatibility shim for consumers that use mozlog.structured structured = sys.modules[__name__] diff --git a/testing/mozbase/mozlog/mozlog/proxy.py b/testing/mozbase/mozlog/mozlog/proxy.py new file mode 100644 index 000000000000..b26dfd0b5f14 --- /dev/null +++ b/testing/mozbase/mozlog/mozlog/proxy.py @@ -0,0 +1,34 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +from .structuredlog import get_default_logger + + +class ProxyLogger(object): + """ + A ProxyLogger behaves like a + :class:`mozlog.structuredlog.StructuredLogger`. + + Each method and attribute access will be forwarded to the underlying + StructuredLogger. + + RuntimeError will be raised when the default logger is not yet initialized. + """ + def __init__(self, component=None): + self.logger = None + self._component = component + + def __getattr__(self, name): + if self.logger is None: + self.logger = get_default_logger(component=self._component) + if self.logger is None: + raise RuntimeError("Default logger is not initialized!") + return getattr(self.logger, name) + + +def get_proxy_logger(component=None): + """ + Returns a :class:`ProxyLogger` for the given component. + """ + return ProxyLogger(component)