rjha
rjha

Reputation: 148

Python Colorlog not printing in the log files with colors

I'm using Python colorlogs for having different colors for different levels of logs. When i'm running the code the console logs are in colors but the log file does not have colors. I'm using the below code

def setup_logger(logfiletouse):
    """Return a logger with a default ColoredFormatter."""
    formatter = colorlog.ColoredFormatter(
        "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s",
        datefmt=None,
        reset=True,
        log_colors={
            'DEBUG': 'cyan',
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'red',
        }
    )

    log = logging.getLogger(logfiletouse)

    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    log.addHandler(handler)
    log.setLevel(logging.DEBUG)

    return log

This is my first attempt of using Python colorlogs. Any help is appreciated.

Upvotes: 3

Views: 2337

Answers (2)

James Wang
James Wang

Reputation: 31

You can use 'nb_log' instead of Python's logging module:

  1. pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple (if needed).

  2. pip install nb_log

  3. Code:

    from nb_log import get_logger
    
    log = get_logger('', log_filename='log', log_path="/zzy-log/")
    log.error('your msg')
    log.debug('your msg')
    
  4. It will generate a configuration file named nb_log_config.py in the root directory of your project when first time using, then you can change your desired option in it. The only item that you may need to modify is: DISPLAY_BACKGROUD_COLOR_IN_CONSOLE = False.

  5. nb_log will automatically output the most compreshensive colors in the console of PyCharm.

  6. You can click the 'file name(n)' in very single line to jump back into the line which launches this log output in the source code editor of PyCharm! It's very helpful for code debugging!

https://stackoverflow.com/a/78989175/23869714

Upvotes: 0

guhcampos
guhcampos

Reputation: 314

The colored output used by colorlog and most other terminal coloring libraries changes properties of the user terminal, through the shell's escape sequences.

In practice, this will print shell escape sequences which are not human readable, such as \[\033[34m\]. Your shell is responsible for parsing these sequences into colors on your display.

A plain text file does not support color information encoded into it, so generally when writing to files, all logging tools will turn off the color support, or else you would get mangled text in your log files. Just think of a plain text file packed with those unreadable escape sequences everywhere.

For more information on shell coloring and escape sequences you can take a look at http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html (bash specific, similar on other shells)

Upvotes: 4

Related Questions