Bug 1226554 - [mozlog] add a ProxyLogger concept. r=jgraham

--HG--
extra : commitid : Ez3CFCMZVYb
extra : rebase_source : f2515b3bf0fc813a3f10613fb8d1bc94878a6e60
This commit is contained in:
Julien Pagès 2015-11-20 12:42:51 +01:00
Родитель 11e1dd10a1
Коммит dfdc7dc7de
3 изменённых файлов: 62 добавлений и 0 удалений

Просмотреть файл

@ -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
--------

Просмотреть файл

@ -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__]

Просмотреть файл

@ -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)