7

I would like to create a separate log file for each subprocess/gateway that is spawned by pytest-xdist. Is there an elegant way of finding out in which subprocess/gateway pytest is currently in? I'm configuring my root logger with a session scoped fixture located in conftest.py, something like this:

@pytest.fixture(scope='session', autouse=True)
def setup_logging():
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)

    fh = logging.FileHandler('xdist.log')
    fh.setLevel(logging.INFO)

   formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
   fh.setFormatter(formatter)

   logger.addHandler(fh)

It would be great if i could add a prefix to the log file name based on the gateway number, e.g:

 fh = logging.FileHandler('xdist_gateway_%s.log' % gateway_number)

Without this each gateway will use the same log and the logs will get messy. I know that I can add a time stamp to the filename. But this doesn't let me to distinguish quickly which file is from which gateway.

MrBean Bremen
  • 14,916
  • 3
  • 26
  • 46
Kanguros
  • 1,902
  • 2
  • 12
  • 18

2 Answers2

4

Similar to @Kanguros's answer but plugging into the pytest fixture paradigm:

You can get the worker id by [accessing] the slaveinput dictionary. Here's a fixture which makes that information available to tests and other fixtures:

@pytest.fixture
def worker_id(request):
    if hasattr(request.config, 'workerinput'):
        return request.config.workerinput['workerid']
    else:
        return 'master'

This is quoted from a comment on the pytest-xdist Issues tracker/discussion (2016).

Jonas H.
  • 2,331
  • 4
  • 17
  • 23
floer32
  • 2,190
  • 4
  • 29
  • 50
3

I found out that you can access the gateway id in the following way:

slaveinput = getattr(session.config, "slaveinput", None)

if slaveinput:
    gatewayid = slaveinput['slaveid']

Of course you need to be in a place where you can access the session.config object.

Kanguros
  • 1,902
  • 2
  • 12
  • 18