function setup_test_logging
Configures Python logging with both console and file output for test execution, returning a logger instance for the calling module.
/tf/active/vicechatdev/contract_validity_analyzer/test_local_document.py
22 - 32
simple
Purpose
This function initializes the Python logging system specifically for testing purposes. It sets up dual output handlers (console via stdout and file named 'test_local_document.log') with INFO level logging and a standardized timestamp format. The function is designed to be called at the beginning of test scripts to ensure consistent logging behavior across test runs, making it easier to debug and track test execution.
Source Code
def setup_test_logging():
"""Set up logging for the test."""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler('test_local_document.log')
]
)
return logging.getLogger(__name__)
Return Value
Returns a logging.Logger instance configured for the calling module (using __name__). This logger inherits the configuration set by basicConfig, including the INFO level, formatted output, and dual handlers. The logger can be used to emit log messages at various levels (debug, info, warning, error, critical) that will be captured both in the console and in the 'test_local_document.log' file.
Dependencies
loggingsys
Required Imports
import logging
import sys
Usage Example
import logging
import sys
def setup_test_logging():
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler('test_local_document.log')
]
)
return logging.getLogger(__name__)
# Usage in a test script
logger = setup_test_logging()
logger.info('Starting test execution')
logger.warning('This is a warning message')
logger.error('An error occurred during testing')
Best Practices
- Call this function only once at the beginning of your test script to avoid duplicate handlers
- Be aware that logging.basicConfig() only works on the first call; subsequent calls have no effect unless force=True is used (Python 3.8+)
- Ensure the directory where the script runs has write permissions for creating the log file
- Consider using a unique log filename for different test modules to avoid log mixing
- The function uses __name__ which will reflect the module where the function is defined, not where it's called from
- For parallel test execution, consider adding process/thread identifiers to the log format or filename to avoid conflicts
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function setup_logging_v4 94.5% similar
-
function setup_test_logging_v4 93.7% similar
-
function setup_test_logging_v1 93.0% similar
-
function setup_test_logging_v3 92.2% similar
-
function setup_test_logging_v2 88.2% similar