Skip to content
Advertisement

How can I get coloredlogs in PyCharm Python Console to format properly?

My logging setup is:

import coloredlogs
import logging
import sys

# Create a logger object.
# logger = logging.getLogger(__name__)

# By default the install() function installs a handler on the root logger,
# this means that log messages from your code and log messages from the
# libraries that you use will all show up on the terminal.
coloredlogs.install(level='DEBUG')



logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    stream=sys.stdout,
    datefmt='%Y-%m-%d %H:%M:%S')

If I configure the console to use python for output, all lines start at column 0, but all output is red. But if I specify use terminal, the colors are there, but the lines don’t start at column 1. They all start with the end column of the line before.

How can I get all log messages starting at column 0 AND in color?

Advertisement

Answer

Try adding isatty to your call to install. This overrides the whatever auto-detection is doing to attempt at determining what type of terminal is being used.

import coloredlogs
import logging
import sys

logger = logging.getLogger(__name__)
coloredlogs.install(level=logging.DEBUG, logger=logger, isatty=True,
                    fmt="%(asctime)s %(levelname)-8s %(message)s",
                    stream=sys.stdout,
                    datefmt='%Y-%m-%d %H:%M:%S')

logger.debug("this is a debugging message")
logger.info("this is an informational message")
logger.warning("this is a warning message")
logger.error("this is an error message")
logger.critical("this is a critical message")

enter image description here

explanation:

If I understood the problem correctly, you are seeing the logging handler default to using sys.stderr instead of sys.stdout. (this is why the text would appear in red)

There are likely two issues going on.

  1. coloredlogs.install needs to be told what type of rules you want in the handler, not logging.basicConfig.
  2. The automatic terminal detection would fail unless you either force the formatter to think it’s a terminal or you set pycharm to ‘simulate’ a terminal. Fixed by passing in stream=sys.stdout
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement