32

I'm sure this is a simple fix, but I'd like to view log messages in the PyCharm console while running a unit test. The modules I'm testing have their own loggers, and normally I'd set a root logger to catch the debugging messages at a certain level, and pipe the other logs to a file. But I can't figure out how this works with unit tests.

I'm using the unittest2 module, and using PyCharm's automatic test discovery (which probably is based on nose, but I don't know).

I've tried fooling with the run configurations, but there doesn't seem to be a straightforward way to do this.

The PyCharm documentation isn't particularly helpful here either, if any of you work there.


In edit: It DOES appear that the console catches critical level log messages. I want to know if there is a way to configure this to catch debug level messages.


This post (Pycharm unit test interactive debug command line doesn't work) suggests adding the -s option to the build configuration, which does not produce the desired result.

Community
  • 1
  • 1
BenDundee
  • 4,389
  • 3
  • 28
  • 34

8 Answers8

23

The only solution I've found is to do the normal logging setup at the top of the file with tests in it (assuming you're just running one test or test class): logging.basicConfig(level=logging.DEBUG). Make sure you put that before most import statements or the default logging for those modules will have already been set (that was a hard one to figure out!).

Pat
  • 16,515
  • 15
  • 95
  • 114
  • thanks for the suggestion. I have written a module that wraps Python's logging module (I want to have a uniform logging configuration across a large code base), and I'm already setting the basic log configs in that module. – BenDundee Dec 09 '14 at 16:58
2

I needed to add too the option --nologcapture to nosetests as param in pycharm 2016.3.2

Run>Edit COnfigurations > Defaults > Python Tests > Nosetests : activate the check for Prams option and add --nologcapture

bott
  • 188
  • 1
  • 2
  • 12
  • 5
    Produces ```_pytest.config.exceptions.UsageError: usage: _jb_pytest_runner.py [options] [file_or_dir] [file_or_dir] [...] _jb_pytest_runner.py: error: unrecognized arguments: --nologcapture``` in PyCharm 2019 2.3 – Hryhorii Liashenko Oct 19 '19 at 13:21
2

In Edit Configurations:

  • delete old configurations
  • go to Defaults / Python tests / NoseTests
  • add --nologcapture to "additional Arguments"

worked like a "charm" for me in pyCharm 2017.2.3

thanks bott

gturbo
  • 81
  • 3
1

My problem was similar, I only saw messages with level WARNING or higher while running tests in PyCharm. A colleague suggested to configure the logger in __init__.py which is in the directory of my tests.

# in tests/__init__.py
import logging
import sys

# Reconfiguring the logger here will also affect test running in the PyCharm IDE
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(message)s'
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format=log_format)

Then I can simply log in the test code like:

import logging
logging.info('whatever')
Attila123
  • 932
  • 8
  • 8
1

I experienced this problem all of a sudden after updating Pycharm. I had been running my tests with the Unittest runner, and all of a sudden Pycharm decided the default should be the pytest runner. When I changed the default test runner back to Unittest the logs appeared as I expected they would.
You can change the default test runner in Project Settings/Preferences >> Tools >> Python Integrated Tools

I assume adding the -nologcapture flag as noted in other answers probably would have worked in my case as well, but I prefer a solution that's exposed by the IDE rather than a manual override.

BTW choosing Unittest also solves an additional error that I got once when trying to run tests - No module named 'nose'

ygesher
  • 1,133
  • 12
  • 26
0

The -s option mentioned in the question in combination with adding the StreamHandler using stream=sys.stdout did work for me.

enter image description here

import logging
import sys

logger = logging.getLogger('foo')
logger.addHandler(logging.StreamHandler(stream=sys.stdout))
logger.warning('foo')

Pycharm unit test interactive debug command line doesn't work

Stefan
  • 10,010
  • 7
  • 61
  • 117
0

PyCharm suppresses the logs by adding a --no-summary flag when it runs tests by default. You can override this behaviour by going by going to File > Settings > Advanced Settings > Python and checking the option Pytest: do not add "--no-header --no-summary -q"

More detailed answer here https://stackoverflow.com/a/73873315/13466774

patelnets
  • 11
  • 2
-1

Add a stream handler, pointing to sys.stdout if doctest or pytest is running:

    import logging
    import sys
    logger = logging.getLogger()

    def setup_doctest_logger(log_level:int=logging.DEBUG):
        """

        :param log_level:
        :return:

        >>> logger.info('test')     # there is no output in pycharm by default
        >>> setup_doctest_logger()
        >>> logger.info('test')     # now we have the output we want
        test

        """
        if is_pycharm_running():
            logger_add_streamhandler_to_sys_stdout()
        logger.setLevel(log_level)

    def is_pycharm_running()->bool:
        if ('docrunner.py' in sys.argv[0]) or ('pytest_runner.py' in sys.argv[0]):
            return True
        else:
            return False

    def logger_add_streamhandler_to_sys_stdout():
        stream_handler=logging.StreamHandler(stream=sys.stdout)
        logger.addHandler(stream_handler)
bitranox
  • 1,664
  • 13
  • 21
  • 2
    Please avoid letting the "code speak for itself" and provide an explanation to help the OP understand why your solution works best. – Kasia Gogolek Mar 15 '18 at 10:59
  • 1
    We are coders. the most exact language to describe, is the code itself. You test it. You debug it. You step through it. No missunderstandings. (I like "Uncle Bob´s" approach ...) – bitranox Mar 15 '18 at 11:08
  • 1
    Please provide an explanation. I don't have time to read your code to decide if it solves my problem. This makes your contribution less useful than it might be. – hibernado Apr 11 '18 at 12:40
  • This answer was exactly what I was looking for – Dinis Cruz Dec 11 '20 at 04:21