🔍 Code Extractor

function setup_logging_v1

Maturity: 50

Configures and initializes Python's logging system with customizable log level and output destination (console or file).

File:
/tf/active/vicechatdev/QA_updater/utils/logging_utils.py
Lines:
5 - 32
Complexity:
simple

Purpose

This function provides a centralized way to set up logging for an application. It creates a root logger with a specified log level and formatter, and configures it to output either to a file (creating necessary directories if needed) or to the console. This is typically called once at application startup to establish consistent logging behavior throughout the codebase.

Source Code

def setup_logging(log_level=logging.INFO, log_file=None):
    """
    Sets up logging configuration for the application.

    Args:
        log_level (int): The logging level to use (e.g., logging.DEBUG, logging.INFO).
        log_file (str, optional): The path to the log file. If None, logs will be output to the console.
    """
    logger = logging.getLogger()
    logger.setLevel(log_level)

    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    if log_file:
        # Create the directory if it doesn't exist
        log_dir = os.path.dirname(log_file)
        if log_dir and not os.path.exists(log_dir):
            os.makedirs(log_dir)

        file_handler = logging.FileHandler(log_file)
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)
    else:
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)
        logger.addHandler(console_handler)

    return logger

Parameters

Name Type Default Kind
log_level - logging.INFO positional_or_keyword
log_file - None positional_or_keyword

Parameter Details

log_level: An integer constant from the logging module that determines the minimum severity level of messages to log. Common values include logging.DEBUG (10), logging.INFO (20), logging.WARNING (30), logging.ERROR (40), and logging.CRITICAL (50). Default is logging.INFO. Lower values capture more verbose output.

log_file: Optional string specifying the file path where logs should be written. If provided, logs are written to this file and the parent directory is created if it doesn't exist. If None (default), logs are output to the console (stdout/stderr) instead. Can be an absolute or relative path.

Return Value

Returns a logging.Logger object, specifically the root logger configured with the specified settings. This logger can be used directly for logging operations or retrieved elsewhere using logging.getLogger(). The returned logger has handlers and formatters already attached based on the provided parameters.

Dependencies

  • logging
  • os

Required Imports

import logging
import os

Usage Example

import logging
import os

# Example 1: Console logging with INFO level
logger = setup_logging()
logger.info('Application started')

# Example 2: File logging with DEBUG level
logger = setup_logging(log_level=logging.DEBUG, log_file='logs/app.log')
logger.debug('Debug message')
logger.info('Info message')
logger.error('Error message')

# Example 3: Custom log level and nested directory
logger = setup_logging(log_level=logging.WARNING, log_file='./output/logs/warnings.log')
logger.warning('This will be logged')
logger.info('This will not be logged due to WARNING level')

Best Practices

  • Call this function once at application startup, typically in the main entry point or __init__.py
  • Avoid calling this function multiple times as it adds handlers to the root logger each time, which can result in duplicate log messages
  • Consider using logging.getLogger(__name__) in modules instead of the root logger for better log organization
  • Use appropriate log levels: DEBUG for development, INFO for production, WARNING/ERROR for critical issues
  • When using log_file, ensure the application has write permissions to the target directory
  • For production applications, consider adding log rotation using RotatingFileHandler or TimedRotatingFileHandler instead of FileHandler
  • The formatter pattern '%(asctime)s - %(name)s - %(levelname)s - %(message)s' is fixed; consider making it configurable for different use cases
  • Be aware that this function modifies the root logger, which affects all logging throughout the application

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function setup_logging_v2 82.7% similar

    Configures Python's logging system with console and rotating file handlers, creating necessary directories and setting appropriate log levels for the application and third-party libraries.

    From: /tf/active/vicechatdev/email-forwarder/src/utils/logger.py
  • function setup_logging_v4 77.2% similar

    Configures Python's logging system for testing purposes with both console and file output.

    From: /tf/active/vicechatdev/contract_validity_analyzer/test_implementation.py
  • function setup_logging 76.8% 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
  • function setup_test_logging 73.6% similar

    Configures Python logging with both console and file output for test execution, returning a logger instance for the calling module.

    From: /tf/active/vicechatdev/contract_validity_analyzer/test_local_document.py
  • function setup_test_logging_v1 73.0% similar

    Configures Python logging for test environments with both console and file output handlers.

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