1

I'd like to add additional logging to pytest framework test cases. Currently my idea is like this: Logger clas with the following configuration (let's say default)

import logging
class Logger:
    logger = logging.getLogger()
    handler = logging.StreamHandler()
    formatter = logging.Formatter(
        '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logger.setLevel(logging.INFO)

In the conftest I am creating a fixture which is actually an instance of the Logger:

#conftest.py
@pytest.fixture
def trace():
    trace = Logger()
    return trace

Then I am passing this trace fixture to every test where logging is needed.

trace.logger.info("Processing data")
    value = input_data.data["value1"]

It does work but I am not sure if there is something better to have one common logger for every test case. Currently it is also needed to pass this fixture to any test I want to add more traces.

ban.85
  • 113
  • 1
  • 1
  • 7
  • This is what I needed. https://stackoverflow.com/questions/4673373/logging-within-py-test-tests – ban.85 Jun 05 '19 at 15:43

2 Answers2

1

You are misunderstanding how logging.getLogger() works. Loggers are some kind of singletons...

logging.getLogger() will return the logger object if it has already been instanciated, or creates and return a new one else. If you want to get different loggers, you will need to give them names.

Ex:

logger = logging.getLogger("logger1")

You should take a look there, the doc is really complete: https://docs.python.org/3/howto/logging-cookbook.html

olinox14
  • 6,177
  • 2
  • 22
  • 39
1

If you want to check what's logged by your various tests, pytest comes with the battery included fixture named caplog. You don't need to build your custom handler as I did when testing with unittest.

https://docs.pytest.org/en/latest/logging.html

glenfant
  • 1,298
  • 8
  • 9