pythonloggingansi-escape

How to set a formatter for file handler that will replace unwanted characters?


I have python logger set, which has 2 handlers - 1 for stdout, 1 for file.

Some of the logs i have, contains ANSI Escape characters for colorizing logs in stdout, e.g.

SomeExampleText.... [32mPASS[0m....

I would like to utilize solution in following thread:

How can I remove the ANSI escape sequences from a string in python

In order to adjust my logger, to strip out the "color" related characters, But only when logging into fileHandler -

Keep the stdout colored, but my log file without any color related characters.

How can I achieve that?


Solution

  • Per @wjandrea references in comment:

    Related: Printing to STDOUT and log file while removing ANSI color codes and Remove ANSI Escape codes from logging message to file

    the solution revised is as follows - which works great.

    _default_fmt = '[%(asctime)s,%(msecs)03d][%(levelname)s][%(filename)s:%(lineno)d] %(message)s'
    _default_datefmt = '%m-%d %H:%M:%S'
    
    logger = logging.getLogger(__file__)
    formatter = logging.Formatter(_default_fmt, _default_datefmt)
    sh = logging.StreamHandler(sys.stdout)
    sh.setFormatter(formatter)
    logger.addHandler(sh)
    
    class FileNoAnsiLogFormat(logging.Formatter):
        _ansi_escape_regex = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
    
        def format(self, record):
            return self._ansi_escape_regex.sub('', super().format(record))
    
    handler = logging.FileHandler(file_name, mode=file_mode)
    handler.setLevel(level)
    handler.setFormatter(FileNoAnsiLogFormat(_default_fmt, _default_datefmt))
    logger.addHandler(handler)