Created
March 31, 2022 12:19
-
-
Save JinBlack/2b039cb6a8c9ad7c85600e658dffed96 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Auto enable logger for ipython. path /home/<user>/.ipython/profile_default/startup/10-logger.py | |
import logging | |
import sys | |
class CustomFormatter(logging.Formatter): | |
bold_blue = "\x1b[34;1m" | |
bold_yellow = "\x1b[33;1m" | |
bold_magenta = "\x1b[35;1m" | |
bold_red = "\x1b[31;1m" | |
bold_green = "\x1b[32;1m" | |
reset = "\x1b[0m" | |
fmt = "[%(asctime)s] %(name)s\t - %(message)s (%(filename)s:%(lineno)d)" | |
fmt_level = "{%(levelname)s}\t" | |
COLORS = [f"\x1b[{i};10m" for i in range(90,97)] | |
FORMATS_COLOR = { | |
logging.DEBUG: bold_green, | |
logging.INFO: bold_blue, | |
logging.WARNING: bold_yellow, | |
logging.ERROR: bold_red, | |
logging.CRITICAL: bold_magenta, | |
} | |
def format(self, record): | |
c = id(record.name)%len(self.COLORS) | |
log_fmt = self.FORMATS_COLOR.get(record.levelno) + self.fmt_level + self.reset + self.COLORS[c] + self.fmt + self.reset | |
formatter = logging.Formatter(log_fmt) | |
return formatter.format(record) | |
# set up logging to console | |
console = logging.StreamHandler(sys.stdout) | |
console.setFormatter(CustomFormatter()) | |
# add the handler to the root logger | |
logging.basicConfig(handlers = [console], level=logging.DEBUG) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment