class LoggerContext
A base class that provides namespaced logging functionality to subclasses through a lazy-initialized class-level logger.
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/logger.py
18 - 31
simple
Purpose
LoggerContext serves as a superclass for any class that needs logging capabilities. It implements a lazy-loading pattern for loggers with automatic namespace generation based on the module and class name. The logger is shared across all instances of a class (class-level), and supports creating child loggers for specific methods. This design ensures consistent logging hierarchies and avoids redundant logger creation.
Source Code
class LoggerContext:
"""Superclass for all classes that require namespaced logger."""
_logger = None
@classmethod
def logger(cls, method=None):
if cls._logger is None:
logger_name = cls.__module__ + "." + cls.__name__
cls._logger = logging.getLogger(logger_name)
if method is not None:
return cls._logger.getChild(method)
return cls._logger
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
- | - |
Parameter Details
__init__: This class does not define an __init__ method. It is intended to be inherited by other classes that may define their own constructors.
method (in logger classmethod): Optional string parameter specifying a method name. When provided, returns a child logger namespaced to that method. When None, returns the base class logger.
Return Value
The class itself doesn't return anything on instantiation (no custom __init__). The logger() classmethod returns a logging.Logger instance. If 'method' parameter is None, it returns the class-level logger with namespace '<module>.<classname>'. If 'method' is provided, it returns a child logger with namespace '<module>.<classname>.<method>'.
Class Interface
Methods
logger(cls, method=None) -> logging.Logger
Purpose: Returns a logger instance for the class, optionally creating a child logger for a specific method. Implements lazy initialization of the class-level logger.
Parameters:
cls: The class itself (automatically passed as this is a classmethod)method: Optional string specifying a method name. If provided, returns a child logger with that method name appended to the namespace. Defaults to None.
Returns: A logging.Logger instance. If method is None, returns the class-level logger with namespace '<module>.<classname>'. If method is provided, returns a child logger with namespace '<module>.<classname>.<method>'.
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
_logger |
logging.Logger | None | Class-level variable that caches the logger instance for the class. Initially None, it is lazily initialized on first call to logger(). Shared across all instances of the class. | class |
Dependencies
logging
Required Imports
import logging
Usage Example
import logging
# Configure logging at application level
logging.basicConfig(level=logging.INFO, format='%(name)s - %(levelname)s - %(message)s')
class MyService(LoggerContext):
def __init__(self, name):
self.name = name
def process_data(self, data):
# Get logger for this specific method
logger = self.logger('process_data')
logger.info(f'Processing data: {data}')
return data.upper()
def save_result(self, result):
# Get class-level logger
logger = self.logger()
logger.info(f'Saving result: {result}')
# Usage
service = MyService('DataProcessor')
service.process_data('hello') # Logs: __main__.MyService.process_data - INFO - Processing data: hello
service.save_result('HELLO') # Logs: __main__.MyService - INFO - Saving result: HELLO
# Logger is shared across instances
service2 = MyService('AnotherProcessor')
print(service.logger() is service2.logger()) # True - same logger instance
Best Practices
- This class is designed to be inherited, not instantiated directly. Use it as a base class for any class that needs logging.
- The logger is initialized lazily on first access and cached at the class level, meaning all instances of a subclass share the same logger instance.
- Use the 'method' parameter when calling logger() from within methods to create hierarchical log namespaces that make it easier to trace log messages.
- Configure the logging module at the application entry point before using LoggerContext subclasses to ensure proper log formatting and output.
- The logger namespace is automatically generated as '<module>.<classname>', which helps organize logs in large applications.
- Since _logger is a class variable, it's shared across all instances of the same class but separate for different subclasses.
- Do not modify _logger directly; always use the logger() classmethod to access the logger instance.
- The lazy initialization pattern means the logger is only created when first accessed, reducing overhead for classes that may not always need logging.
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class RequestUserContext 47.0% similar
-
class SharePointHomeServiceContextBuilder 43.6% similar
-
class ComponentContextInfo 43.5% similar
-
class OrgLabelsContext 43.1% similar
-
class ClientContext 42.9% similar