首页 > 解决方案 > 使用 ubuntu-latest 在 github 运行器中基于 Python 的彩色日志记录

问题描述

我在 python 中使用这个库,使用这个库https://coloredlogs.readthedocs.io/en/latest/index.html

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

上面的代码在我的本地按预期工作并test打印出来green. 但是,当我在这样的 github 运行器上运行它时

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

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

标签: pythongithub-actionspython-logging

解决方案


根据kosta的评论,降级以coloredlogs==12.0解决下面描述的问题。


coloredlogs默认情况下使用自动检测,在 linux 上,仅当输出是 TTY 时才启用彩色输出。根据文档,它应该可以isatty = True通过**kwtocoloredlogs.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使用ColoredFormatter,False使用正常Formatter(默认使用自动检测terminal_supports_colors())。

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

terminal_supports_colorshumanfriendly如果传递的流是 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


推荐阅读