Debian Codegraph @

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