0
0
PyTesttesting~8 mins

Log level filtering in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Log level filtering
Folder Structure
project-root/
├── tests/
│   ├── test_example.py
│   └── conftest.py
├── src/
│   └── app_code.py
├── logs/
│   └── test.log
├── pytest.ini
└── requirements.txt
    
Test Framework Layers
  • Tests: Located in tests/, contain test cases using pytest.
  • Fixtures & Config: conftest.py manages setup, including log level filtering configuration.
  • Application Code: src/ holds the main code under test.
  • Logging Output: logs/ stores log files generated during tests.
  • Configuration File: pytest.ini sets pytest options including log level filters.
Configuration Patterns

Use pytest.ini to set log level filtering globally for tests. Example:

[pytest]
log_cli = true
log_cli_level = INFO
log_file = logs/test.log
log_file_level = WARNING
    

This config means:

  • Show logs of level INFO and above in the console during test runs.
  • Write logs of level WARNING and above to the file logs/test.log.

In conftest.py, you can add fixtures to customize or override log levels per test if needed.

Test Reporting and CI/CD Integration

Logs filtered by level help keep test output clean and focused.

  • CI systems can collect logs/test.log for detailed error investigation.
  • Console logs show only important info, reducing noise in CI logs.
  • Combine with pytest reports (e.g., JUnit XML) for full test results and logs.
Best Practices for Log Level Filtering
  1. Set sensible default log levels: Use INFO for console, WARNING or ERROR for files.
  2. Use pytest.ini for global settings: Centralize log config for consistency.
  3. Keep logs readable: Avoid too verbose DEBUG logs in CI unless troubleshooting.
  4. Use fixtures to customize: Override log levels for specific tests if needed.
  5. Separate logs by purpose: Console for quick feedback, files for detailed analysis.
Self Check

Where in this folder structure would you add a fixture to change the log level to DEBUG only for a specific test?

Key Result
Use pytest.ini for global log level filtering and conftest.py fixtures for test-specific log control.