@@ -222,3 +222,52 @@ initializing a database service and populating initial tables.
222
222
223
223
This technique might not work for every case, but should be a starting point for many situations
224
224
where executing a high-scope fixture exactly once is important.
225
+
226
+
227
+ Creating one log file for each worker
228
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
229
+
230
+ To create one log file for each worker with ``pytest-xdist ``, add
231
+ an option to ``pytest.ini `` for the file base name. Then, in ``conftest.py ``,
232
+ register it with ``pytest_addoption(parser) `` and use ``pytest_configure(config) ``
233
+ to rename it with the worker id.
234
+
235
+ Example:
236
+
237
+ .. code-block :: python
238
+
239
+ # content of pytest.ini
240
+ [pytest]
241
+ log_file_format = % (asctime)s % (name)s % (levelname)s % (message)s
242
+ log_file_level = INFO
243
+ worker_log_file = tests_% w.log
244
+
245
+
246
+ .. code-block :: python
247
+
248
+ # content of conftest.py
249
+ def pytest_addoption (parser ):
250
+ log_help_text = ' Similar to log_file, but %w will be replaced with a worker identifier.'
251
+ parser.addini(' worker_log_file' , help = log_help_text)
252
+
253
+
254
+ def pytest_configure (config ):
255
+ configure_logger(config)
256
+
257
+
258
+ def configure_logger (config ):
259
+ if xdist_is_enabled():
260
+ log_file = config.getini(' worker_log_file' )
261
+ logging.basicConfig(
262
+ format = config.getini(' log_file_format' ),
263
+ filename = log_file.replace(' %w' , os.environ.get(' PYTEST_XDIST_WORKER' )),
264
+ level = config.getini(' log_file_level' )
265
+ )
266
+
267
+
268
+ def xdist_is_enabled ():
269
+ return os.environ.get(' PYTEST_XDIST_WORKER' ) is not None
270
+
271
+
272
+ If running tests with ``-n3 ``, for example, three files would be created and named
273
+ as ``tests_gw0.log ``, ``tests_gw1.log `` and ``tests_gw2.log ``.
0 commit comments