πŸ› Remove ANSI escape sequences from logs, before they hit our console

Also skip empty lines that may result from that or other SSH command
gibberish--empty lines in logs is no good for us.

Coming from SSH calls, there could be anything in them. Delete chars,
clear all the screen, change colors, whatever. These belong in the
original SSH sessions only, not on our logs.

The regex in question seems to address our needs well (7-bit ANSI C1
escape
sequences--https://en.wikipedia.org/wiki/C0_and_C1_control_codes). Ready-made
packages have been tried, like strip_ansi, and have proven to be
inferior in what they catch.
This commit is contained in:
Gustavo Lima Chaves 2021-04-27 16:56:16 -07:00 ΠΊΠΎΠΌΠΌΠΈΡ‚ ΠΏΡ€ΠΎΠΈΠ·Π²Ρ‘Π» Chi Song
Π ΠΎΠ΄ΠΈΡ‚Π΅Π»ΡŒ ea7bf7bb86
ΠšΠΎΠΌΠΌΠΈΡ‚ 9733f0abca
1 ΠΈΠ·ΠΌΠ΅Π½Ρ‘Π½Π½Ρ‹Ρ… Ρ„Π°ΠΉΠ»ΠΎΠ²: 10 Π΄ΠΎΠ±Π°Π²Π»Π΅Π½ΠΈΠΉ ΠΈ 0 ΡƒΠ΄Π°Π»Π΅Π½ΠΈΠΉ

ΠŸΡ€ΠΎΡΠΌΠΎΡ‚Ρ€Π΅Ρ‚ΡŒ Ρ„Π°ΠΉΠ»

@ -2,6 +2,7 @@
# Licensed under the MIT license.
import logging
import re
import sys
import time
from functools import partial
@ -14,6 +15,10 @@ from lisa.util import LisaException
ENV_KEY_RUN_LOCAL_PATH = "LISA_RUN_LOCAL_PATH"
DEFAULT_LOG_NAME = "LISA"
# We can't afford to let ANSI escape codes trash our
# stdout stream
_ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
class Logger(logging.Logger):
def lines(
@ -30,6 +35,11 @@ class Logger(logging.Logger):
temp_content.append(f"{key}: {value}")
content = temp_content
for line in content:
line = _ansi_escape.sub("", line)
# No good in logging empty lines (and they can happen via
# SSH stdout)
if not line or line.isspace():
continue
if prefix:
self.log(level, f"{prefix}{line}")
else: