logging.rst

Overview

This documentation file provides a comprehensive guide on how to manage and customize logging in pytest, the Python testing framework. It explains the built-in features of pytest's logging capture mechanism, how to configure logging output formats and levels, and how to interact with logging inside tests using the `caplog` fixture. It also covers live logging to the console, customizing log colors, and important changes introduced in pytest versions 3.3 and 3.4.

This file serves as a user-facing explanation rather than source code. It documents the logging functionality integrated into pytest, helping users configure and utilize logging effectively during test runs.


Detailed Explanation

Logging Capture in pytest


caplog Fixture

The `caplog` fixture provides powerful ways to interact with logging inside test functions.

Key Features:

Important Notes:


Live Logs

pytest supports *live* logging output to the console during test execution.

Example enabling live logs:

[pytest]
log_cli = true
log_cli_level = INFO

Customizing Log Colors


Release Notes & Compatibility


Interactions with Other Parts of pytest


Visual Diagram

The following Mermaid class diagram illustrates the main entity exposed by this feature: the `caplog` fixture, represented by the `LogCaptureFixture` class, showing its key methods and attributes that tests interact with.

classDiagram
    class LogCaptureFixture {
        +set_level(level: int, logger: Optional[str] = None)
        +at_level(level: int, logger: Optional[str] = None)
        +clear()
        +get_records(when: str) List[LogRecord]
        +records List[LogRecord]
        +record_tuples List[Tuple[str, int, str]]
        +text str
    }

    class LogRecord {
        +levelname: str
        +levelno: int
        +message: str
        +name: str
        +pathname: str
        +lineno: int
        +created: float
        +args: tuple
        +exc_info: Optional[tuple]
    }

    LogCaptureFixture --> LogRecord : "captures"

Usage Examples Summary


Summary

This documentation file provides a thorough reference for pytest's logging capabilities, including how to capture and manipulate logs inside tests with the `caplog` fixture, configure logging output, live logging to console and files, and customize log colors. It also details important historical changes and compatibility notes. The file is crucial for pytest users who want fine-grained control over logging during automated testing.