_pytest.logging module¶
Access and control log capturing.
-
class
ColoredLevelFormatter
(terminalwriter, *args, **kwargs)[source]¶ Bases:
logging.Formatter
Colorize the %(levelname)..s part of the log format passed to __init__.
-
LOGLEVEL_COLOROPTS
: Mapping[int, AbstractSet[str]] = {0: {}, 10: {'purple'}, 20: {'green'}, 30: {'yellow'}, 40: {'bold', 'red'}, 50: {'red'}}¶
-
LEVELNAME_FMT_REGEX
= re.compile('%\\(levelname\\)([+-.]?\\d*s)')¶
-
format
(record)[source]¶ Format the specified record as text.
The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.
-
-
class
PercentStyleMultiline
(fmt, auto_indent)[source]¶ Bases:
logging.PercentStyle
A logging style with special support for multiline messages.
If the message of a record consists of multiple lines, this style formats the message as if each line were logged separately.
-
staticmethod
_get_auto_indent
(auto_indent_option) → int[source]¶ Determines the current auto indentation setting
Specify auto indent behavior (on/off/fixed) by passing in extra={“auto_indent”: [value]} to the call to logging.log() or using a –log-auto-indent [value] command line or the log_auto_indent [value] config option.
Default behavior is auto-indent off.
Using the string “True” or “on” or the boolean True as the value turns auto indent on, using the string “False” or “off” or the boolean False or the int 0 turns it off, and specifying a positive integer fixes the indentation position to the value specified.
Any other values for the option are invalid, and will silently be converted to the default.
- Parameters
auto_indent_option (any) – User specified option for indentation from command line, config or extra kwarg. Accepts int, bool or str. str option accepts the same range of values as boolean config options, as well as positive integers represented in str form.
- Returns
indentation value, which can be -1 (automatically determine indentation) or 0 (auto-indent turned off) or >0 (explicitly set indentation position).
-
staticmethod
-
with
catching_logs
(handler, formatter=None, level=None)[source]¶ Context manager that prepares the whole logging machinery properly.
-
class
LogCaptureHandler
[source]¶ Bases:
logging.StreamHandler
A logging handler that stores log records and the log text.
-
emit
(record: logging.LogRecord) → None[source]¶ Keep the log records in a list in addition to the log text.
-
-
class
LogCaptureFixture
(item)[source]¶ Bases:
object
Provides access and control of log capturing.
-
_finalize
() → None[source]¶ Finalizes the fixture.
This restores the log levels changed by
set_level()
.
-
handler
¶ - Return type
-
get_records
(when: str) → List[logging.LogRecord][source]¶ Get the logging records for one of the possible test phases.
- Parameters
when (str) – Which test phase to obtain the records from. Valid values are: “setup”, “call” and “teardown”.
- Return type
List[logging.LogRecord]
- Returns
the list of captured records at the given stage
New in version 3.4.
-
text
¶ Returns the formatted log text.
-
records
¶ Returns the list of log records.
-
record_tuples
¶ Returns a list of a stripped down version of log records intended for use in assertion comparison.
The format of the tuple is:
(logger_name, log_level, message)
-
messages
¶ Returns a list of format-interpolated log messages.
Unlike ‘records’, which contains the format string and parameters for interpolation, log messages in this list are all interpolated. Unlike ‘text’, which contains the output from the handler, log messages in this list are unadorned with levels, timestamps, etc, making exact comparisons more reliable.
Note that traceback or stack info (from
logging.exception()
or theexc_info
orstack_info
arguments to the logging functions) is not included, as this is added by the formatter in the handler.New in version 3.7.
-
set_level
(level, logger=None)[source]¶ Sets the level for capturing of logs. The level will be restored to its previous value at the end of the test.
- Parameters
Changed in version 3.4: The levels of the loggers changed by this function will be restored to their initial values at the end of the test.
-
-
for ... in
caplog
(request)[source]¶ Access and control log capturing.
Captured logs are available through the following properties/methods:
* caplog.messages -> list of format-interpolated log messages * caplog.text -> string containing formatted log output * caplog.records -> list of logging.LogRecord instances * caplog.record_tuples -> list of (logger_name, level, message) tuples * caplog.clear() -> clear captured records and formatted log output string
-
get_log_level_for_setting
(config: _pytest.config.Config, *setting_names: str) → Optional[int][source]¶
-
class
LoggingPlugin
(config: _pytest.config.Config)[source]¶ Bases:
object
Attaches to the logging module and captures log messages for each test.
-
_create_formatter
(log_format, log_date_format, auto_indent) → logging.Formatter[source]¶
-
set_log_path
(fname)[source]¶ Public method, which can set filename parameter for Logging.FileHandler(). Also creates parent directory if it does not exist.
Warning
Please considered as an experimental API.
-
_log_cli_enabled
() → bool[source]¶ Return True if log_cli should be considered enabled, either explicitly or because –log-cli-level was given on the command-line.
-
with
_runtest_for_main
(item: _pytest.nodes.Item, when: str) → Generator[None, None, None][source]¶ Implements the internals of pytest_runtest_xxx() hook.
-
-
class
_LiveLoggingStreamHandler
(terminal_reporter, capture_manager)[source]¶ Bases:
logging.StreamHandler
Custom StreamHandler used by the live logging feature: it will write a newline before the first log message in each test.
During live logging we must also explicitly disable stdout/stderr capturing otherwise it will get captured and won’t appear in the terminal.
-
emit
(record)[source]¶ Emit a record.
If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an ‘encoding’ attribute, it is used to determine how to do the output to the stream.
-