1

I'm using logging to log some information.
I used both FileHandler and StreamHandler in my logger, to output the message in the console and saved to a specific file.
In the console, to highlight some important message, I used \033. But this word also add into my log file and shown a weird symbol. Following is my currently usage example

logger = logging.getLogger('SayHello')
file_hdlr = logging.FileHandler('test.log')
file_hdlr.setFormatter(logging.Formatter('%(message)s'))
console_hdlr = logging.StreamHandler()
console_hdlr.setFormatter(logging.Formatter('%(message)s'))
logger.addHandler(file_hdlr)
logger.addHandler(console_hdlr)
logger.setLevel(logging.INFO)
logger.info('\033[1;31mHello World\033[0m')

Output in console: Hello World (in red)

Output in log file: [1;31mHello World[0m

How can I ignore the \033 and other color code in my file handler? Should I override the FileHandler class? Thanks a lot!

Sean Lu
  • 73
  • 5
  • Would you like the `logger.info('\033[1;31mHello World\033[0m')` to log just `Hello World`? – Niko Föhr Nov 10 '20 at 08:53
  • Note that the simple "fix" is to read the logs with a viewer that interprets the escapes properly. For example, if your terminal can properly interpret the escapes, then using ``less -R`` to view the file should work. – MisterMiyagi Nov 10 '20 at 08:53
  • @np8 I want the console to show the message in colour and no control code in my log file – Sean Lu Nov 10 '20 at 09:12
  • @MisterMiyagi Yes! `less` can display the file properly. Not sure if there is any plugin in `gedit` to handle these control codes? – Sean Lu Nov 10 '20 at 09:14
  • See also: https://stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python and https://stackoverflow.com/questions/44075911/debugging-a-python-function-to-remove-ansi-codes – Niko Föhr Nov 10 '20 at 09:15
  • Currently I revised the `emit` in `StreamHandler`, if the stream is a file instead of `stderr`, then I will ignore the control sequences. It can solve the problem, but I know that was not a good solution :( – Sean Lu Nov 10 '20 at 10:11

1 Answers1

1

After several hours tracing, I found that FileHandler also inherited from StreamHandler. FileHandler.emit call StreamHandler.emit to write message into the file.
To ignore the control sequences in the message, I have to override both FileHandler and StreamHandler, says CustomFileHandler and CustomStreamHandler, respectively.
CustomFileHandler.emit call CustomStreamHandler.emit to write the message, where we have to remove the control sequences in it. With the help of regular expression, this should be easy to find them.

Sean Lu
  • 73
  • 5