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
project-root/
├── tests/
│ ├── test_example.py
│ └── conftest.py
├── src/
│ └── app_code.py
├── logs/
│ └── test.log
├── pytest.ini
└── requirements.txt
tests/, contain test cases using pytest.conftest.py manages setup, including log level filtering configuration.src/ holds the main code under test.logs/ stores log files generated during tests.pytest.ini sets pytest options including log level filters.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:
logs/test.log.In conftest.py, you can add fixtures to customize or override log levels per test if needed.
Logs filtered by level help keep test output clean and focused.
logs/test.log for detailed error investigation.pytest.ini for global settings: Centralize log config for consistency.Where in this folder structure would you add a fixture to change the log level to DEBUG only for a specific test?
caplog.at_level() do in pytest?caplog is a pytest fixture used to capture log messages during tests.at_level()at_level() sets the minimum log level to capture, filtering out lower-level messages.caplog.at_level() used with with statement.with caplog.at_level(logging.WARNING): which is the documented and correct syntax.import logging
def test_logs(caplog):
with caplog.at_level(logging.ERROR):
logging.warning('Warning message')
logging.error('Error message')
return caplog.records
caplog.at_level(logging.ERROR) captures logs at ERROR level or higher only.def test_example(caplog):
caplog.at_level(logging.INFO)
logging.debug('Debug message')
logging.info('Info message')
assert 'Info message' in caplog.text
at_level() must be used with a with statement to set the log level context.caplog.at_level(logging.INFO) without with does not set the level properly, so logs may not be filtered as expected.caplog.at_level(logging.INFO) captures INFO and ERROR logs but excludes DEBUG logs.Pass the test and this pattern moves unknown