Python based colored logging in github runner with ubuntu-latest

2k views Asked by At

I am using this library in python using this library https://coloredlogs.readthedocs.io/en/latest/index.html

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

The above code works as expected on my local and test is printed out in green. However, when I run this on a github runner like this

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

The generated output on the runner doesn't have any color. Is there any specific env. variable that needs to set or any other change?

1

There are 1 answers

4
riQQ On

Downgrading to coloredlogs==12.0 works around the issue described below as per kosta's comment.


coloredlogs uses auto detection by default, which, on linux, only enables colored output iff the output is a TTY. According to the documentation it should work to pass isatty = True via **kw to coloredlogs.install to force colored output.

But documentation and code are inconsistent, it looks like the code has a bug and forcing colored output doesn't work. See 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 to use a ColoredFormatter, False to use a normal Formatter (defaults to auto-detection using terminal_supports_colors()).

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

terminal_supports_colors is from humanfriendly and returns true iff the passed stream is a TTY. In a GitHub Actions runner the output is redirected.

humanfriendly.terminal.terminal_supports_colors(stream=None)
Check if a stream is connected to a terminal that supports ANSI escape sequences.
Parameters: stream – The stream to check (a file-like object, defaults to sys.stdout).
Returns: True if the terminal supports ANSI escape sequences, False otherwise.

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

Source code

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