PyCharm logging output colours

2020-02-20 05:51发布

I'm using PyCharm to develop a GAE app in Mac OS X. Is there any way to display colours in the run console of PyCharm?

I've set a handler to output colours in ansi format. Then, I've added the handler:

LOG = logging.getLogger()
LOG.setLevel(logging.DEBUG)
for handler in LOG.handlers:
    LOG.removeHandler(handler)

LOG.addHandler(ColorHandler())

LOG.info('hello!')
LOG.warning('hello!')
LOG.debug('hello!')
LOG.error('hello!')

But the colour is the same.

PyCharm run console output

EDIT:

A response from JetBrains issue tracker: Change line 55 of the snippet from sys.stderr to sys.stdout. stderr stream is always colored with red color while stdout not.

Now colours are properly displayed.

7条回答
Evening l夕情丶
2楼-- · 2020-02-20 06:50

I discovered the following solution. Apparently Pycharm redirects sys.stdout. From the sys module documentation:

sys.__stdin__
sys.__stdout__
sys.__stderr__

These objects contain the original values of stdin, stderr and stdout at the start of the program. They are used during finalization, and could be useful to print to the actual standard stream no matter if the sys.std* object has been redirected.

It can also be used to restore the actual files to known working file objects in case they have been overwritten with a broken object. However, the preferred way to do this is to explicitly save the previous stream before replacing it, and restore the saved object.

Therefore, to solve this issue you can redirect output to sys.__stdout__. Example configuration from my log_config.yml:

console:
  class: logging.StreamHandler
  level: DEBUG
  stream: "ext://sys.__stdout__"
  formatter: colorFormatter
查看更多
登录 后发表回答