CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-structlog

Structured logging for Python that emphasizes simplicity, power, and performance

Overview
Eval results
Files

logger-creation.mddocs/

Logger Creation and Wrapping

Core functions for creating and wrapping loggers in structlog. These functions provide the main entry points for getting configured logger instances and integrating existing loggers with structlog's processor pipeline.

Capabilities

Logger Creation

Get logger instances according to the current structlog configuration.

def get_logger(*args, **initial_values) -> Any:
    """
    Get a logger according to current configuration.

    Args:
        *args: Positional arguments passed to logger factory
        **initial_values: Initial context values to bind to the logger

    Returns:
        Logger instance wrapped according to current configuration
    """

def getLogger(*args, **initial_values) -> Any:
    """
    Alias for get_logger() using CamelCase naming convention.

    Args:
        *args: Positional arguments passed to logger factory
        **initial_values: Initial context values to bind to the logger

    Returns:
        Logger instance wrapped according to current configuration
    """

Logger Wrapping

Wrap existing logger instances with structlog functionality, allowing integration with any logging system.

def wrap_logger(
    logger,
    processors=None,
    wrapper_class=None,
    context_class=None,
    cache_logger_on_first_use=None,
    logger_factory_args=None,
    **initial_values
) -> Any:
    """
    Wrap an existing logger with structlog functionality.

    Args:
        logger: Logger instance to wrap
        processors (list, optional): Processor chain (defaults to global config)
        wrapper_class (type, optional): Wrapper class (defaults to global config)
        context_class (type, optional): Context class (defaults to global config)
        cache_logger_on_first_use (bool, optional): Caching behavior (defaults to global config)
        logger_factory_args (tuple, optional): Arguments for logger factory
        **initial_values: Initial context values to bind

    Returns:
        Wrapped logger instance with structlog functionality
    """

Usage Examples

Basic Logger Creation

import structlog

# Configure structlog first
structlog.configure(
    processors=[structlog.processors.JSONRenderer()],
    wrapper_class=structlog.stdlib.BoundLogger,
    logger_factory=structlog.stdlib.LoggerFactory(),
)

# Get a logger
logger = structlog.get_logger()
logger.info("Application started")

# Get a logger with initial context
logger = structlog.get_logger(user_id=123, session="abc")
logger.info("User action", action="login")

Named Loggers

import structlog

# Get named logger (for stdlib integration)
logger = structlog.get_logger("myapp.auth")
logger.info("Authentication module loaded")

# Alternative spelling
logger = structlog.getLogger("myapp.database")
logger.info("Database connection established")

Wrapping Existing Loggers

import logging
import structlog

# Create a standard library logger
stdlib_logger = logging.getLogger("myapp")

# Wrap it with structlog
logger = structlog.wrap_logger(
    stdlib_logger,
    processors=[
        structlog.processors.TimeStamper(),
        structlog.processors.add_log_level,
        structlog.processors.JSONRenderer()
    ]
)

logger.info("Wrapped logger", component="auth")

Custom Logger Wrapping

import structlog

class CustomLogger:
    def __init__(self, name):
        self.name = name
    
    def log(self, level, message):
        print(f"[{level}] {self.name}: {message}")

# Wrap custom logger
custom = CustomLogger("myapp")
logger = structlog.wrap_logger(
    custom,
    processors=[structlog.processors.JSONRenderer()],
    wrapper_class=structlog.BoundLogger
)

logger.info("Custom logger wrapped", service="api")

Per-Logger Configuration

import structlog

# Global configuration
structlog.configure(
    processors=[structlog.processors.KeyValueRenderer()],
    wrapper_class=structlog.BoundLogger,
)

# Override configuration for specific logger
import logging
stdlib_logger = logging.getLogger("special")

special_logger = structlog.wrap_logger(
    stdlib_logger,
    processors=[
        structlog.processors.TimeStamper(),
        structlog.processors.JSONRenderer()
    ],
    wrapper_class=structlog.stdlib.BoundLogger
)

# Regular logger uses global config
regular_logger = structlog.get_logger()

regular_logger.info("Using global config")  # KeyValue output
special_logger.info("Using custom config")  # JSON output

Logger with Factory Arguments

import structlog

def custom_logger_factory(name=None):
    import logging
    logger = logging.getLogger(name or "default")
    logger.setLevel(logging.DEBUG)
    return logger

# Configure with custom factory
structlog.configure(
    logger_factory=custom_logger_factory,
    wrapper_class=structlog.stdlib.BoundLogger,
)

# Create logger with factory arguments
logger = structlog.get_logger("myapp.service")
logger.debug("Debug message")  # Will be shown due to DEBUG level

Context Binding at Creation

import structlog

# Configure structlog
structlog.configure(
    processors=[structlog.processors.JSONRenderer()],
    wrapper_class=structlog.BoundLogger,
)

# Create logger with initial context
request_logger = structlog.get_logger(
    request_id="req-123",
    user_id=456,
    endpoint="/api/users"
)

# All log calls will include the initial context
request_logger.info("Request started")
request_logger.info("Processing data", records_count=10)
request_logger.info("Request completed", status_code=200)

Install with Tessl CLI

npx tessl i tessl/pypi-structlog

docs

bound-loggers.md

configuration.md

context-management.md

development-tools.md

exception-handling.md

index.md

logger-creation.md

output-loggers.md

processors.md

stdlib-integration.md

testing.md

tile.json