Add ansi colors to python logs

This commit is contained in:
GilbN 2023-04-10 23:36:19 +02:00
parent 2255a6739d
commit 17ce41cc0d
2 changed files with 50 additions and 5 deletions

View File

@ -3,6 +3,7 @@
import os
import logging
from logging.handlers import TimedRotatingFileHandler
from logging import LogRecord
import re
import platform
@ -17,6 +18,33 @@ else:
logger = logging.getLogger()
class ColorPercentStyle(logging.PercentStyle):
"""Custom log formatter that add color to specific log levels."""
grey = "38"
blue = "34"
yellow = "33"
red = "31"
cyan = "36"
def _get_color_fmt(self, color_code, bold=False):
if bold:
return "\x1b[" + color_code + ";1m" + self._fmt + "\x1b[0m"
return "\x1b[" + color_code + ";20m" + self._fmt + "\x1b[0m"
def _get_fmt(self, levelno):
colors = {
logging.DEBUG: self._get_color_fmt(self.grey),
logging.INFO: self._get_color_fmt(self.cyan),
logging.WARNING: self._get_color_fmt(self.yellow),
logging.ERROR: self._get_color_fmt(self.red),
logging.CRITICAL: self._get_color_fmt(self.red)
}
return colors.get(levelno, self._get_color_fmt(self.grey))
def _format(self, record:LogRecord):
return self._get_fmt(record.levelno) % record.__dict__
class CustomLogFormatter(logging.Formatter):
"""Formatter that removes creds from logs."""
ACCESS_KEY = os.environ.get("ACCESS_KEY","super_secret_key")
@ -42,6 +70,8 @@ class CustomLogFormatter(logging.Formatter):
return s
def formatMessage(self, record):
return ColorPercentStyle(self._fmt).format(record)
def configure_logging(log_level:str):
"""Setup console and file logging"""

View File

@ -99,10 +99,15 @@
strong {
color: rgba(218, 59, 138);
}
.warning-note {
color: #96a2b4;
}
.log-debug {color:lightgray}
.log-info {color:lightskyblue}
.log-warning {color:darkorange}
.log-error {color:red}
}
.warning-note {
color: #96a2b4;
}
@media (prefers-color-scheme: light) {
body {
@ -174,6 +179,11 @@
border-bottom: 1px solid #dcdcdc;
background: #f5f5f5;
}
.log-debug {color:#9bb0bf}
.log-info {color:#60707c}
.log-warning {color:darkorange}
.log-error {color:red}
}
body,
@ -577,8 +587,13 @@
fetch("ci.log")
.then(response => response.text())
.then(logs => {
document.getElementById("logs").innerText = logs
})
pylogs = logs.replace(/\[38;20m/gi,"<span class='log-debug'>"
).replace(/\[33;20m/gi,"<span class='log-warning'>"
).replace(/\[31;20m/gi,"<span class='log-error'>"
).replace(/\[36;20m/gi,"<span class='log-info'>"
).replace(/\[0m/gi,"</span>")
document.getElementById("logs").innerHTML = pylogs
})
</script>
</body>