### LazyLoggerFactory and Multiple Loggers in Python Source: https://github.com/bobthebuidler/lazy_logging/blob/master/README.md Illustrates the use of LazyLoggerFactory to create custom logger instances and apply them as decorators. This allows for more granular control over logging configurations, potentially for different parts of an application. The example shows how to instantiate a factory, apply it to functions, and compares two functions decorated with different configurations. ```python from lazy_logging import LazyLogger, LazyLoggerFactory import logging logger = logging.getLogger(__name__) exampleLazyLogger = LazyLoggerFactory("EXAMPLE") @exampleLazyLogger(logger) def my_function_a(): pass @LazyLogger(logger,"EXAMPLE") def my_function_b(): pass my_function_a == my_function_b ``` -------------------------------- ### Basic LazyLogger Usage in Python Source: https://github.com/bobthebuidler/lazy_logging/blob/master/README.md Demonstrates the basic usage of the LazyLogger decorator with a Python function. The decorator wraps the function, allowing for logging based on the logger's configuration. No external dependencies beyond the standard `logging` module and the `lazy_logging` library are required. ```python import logging from lazy_logging import LazyLogger logger = logging.getLogger(__name__) @LazyLogger(logger) def something(): ' i do something ' return ``` -------------------------------- ### Environment Variable Configuration for LazyLogger Source: https://context7.com/bobthebuidler/lazy_logging/llms.txt Illustrates how LazyLogger uses environment variables to dynamically control logging levels. It shows direct LazyLogger usage with custom keys, LazyLoggerFactory for shared control, and the default key mechanism. ```python import logging import os from lazy_logging import LazyLogger, LazyLoggerFactory # Method 1: Direct LazyLogger with custom key logger1 = logging.getLogger("module1") os.environ["LL_LEVEL_MODULE1"] = "DEBUG" # Enable debug for MODULE1 @LazyLogger(logger1, "MODULE1") def function_a(): return "a" # Method 2: LazyLoggerFactory for shared control factory = LazyLoggerFactory("SHARED") logger2 = logging.getLogger("module2") logger3 = logging.getLogger("module3") # Both use LL_LEVEL_SHARED @factory(logger2) def function_b(): return "b" @factory(logger3) def function_c(): return "c" # Enable debug for all SHARED functions at once os.environ["LL_LEVEL_SHARED"] = "INFO" # Method 3: Default key (empty string uses LL_LEVEL) logger4 = logging.getLogger("default") os.environ["LL_LEVEL"] = "WARNING" @LazyLogger(logger4) # Uses default LL_LEVEL key def function_d(): return "d" # Verify keys print(f"Factory key: {factory.key}") # LL_LEVEL_SHARED print(f"LazyLogger key: {LazyLogger(logger1, 'MODULE1').key}") # LL_LEVEL_MODULE1 ``` -------------------------------- ### Async Descriptor Support with LazyLogger Source: https://context7.com/bobthebuidler/lazy_logging/llms.txt Demonstrates how LazyLogger can wrap async descriptors, enabling logging for property-like async accessors on classes. This allows tracing the execution and return values of asynchronous computations exposed as properties. ```python import asyncio import logging import os from typing import Awaitable, cast from lazy_logging import LazyLogger logger = logging.getLogger("descriptor.example") logger.addHandler(logging.StreamHandler()) os.environ["LL_LEVEL_DESC"] = "DEBUG" lazy_logger = LazyLogger(logger, "DESC") class AsyncCachedProperty: """An async descriptor that caches computed values.""" def __init__(self, func): self.func = func self.__name__ = func.__name__ async def __get__(self, instance, owner): if instance is None: return self value = await self.func(instance) return value class DataModel: # Wrap the async descriptor with LazyLogger @lazy_logger @AsyncCachedProperty async def expensive_computation(self) -> int: """Simulate expensive async computation.""" await asyncio.sleep(0.1) return 42 async def main(): model = DataModel() # Accessing the descriptor logs the fetch and return value result = await cast(Awaitable[int], model.expensive_computation) print(f"Computed value: {result}") # Computed value: 42 asyncio.run(main()) ``` -------------------------------- ### Decorate Function with LazyLogger in Python Source: https://context7.com/bobthebuidler/lazy_logging/llms.txt Demonstrates how to use the LazyLogger class to automatically log function entry, arguments, and return values. It requires a logger instance and an optional environment variable key for level control. Logging is enabled via an environment variable. ```python import logging import os from lazy_logging import LazyLogger # Set up a logger logger = logging.getLogger("myapp.utils") logger.addHandler(logging.StreamHandler()) # Enable debug logging via environment variable os.environ["LL_LEVEL_UTILS"] = "DEBUG" # Decorate a function with LazyLogger @LazyLogger(logger, "UTILS") def calculate_total(items: list[float], tax_rate: float = 0.08) -> float: """Calculate total with tax.""" subtotal = sum(items) return subtotal * (1 + tax_rate) # When called, automatically logs: # DEBUG - Fetching myapp.utils.calculate_total([10.0, 20.0, 30.0],tax_rate=0.08)... # DEBUG - myapp.utils.calculate_total([10.0, 20.0, 30.0],tax_rate=0.08) returns: 64.8 result = calculate_total([10.0, 20.0, 30.0], tax_rate=0.08) print(f"Total: ${result:.2f}") # Total: $64.80 ``` -------------------------------- ### Class Method Decoration with LazyLogger Source: https://context7.com/bobthebuidler/lazy_logging/llms.txt Shows how LazyLogger correctly decorates class methods, instance methods, and static methods by leveraging the descriptor protocol. This enables logging for various types of methods within a class. ```python import logging import os from lazy_logging import LazyLogger logger = logging.getLogger("service") logger.addHandler(logging.StreamHandler()) os.environ["LL_LEVEL_SVC"] = "DEBUG" class UserService: def __init__(self, db_connection: str): self.db = db_connection @LazyLogger(logger, "SVC") def get_user(self, user_id: int) -> dict: """Fetch user by ID.""" return {"id": user_id, "db": self.db} @LazyLogger(logger, "SVC") def update_user(self, user_id: int, data: dict) -> bool: """Update user data.""" return True # Usage service = UserService("postgres://localhost/mydb") user = service.get_user(123) # Logs: Fetching service.UserService.get_user(123)... # Logs: service.UserService.get_user(123) returns: {'id': 123, 'db': 'postgres://localhost/mydb'} updated = service.update_user(123, {"name": "Jane"}) # Logs: Fetching service.UserService.update_user(123,data={'name': 'Jane'})... # Logs: service.UserService.update_user(123,data={'name': 'Jane'}) returns: True ``` -------------------------------- ### Create Shared Key Loggers with LazyLoggerFactory in Python Source: https://context7.com/bobthebuidler/lazy_logging/llms.txt Illustrates using LazyLoggerFactory to create multiple LazyLogger instances that share a single environment variable for logging level control. This allows centralized management of debug output for related components. ```python import logging import os from lazy_logging import LazyLoggerFactory # Create a factory with a shared key api_logger_factory = LazyLoggerFactory("API") # Set up different loggers for different modules auth_logger = logging.getLogger("api.auth") data_logger = logging.getLogger("api.data") # Both decorators use the same LL_LEVEL_API environment variable @api_logger_factory(auth_logger) def authenticate_user(username: str, token: str) -> bool: """Validate user credentials.""" return len(token) > 10 and username != "" @api_logger_factory(data_logger) def fetch_user_data(user_id: int) -> dict: """Retrieve user data from database.""" return {"id": user_id, "name": "John Doe", "email": "john@example.com"} # Enable debug logging for ALL API functions with one env var os.environ["LL_LEVEL_API"] = "DEBUG" # Both functions now log debug information is_valid = authenticate_user("john", "secret_token_123") user = fetch_user_data(42) # Output includes entry/exit logs for both functions ``` -------------------------------- ### LazyLoggerFactory - Shared Key Logger Creation Source: https://context7.com/bobthebuidler/lazy_logging/llms.txt The LazyLoggerFactory creates multiple LazyLogger instances that share the same environment variable key, allowing centralized control of logging levels across related components. ```APIDOC ## LazyLoggerFactory - Shared Key Logger Creation ### Description Creates a factory that generates `LazyLogger` instances sharing a common environment variable key for log level control. This allows managing logging levels for a group of related functions centrally. ### Method Factory and Decorator ### Endpoint N/A (Factory and Decorator) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import logging import os from lazy_logging import LazyLoggerFactory api_logger_factory = LazyLoggerFactory("API") auth_logger = logging.getLogger("api.auth") data_logger = logging.getLogger("api.data") os.environ["LL_LEVEL_API"] = "DEBUG" @api_logger_factory(auth_logger) def authenticate_user(username: str, token: str) -> bool: """Validate user credentials.""" return len(token) > 10 and username != "" @api_logger_factory(data_logger) def fetch_user_data(user_id: int) -> dict: """Retrieve user data from database.""" return {"id": user_id, "name": "John Doe", "email": "john@example.com"} is_valid = authenticate_user("john", "secret_token_123") user = fetch_user_data(42) ``` ### Response #### Success Response (200) Logs are printed to the respective loggers. Functions return their computed values. #### Response Example ``` # Example output when LL_LEVEL_API is DEBUG: DEBUG - Fetching api.auth.authenticate_user(username='john', token='secret_token_123')... DEBUG - api.auth.authenticate_user(username='john', token='secret_token_123') returns: False DEBUG - Fetching api.data.fetch_user_data(user_id=42)... DEBUG - api.data.fetch_user_data(user_id=42) returns: {'id': 42, 'name': 'John Doe', 'email': 'john@example.com'} ``` ``` -------------------------------- ### Async Function Support Source: https://context7.com/bobthebuidler/lazy_logging/llms.txt LazyLogger seamlessly wraps asynchronous functions and coroutines, providing the same logging capabilities for asynchronous code, including entry, arguments, and return values. ```APIDOC ## Async Function Support ### Description Demonstrates how `LazyLogger` can be used to decorate asynchronous functions and coroutines, providing automatic logging for their execution, arguments, and return values. ### Method Decorator for async functions ### Endpoint N/A (Decorator) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import asyncio import logging import os from lazy_logging import LazyLogger logger = logging.getLogger("async.worker") logger.addHandler(logging.StreamHandler()) os.environ["LL_LEVEL_ASYNC"] = "DEBUG" @LazyLogger(logger, "ASYNC") async def fetch_data(url: str, timeout: int = 30) -> dict: """Simulate async data fetching.""" await asyncio.sleep(0.1) # Simulate network delay return {"url": url, "status": 200, "data": "content"} @LazyLogger(logger, "ASYNC") async def process_urls(urls: list[str]) -> list[dict]: """Process multiple URLs concurrently.""" tasks = [fetch_data(url) for url in urls] return await asyncio.gather(*tasks) async def main(): urls = ["https://api.example.com/users", "https://api.example.com/posts"] results = await process_urls(urls) print(f"Fetched {len(results)} results") asyncio.run(main()) ``` ### Response #### Success Response (200) Logs are printed to the configured logger. The async functions complete their execution and return values. #### Response Example ``` DEBUG - Fetching async.worker.process_urls(urls=['https://api.example.com/users', 'https://api.example.com/posts']) DEBUG - Fetching async.worker.fetch_data(url='https://api.example.com/users', timeout=30)... DEBUG - async.worker.fetch_data(url='https://api.example.com/users', timeout=30) returns: {'url': 'https://api.example.com/users', 'status': 200, 'data': 'content'} DEBUG - Fetching async.worker.fetch_data(url='https://api.example.com/posts', timeout=30)... DEBUG - async.worker.fetch_data(url='https://api.example.com/posts', timeout=30) returns: {'url': 'https://api.example.com/posts', 'status': 200, 'data': 'content'} DEBUG - async.worker.process_urls(urls=['https://api.example.com/users', 'https://api.example.com/posts']) returns: [{'url': 'https://api.example.com/users', 'status': 200, 'data': 'content'}, {'url': 'https://api.example.com/posts', 'status': 200, 'data': 'content'}] Fetched 2 results ``` ``` -------------------------------- ### Decorate Async Functions with LazyLogger in Python Source: https://context7.com/bobthebuidler/lazy_logging/llms.txt Shows how LazyLogger can be used to decorate asynchronous functions and coroutines, providing the same automatic logging capabilities for async code. This enables debugging of asynchronous operations without modifying their internals. ```python import asyncio import logging import os from lazy_logging import LazyLogger logger = logging.getLogger("async.worker") logger.addHandler(logging.StreamHandler()) os.environ["LL_LEVEL_ASYNC"] = "DEBUG" @LazyLogger(logger, "ASYNC") async def fetch_data(url: str, timeout: int = 30) -> dict: """Simulate async data fetching.""" await asyncio.sleep(0.1) # Simulate network delay return {"url": url, "status": 200, "data": "content"} @LazyLogger(logger, "ASYNC") async def process_urls(urls: list[str]) -> list[dict]: """Process multiple URLs concurrently.""" tasks = [fetch_data(url) for url in urls] return await asyncio.gather(*tasks) async def main(): urls = ["https://api.example.com/users", "https://api.example.com/posts"] results = await process_urls(urls) # Logs entry/exit for process_urls and each fetch_data call print(f"Fetched {len(results)} results") asyncio.run(main()) ``` -------------------------------- ### LazyLogger - Basic Function Decorator Source: https://context7.com/bobthebuidler/lazy_logging/llms.txt The LazyLogger class wraps synchronous functions to automatically log entry, arguments, and return values. It requires a logger instance and an optional key for environment variable-based level control. ```APIDOC ## LazyLogger - Basic Function Decorator ### Description Decorates a synchronous function to automatically log its entry point, arguments, and return value. The logging level can be controlled via an environment variable. ### Method Decorator ### Endpoint N/A (Decorator) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import logging import os from lazy_logging import LazyLogger logger = logging.getLogger("myapp.utils") logger.addHandler(logging.StreamHandler()) os.environ["LL_LEVEL_UTILS"] = "DEBUG" @LazyLogger(logger, "UTILS") def calculate_total(items: list[float], tax_rate: float = 0.08) -> float: """Calculate total with tax.""" subtotal = sum(items) return subtotal * (1 + tax_rate) result = calculate_total([10.0, 20.0, 30.0], tax_rate=0.08) print(f"Total: ${result:.2f}") ``` ### Response #### Success Response (200) Logs are printed to the configured logger. The function returns its computed value. #### Response Example ``` DEBUG - Fetching myapp.utils.calculate_total([10.0, 20.0, 30.0],tax_rate=0.08)... DEBUG - myapp.utils.calculate_total([10.0, 20.0, 30.0],tax_rate=0.08) returns: 64.8 Total: $64.80 ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.