Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/doc/en/how-to/logging.rst

raw
1 .. _logging:
2
3 How to manage logging
4 ---------------------
5
6 pytest captures log messages of level ``WARNING`` or above automatically and displays them in their own section
7 for each failed test in the same manner as captured stdout and stderr.
8
9 Running without options:
10
11 .. code-block:: bash
12
13 pytest
14
15 Shows failed tests like so:
16
17 .. code-block:: pytest
18
19 ----------------------- Captured stdlog call ----------------------
20 test_reporting.py 26 WARNING text going to logger
21 ----------------------- Captured stdout call ----------------------
22 text going to stdout
23 ----------------------- Captured stderr call ----------------------
24 text going to stderr
25 ==================== 2 failed in 0.02 seconds =====================
26
27 By default each captured log message shows the module, line number, log level
28 and message.
29
30 If desired the log and date format can be specified to
31 anything that the logging module supports by passing specific formatting options:
32
33 .. code-block:: bash
34
35 pytest --log-format="%(asctime)s %(levelname)s %(message)s" \
36 --log-date-format="%Y-%m-%d %H:%M:%S"
37
38 Shows failed tests like so:
39
40 .. code-block:: pytest
41
42 ----------------------- Captured stdlog call ----------------------
43 2010-04-10 14:48:44 WARNING text going to logger
44 ----------------------- Captured stdout call ----------------------
45 text going to stdout
46 ----------------------- Captured stderr call ----------------------
47 text going to stderr
48 ==================== 2 failed in 0.02 seconds =====================
49
50 These options can also be customized through ``pytest.ini`` file:
51
52 .. code-block:: ini
53
54 [pytest]
55 log_format = %(asctime)s %(levelname)s %(message)s
56 log_date_format = %Y-%m-%d %H:%M:%S
57
58 Specific loggers can be disabled via ``--log-disable={logger_name}``.
59 This argument can be passed multiple times:
60
61 .. code-block:: bash
62
63 pytest --log-disable=main --log-disable=testing
64
65 Further it is possible to disable reporting of captured content (stdout,
66 stderr and logs) on failed tests completely with:
67
68 .. code-block:: bash
69
70 pytest --show-capture=no
71
72
73 caplog fixture
74 ^^^^^^^^^^^^^^
75
76 Inside tests it is possible to change the log level for the captured log
77 messages. This is supported by the ``caplog`` fixture:
78
79 .. code-block:: python
80
81 def test_foo(caplog):
82 caplog.set_level(logging.INFO)
83
84 By default the level is set on the root logger,
85 however as a convenience it is also possible to set the log level of any
86 logger:
87
88 .. code-block:: python
89
90 def test_foo(caplog):
91 caplog.set_level(logging.CRITICAL, logger="root.baz")
92
93 The log levels set are restored automatically at the end of the test.
94
95 It is also possible to use a context manager to temporarily change the log
96 level inside a ``with`` block:
97
98 .. code-block:: python
99
100 def test_bar(caplog):
101 with caplog.at_level(logging.INFO):
102 pass
103
104 Again, by default the level of the root logger is affected but the level of any
105 logger can be changed instead with:
106
107 .. code-block:: python
108
109 def test_bar(caplog):
110 with caplog.at_level(logging.CRITICAL, logger="root.baz"):
111 pass
112
113 Lastly all the logs sent to the logger during the test run are made available on
114 the fixture in the form of both the ``logging.LogRecord`` instances and the final log text.
115 This is useful for when you want to assert on the contents of a message:
116
117 .. code-block:: python
118
119 def test_baz(caplog):
120 func_under_test()
121 for record in caplog.records:
122 assert record.levelname != "CRITICAL"
123 assert "wally" not in caplog.text
124
125 For all the available attributes of the log records see the
126 ``logging.LogRecord`` class.
127
128 You can also resort to ``record_tuples`` if all you want to do is to ensure,
129 that certain messages have been logged under a given logger name with a given
130 severity and message:
131
132 .. code-block:: python
133
134 def test_foo(caplog):
135 logging.getLogger().info("boo %s", "arg")
136
137 assert caplog.record_tuples == [("root", logging.INFO, "boo arg")]
138
139 You can call ``caplog.clear()`` to reset the captured log records in a test:
140
141 .. code-block:: python
142
143 def test_something_with_clearing_records(caplog):
144 some_method_that_creates_log_records()
145 caplog.clear()
146 your_test_method()
147 assert ["Foo"] == [rec.message for rec in caplog.records]
148
149
150 The ``caplog.records`` attribute contains records from the current stage only, so
151 inside the ``setup`` phase it contains only setup logs, same with the ``call`` and
152 ``teardown`` phases.
153
154 To access logs from other stages, use the ``caplog.get_records(when)`` method. As an example,
155 if you want to make sure that tests which use a certain fixture never log any warnings, you can inspect
156 the records for the ``setup`` and ``call`` stages during teardown like so:
157
158 .. code-block:: python
159
160 @pytest.fixture
161 def window(caplog):
162 window = create_window()
163 yield window
164 for when in ("setup", "call"):
165 messages = [
166 x.message for x in caplog.get_records(when) if x.levelno == logging.WARNING
167 ]
168 if messages:
169 pytest.fail(f"warning messages encountered during testing: {messages}")
170
171
172
173 The full API is available at :class:`pytest.LogCaptureFixture`.
174
175 .. warning::
176
177 The ``caplog`` fixture adds a handler to the root logger to capture logs. If the root logger is
178 modified during a test, for example with ``logging.config.dictConfig``, this handler may be
179 removed and cause no logs to be captured. To avoid this, ensure that any root logger configuration
180 only adds to the existing handlers.
181
182
183 .. _live_logs:
184
185 Live Logs
186 ^^^^^^^^^
187
188 By setting the :confval:`log_cli` configuration option to ``true``, pytest will output
189 logging records as they are emitted directly into the console.
190
191 You can specify the logging level for which log records with equal or higher
192 level are printed to the console by passing ``--log-cli-level``. This setting
193 accepts the logging level names or numeric values as seen in
194 :ref:`logging's documentation <python:levels>`.
195
196 Additionally, you can also specify ``--log-cli-format`` and
197 ``--log-cli-date-format`` which mirror and default to ``--log-format`` and
198 ``--log-date-format`` if not provided, but are applied only to the console
199 logging handler.
200
201 All of the CLI log options can also be set in the configuration INI file. The
202 option names are:
203
204 * ``log_cli_level``
205 * ``log_cli_format``
206 * ``log_cli_date_format``
207
208 If you need to record the whole test suite logging calls to a file, you can pass
209 ``--log-file=/path/to/log/file``. This log file is opened in write mode by default which
210 means that it will be overwritten at each run tests session.
211 If you'd like the file opened in append mode instead, then you can pass ``--log-file-mode=a``.
212 Note that relative paths for the log-file location, whether passed on the CLI or declared in a
213 config file, are always resolved relative to the current working directory.
214
215 You can also specify the logging level for the log file by passing
216 ``--log-file-level``. This setting accepts the logging level names or numeric
217 values as seen in :ref:`logging's documentation <python:levels>`.
218
219 Additionally, you can also specify ``--log-file-format`` and
220 ``--log-file-date-format`` which are equal to ``--log-format`` and
221 ``--log-date-format`` but are applied to the log file logging handler.
222
223 All of the log file options can also be set in the configuration INI file. The
224 option names are:
225
226 * ``log_file``
227 * ``log_file_mode``
228 * ``log_file_level``
229 * ``log_file_format``
230 * ``log_file_date_format``
231
232 You can call ``set_log_path()`` to customize the log_file path dynamically. This functionality
233 is considered **experimental**. Note that ``set_log_path()`` respects the ``log_file_mode`` option.
234
235 .. _log_colors:
236
237 Customizing Colors
238 ^^^^^^^^^^^^^^^^^^
239
240 Log levels are colored if colored terminal output is enabled. Changing
241 from default colors or putting color on custom log levels is supported
242 through ``add_color_level()``. Example:
243
244 .. code-block:: python
245
246 @pytest.hookimpl(trylast=True)
247 def pytest_configure(config):
248 logging_plugin = config.pluginmanager.get_plugin("logging-plugin")
249
250 # Change color on existing log level
251 logging_plugin.log_cli_handler.formatter.add_color_level(logging.INFO, "cyan")
252
253 # Add color to a custom log level (a custom log level `SPAM` is already set up)
254 logging_plugin.log_cli_handler.formatter.add_color_level(logging.SPAM, "blue")
255 .. warning::
256
257 This feature and its API are considered **experimental** and might change
258 between releases without a deprecation notice.
259 .. _log_release_notes:
260
261 Release notes
262 ^^^^^^^^^^^^^
263
264 This feature was introduced as a drop-in replacement for the
265 :pypi:`pytest-catchlog` plugin and they conflict
266 with each other. The backward compatibility API with ``pytest-capturelog``
267 has been dropped when this feature was introduced, so if for that reason you
268 still need ``pytest-catchlog`` you can disable the internal feature by
269 adding to your ``pytest.ini``:
270
271 .. code-block:: ini
272
273 [pytest]
274 addopts=-p no:logging
275
276
277 .. _log_changes_3_4:
278
279 Incompatible changes in pytest 3.4
280 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
281
282 This feature was introduced in ``3.3`` and some **incompatible changes** have been
283 made in ``3.4`` after community feedback:
284
285 * Log levels are no longer changed unless explicitly requested by the :confval:`log_level` configuration
286 or ``--log-level`` command-line options. This allows users to configure logger objects themselves.
287 Setting :confval:`log_level` will set the level that is captured globally so if a specific test requires
288 a lower level than this, use the ``caplog.set_level()`` functionality otherwise that test will be prone to
289 failure.
290 * :ref:`Live Logs <live_logs>` is now disabled by default and can be enabled setting the
291 :confval:`log_cli` configuration option to ``true``. When enabled, the verbosity is increased so logging for each
292 test is visible.
293 * :ref:`Live Logs <live_logs>` are now sent to ``sys.stdout`` and no longer require the ``-s`` command-line option
294 to work.
295
296 If you want to partially restore the logging behavior of version ``3.3``, you can add this options to your ``ini``
297 file:
298
299 .. code-block:: ini
300
301 [pytest]
302 log_cli=true
303 log_level=NOTSET
304
305 More details about the discussion that lead to this changes can be read in :issue:`3013`.