Skip to content

Instantly share code, notes, and snippets.

@huskercane
Created October 10, 2024 13:12
Show Gist options
  • Save huskercane/7c3b538e4107fae7aff70ade50388ad6 to your computer and use it in GitHub Desktop.
Save huskercane/7c3b538e4107fae7aff70ade50388ad6 to your computer and use it in GitHub Desktop.
import logging
class CustomFormatter(logging.Formatter):
grey = "\x1b[38;20m"
yellow = "\x1b[33;20m"
red = "\x1b[31;20m"
bold_red = "\x1b[31;1m"
green = "\x1b[38;2;0;255;0m"
sky_blue = "\x1b[38;2;135;206;235m"
beige = "\x1b[38;2;245;245;220m"
reset = "\x1b[0m"
# format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
format = "%(asctime)s - %(levelname)s - [%(threadName)s] - %(message)s (%(filename)s:%(lineno)d)"
SELECTED_COLORS = {
logging.DEBUG: f"%(asctime)s - {beige} %(levelname)s {reset} - {sky_blue} [%(threadName)s] {reset} - %(message)s {sky_blue} (%(filename)s:%(lineno)d) {reset}",
logging.INFO: f"%(asctime)s - {green} %(levelname)s {reset} - {sky_blue} [%(threadName)s] {reset} - %(message)s {sky_blue} (%(filename)s:%(lineno)d) {reset}",
logging.WARNING: f"%(asctime)s - {yellow} %(levelname)s {reset} - {sky_blue} [%(threadName)s] {reset} - %(message)s {sky_blue} (%(filename)s:%(lineno)d) {reset}",
logging.ERROR: f"%(asctime)s - {red} %(levelname)s {reset} - {sky_blue} [%(threadName)s] {reset} - %(message)s {sky_blue} (%(filename)s:%(lineno)d) {reset}",
logging.CRITICAL: f"%(asctime)s - {bold_red} %(bold_red)s {reset} - {sky_blue} [%(threadName)s] {reset} - %(message)s {sky_blue} (%(filename)s:%(lineno)d) {reset}"
}
WHOLE_LINE_COLORS = {
logging.DEBUG: grey + format + reset,
logging.INFO: grey + format + reset,
logging.WARNING: yellow + format + reset,
logging.ERROR: red + format + reset,
logging.CRITICAL: bold_red + format + reset
}
def format(self, record):
log_fmt = self.SELECTED_COLORS.get(record.levelno)
formatter = logging.Formatter(log_fmt)
return formatter.format(record)
@huskercane
Copy link
Author

To add to your script

ch = logging.StreamHandler()

ch.setFormatter(CustomFormatter())

logging.basicConfig(level=logging.INFO, handlers=[ch])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment