0

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?

2

1 Answer 1

0

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) 
Sign up to request clarification or add additional context in comments.

2 Comments

Please include the link(s) in your answer. It's important to provide attribution, and comments can be deleted for a variety of reasons.
@wjandrea sure, done

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.