使用ubuntu-latest在github运行程序中基于Python的彩色日志记录

问题描述

我正在使用此库https://coloredlogs.readthedocs.io/en/latest/index.html在python中使用此库

import coloredlogs,logging
logger = logging.getLogger(__name__)
coloredlogs.install(level='DEBUG',logger=logger)
logger.debug("test")

以上代码在我的本地计算机上按预期工作,并且testgreen.中打印输出 但是,当我在像这样的github运行程序上运行此代码

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
    - name: Create workflow
      run: |
        python scripts/my-logging-file.py

在跑步者上生成输出没有任何颜色。是否有任何特定的环境。需要设置或其他任何更改的变量?

解决方法

降级为coloredlogs==12.0可以解决以下根据kosta的评论所述的问题。


coloredlogs默认使用自动检测,在Linux上,仅当输出为TTY时才启用彩色输出。根据文档,应该将isatty = True通过**kw传递到coloredlogs.install以强制进行彩色输出。

但是文档和代码不一致,看起来代码有错误并且强制彩色输出不起作用。参见https://github.com/xolox/python-coloredlogs/issues/84

import coloredlogs,logging
logger = logging.getLogger(__name__)
coloredlogs.install(level='DEBUG',logger=logger,isatty=true)
logger.debug("test")

coloredlogs.install(level=None,**kw)
isattyTrue使用ColoredFormatterFalse使用普通Formatter(默认为使用terminal_supports_colors()自动检测)。>

https://coloredlogs.readthedocs.io/en/latest/api.html?highlight=isatty#coloredlogs.install

terminal_supports_colors来自humanfriendly,并且如果传递的流是TTY,则返回true。在GitHub Actions运行程序中,输出被重定向。

humanfriendly.terminal.terminal_supports_colors(stream=None)
检查流是否已连接到支持ANSI转义序列的终端。
参数:stream –要检查的流(类似文件的对象,默认为sys.stdout)。
返回:True,如果终端支持ANSI转义序列,否则返回False。

https://humanfriendly.readthedocs.io/en/latest/api.html#humanfriendly.terminal.terminal_supports_colors

源代码

https://github.com/xolox/python-humanfriendly/blob/05d02d4f6ef317edf97aca679411ec6514685243/humanfriendly/terminal/init.py#L702

https://github.com/xolox/python-humanfriendly/blob/05d02d4f6ef317edf97aca679411ec6514685243/humanfriendly/terminal/init.py#L402