Colored logs in a .log file in python : Not working

Viewed 21

I wanted to have colored log files for one of my programs. So I tried utilizing colored logging from one of answers on stackoverflow questions, and it worked great in the python terminal but the log file showed strange characters and no color as shown below.

In Terminal :

Terminal

In Log File :

Log File

I tried many ways , but still am getting the same .

Can anyone help me , Below is my code .

import coloredlogs
import logging

# Create a logger object.
logger = logging.getLogger(__name__)

# Create a filehandler object
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)

# Create a ColoredFormatter to use as formatter for the FileHandler
formatter = coloredlogs.ColoredFormatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)

# Install the coloredlogs module on the root logger
coloredlogs.install(level='DEBUG')

logger.debug("this is a debugging message")
logger.info("this is an informational message")
logger.warning("this is a warning message")
logger.error("this is an error message")
logger.critical("this is a critical message")
1 Answers

This is not possible using just a mere text editor for reading your .log files

If you look at the question here you can see how using escape characters changes the style for the terminal output until you change it again.

Here you can see examples for these escape sequences as they were in your file aswell

HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'

your ESC is the same as \033

To get colored log files you could use the RTF file format or just HTML. You might wanna also look at this question

Related