Pytest Logging Explained (Set Log Level, Show Logs, caplog, Fix Issues)

Pytest Logging Explained (Set Log Level, Show Logs, caplog, Fix Issues)

Pytest Logging

Pytest logging allows you to control how logs are displayed during test execution using CLI options or configuration files like pytest.ini. It is built on top of Python’s logging module, so understanding basic logging concepts is helpful.

If you're new to logging, refer to /python-logging/.

Enable Logging in Pytest (CLI + pytest.ini)

You can enable logging directly from the command line or using pytest.ini.

python
pytest --log-cli-level=INFO

Or using pytest.ini:

python
[pytest]
log_cli = true
log_cli_level = INFO

Key takeaway:

  • CLI option is quick for temporary runs
  • pytest.ini is preferred for persistent configuration

Set Log Level in Pytest (DEBUG, INFO, ERROR)

Pytest supports standard logging levels from Python.

python
pytest --log-cli-level=DEBUG

Common levels:

  • DEBUG → detailed logs
  • INFO → general information
  • WARNING → potential issues
  • ERROR → failures

These levels come from Python’s logging system.


How to Enable and Control Logs in Pytest

Show Logs in Console (log_cli, --log-cli-level)

To display logs in the console during test execution:

python
pytest --log-cli=true --log-cli-level=INFO

Or via pytest.ini:

python
[pytest]
log_cli = true
log_cli_level = INFO

This enables live logging output during test execution.

Set Log Level from Command Line

Override logging levels without modifying configuration files:

python
pytest --log-cli-level=ERROR

Useful for:

  • CI/CD pipelines
  • Debugging specific test runs

Configure Logging in pytest.ini (Best Practice)

For consistent logging across your project, use pytest.ini.

python
[pytest]
log_cli = true
log_cli_level = DEBUG
log_cli_format = %(asctime)s [%(levelname)s] %(message)s

Key benefits:

  • Centralized configuration
  • Consistent logs across team
  • Easy to maintain

Common Logging Scenarios

Show Logs During Test Execution (Live Logging)

To see logs in real time while tests are running, enable live logging.

python
pytest --log-cli=true --log-cli-level=INFO

This displays logs directly in the console during execution.

For persistent configuration, use pytest.ini instead of CLI.

Show Logs for Passed Tests

By default, pytest may not show logs for passed tests unless configured.

python
pytest --log-cli-level=INFO -o log_cli=true

This ensures logs are visible even when tests pass.

Useful when debugging intermittent issues or verifying expected logs.

Pytest captures logs by default. You can control this behavior.

python
pytest -s

Key differences:

  • -s → disables capture, shows print() output directly
  • Logging → structured, configurable, and filterable

Prefer logging over print statements for better control.

Debug Logging in Pytest (Enable DEBUG Level)

To see detailed logs, enable DEBUG level.

python
pytest --log-cli-level=DEBUG

This shows all log levels including debug messages.

Useful for troubleshooting complex test failures.


Pytest caplog Fixture

Capture Logs in Tests Using caplog

python
import logging

def test_logging(caplog):
    caplog.set_level(logging.INFO)
    
    logging.info("Test log message")

    assert "Test log message" in caplog.text

Key takeaway:

  • Captures logs during test execution
  • Helps validate expected logging behavior

Assert Logs in Pytest Tests

You can assert specific log messages or levels.

python
import logging

def test_error_log(caplog):
    caplog.set_level(logging.ERROR)
    
    logging.error("Error occurred")

    assert "Error occurred" in caplog.text

Useful for:

  • Testing error handling
  • Verifying warnings and failures

caplog vs print vs logging

MethodUse CaseLimitation
print()Quick debuggingNot structured, cannot assert
loggingApplication loggingNeeds configuration
caplogTesting logsOnly works inside pytest

Recommendation:

  • Use logging for application code
  • Use caplog for testing log output
  • Avoid print() in production tests

Fix Issues: Pytest Logging Not Showing

One of the most common problems is logs not appearing during pytest execution. This is usually caused by incorrect configuration or log level settings.

Why Logs Are Not Visible (Common Causes)

Common reasons:

  • Logging level set too high (e.g., ERROR instead of DEBUG)
  • log_cli not enabled
  • Logs being captured instead of printed
  • Conflicting logging configurations

Pytest relies on Python’s logging system. If you’re unsure about log behavior, refer to /python-logging/.


Fix log level issues

Ensure the correct log level is set.

python
pytest --log-cli-level=DEBUG

Or in pytest.ini:

python
[pytest]
log_cli = true
log_cli_level = DEBUG

If logs are still missing, try lowering the level further (DEBUG shows everything).


Fix logging configuration conflicts

Conflicts happen when multiple logging configurations override each other.

python
import logging

logging.basicConfig(level=logging.DEBUG)

Tips:

  • Avoid multiple basicConfig() calls
  • Remove duplicate handlers
  • Ensure pytest config matches Python logging config

Advanced Logging Configuration

Customize Log Format (log_format, timestamps)

You can customize how logs appear using format options.

python
[pytest]
log_cli = true
log_cli_format = %(asctime)s [%(levelname)s] %(message)s
log_cli_date_format = %Y-%m-%d %H:%M:%S

This improves readability and debugging efficiency.

Log to File (log_file, log_file_level)

Store logs in a file for later analysis.

python
[pytest]
log_file = pytest_logs.txt
log_file_level = INFO

Or via CLI:

python
pytest --log-file=pytest_logs.txt --log-file-level=INFO

Useful for:

  • CI/CD pipelines
  • Debugging failures after execution

Logging with pytest-xdist (Parallel Execution)

When running tests in parallel, logs may get mixed or harder to track.

python
pytest -n 4 --log-cli-level=INFO

Tips:

  • Include worker info in logs
  • Use structured formats for clarity
  • Keep log level moderate (INFO or WARNING)

Learn more about running commands in Python workflows at /python-run-shell-commands/.


Frequently Asked Questions

1. How do I enable logging in pytest?

You can enable logging in pytest using the --log-cli-level option or by configuring log_cli = true in pytest.ini.

2. Why are my logs not showing in pytest?

Logs may not appear if the log level is too high, log_cli is disabled, or logging configuration conflicts exist. Setting --log-cli-level=DEBUG usually resolves this.

3. How do I set log level in pytest?

You can set log level using --log-cli-level=INFO from CLI or log_cli_level = INFO in pytest.ini.

4. What is caplog in pytest?

caplog is a pytest fixture used to capture and assert log messages during test execution.

5. How do I log pytest output to a file?

Use log_file and log_file_level in pytest.ini or pass --log-file and --log-file-level via command line.

6. How do I show logs for passed tests in pytest?

Enable log_cli and set an appropriate log level using --log-cli-level to display logs even for passed tests.

7. How do I enable debug logging in pytest?

Run pytest with --log-cli-level=DEBUG to see detailed debug logs during test execution.

Summary

Pytest logging is a powerful feature that helps you debug, monitor, and validate test behavior. By configuring log levels, enabling live logging, and using fixtures like caplog, you can gain deep visibility into your test execution.

Key takeaways:

  • Use --log-cli-level or pytest.ini to control logging
  • Enable log_cli to show logs in console
  • Use caplog to capture and assert logs in tests
  • Fix missing logs by adjusting log level and configuration
  • Use file logging for persistent analysis

With the right setup, pytest logging becomes an essential tool for building reliable and maintainable test suites.


Official Documentation

Deepak Prasad

Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels across development, DevOps, networking, and security, delivering robust and efficient solutions for diverse projects.