TL;DR: How can I have the stream handler to print logs with colors, and the file handler log them without the literal code characters? Any approach is fine with me, as long I'm still using standart python libraries.
--
I have been looking how to add color to the logger when it's streamed. Also I would like to use the standart python logging library.
I found this solution: https://stackoverflow.com/a/7995762/11037602
It served me well, the issue is that my logger logs into stream and into file. And the file gets the escape/colors characters aswell, like this:
- [1;33mWARNING[1;0m - run - log
Instead of:
- WARNING - run - log
My code:
def setup_logger():
logger = logging.getLogger()
#Code suggested in SO question
logging.addLevelName( logging.WARNING, "\033[1;31m%s\033[1;0m" % logging.getLevelName(logging.WARNING))
logging.addLevelName( logging.ERROR, "\033[1;41m%s\033[1;0m" % logging.getLevelName(logging.ERROR))
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(funcName)s - %(message)s')
fh = logging.FileHandler('file.log')
fh.setFormatter(formatter)
logger.addHandler(fh)
sh = logging.StreamHandler()
sh.setFormatter(formatter)
logger.addHandler(sh)
return logger
As I said, this works, however it also records the characters into the file log.
If you click in 'show 2 more comments' on the question that I linked, user @lesnik suggested put the answer's code inside if statement, I'm assuming he meant something like this:
if sys.stderr.isatty():
logging.addLevelName( logging.WARNING, "\033[1;31m%s\033[1;0m" % logging.getLevelName(logging.WARNING))
logging.addLevelName( logging.ERROR, "\033[1;41m%s\033[1;0m" % logging.getLevelName(logging.ERROR))
EDIT: Corrected the typo (pointed out by @Brad Solomon) but just adding this if statement didn't solve my problem. The characters are still logged in file.
To sum it up, how can I have the stream handler to print logs with colors, and the file handler log them without the literal code characters? Any approach is fine with me, as long I'm still using standart python libraries.