🔍 Code Extractor

function log_performance

Maturity: 51

A context manager decorator that logs the performance metrics of an operation by wrapping it with a PerformanceLogger instance.

File:
/tf/active/vicechatdev/contract_validity_analyzer/utils/logging_utils.py
Lines:
129 - 145
Complexity:
simple

Purpose

This function provides a convenient way to measure and log the execution time and performance characteristics of code blocks. It creates a PerformanceLogger instance, enters its context, yields it for use within the with-block, and ensures proper cleanup. This is useful for monitoring application performance, identifying bottlenecks, and tracking operation durations in production or development environments.

Source Code

def log_performance(operation_name: str, logger: Optional[logging.Logger] = None):
    """
    Context manager for logging operation performance.
    
    Args:
        operation_name: Name of the operation
        logger: Logger instance (optional)
        
    Yields:
        PerformanceLogger instance
    """
    perf_logger = PerformanceLogger(operation_name, logger)
    try:
        with perf_logger:
            yield perf_logger
    finally:
        pass

Parameters

Name Type Default Kind
operation_name str - positional_or_keyword
logger Optional[logging.Logger] None positional_or_keyword

Parameter Details

operation_name: A string identifier for the operation being logged. This name will be used in log messages to identify which operation's performance is being measured. Should be descriptive and unique enough to distinguish different operations.

logger: An optional logging.Logger instance to use for outputting performance metrics. If None is provided, the PerformanceLogger will likely use a default logger or create its own. This allows integration with existing logging configurations and hierarchies.

Return Value

This is a generator function (context manager) that yields a PerformanceLogger instance. The yielded PerformanceLogger object can be used within the context to access performance metrics, add custom measurements, or interact with the logging functionality. The function itself doesn't return a value in the traditional sense, but yields control to the caller with the PerformanceLogger instance available.

Dependencies

  • logging
  • contextlib

Required Imports

import logging
from typing import Optional
from contextlib import contextmanager

Usage Example

import logging
from contextlib import contextmanager
from typing import Optional

# Assuming PerformanceLogger is defined elsewhere
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(handler)

# Using the context manager
with log_performance('database_query', logger) as perf:
    # Perform some operation
    result = perform_database_query()
    # The performance will be automatically logged when exiting the context

# Or without a custom logger
with log_performance('api_call') as perf:
    response = make_api_call()
    # Performance metrics logged automatically

Best Practices

  • Always use this function as a context manager with the 'with' statement to ensure proper resource cleanup
  • Provide descriptive operation_name values that clearly identify what is being measured
  • Pass a configured logger instance if you need specific logging behavior or output destinations
  • The PerformanceLogger class must be available in scope for this function to work
  • Consider using different loggers for different subsystems to organize performance logs effectively
  • The finally block is empty, suggesting cleanup is handled by the PerformanceLogger's __exit__ method
  • This function is decorated with @contextmanager, so it should only be used with the 'with' statement

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class PerformanceLogger 72.9% similar

    A context manager class that measures and logs the execution time of code blocks, with support for custom metrics and automatic error handling.

    From: /tf/active/vicechatdev/contract_validity_analyzer/utils/logging_utils.py
  • class ProgressLogger 52.6% similar

    A progress tracking logger that monitors and reports the progress of long-running operations with timing statistics, error counts, and estimated completion times.

    From: /tf/active/vicechatdev/contract_validity_analyzer/utils/logging_utils.py
  • function get_logger 49.9% similar

    A wrapper function that retrieves a logger instance from Python's logging module with the specified name.

    From: /tf/active/vicechatdev/contract_validity_analyzer/utils/logging_utils.py
  • function log_controller_action 46.3% similar

    A decorator factory that logs controller actions with different log levels based on whether the action is routine or non-routine, and handles exceptions during execution.

    From: /tf/active/vicechatdev/CDocs/controllers/__init__.py
  • function setup_logging 41.2% similar

    Configures and initializes a Python logging system with both console and rotating file handlers, supporting customizable log levels, formats, and file rotation policies.

    From: /tf/active/vicechatdev/contract_validity_analyzer/utils/logging_utils.py
← Back to Browse