Created
October 23, 2025 13:21
-
-
Save vlntnwbr/835900b51e4e6e290a50b803fa6f9e18 to your computer and use it in GitHub Desktop.
a simple base logging function that sets up a package level logger that optionally outputs in color
This file contains hidden or 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
| def setup_logging(level: str | int, colored: bool) -> logging.Logger: | |
| """Set up logging for the application.""" | |
| class ColorFormatter(logging.Formatter): | |
| """Logging formatter for colored output.""" | |
| RESET_STYLE = "\033[0m" # ANSI code to reset all style information | |
| LEVEL_COLOR = { | |
| # map logging levels to colorized ansi style codes | |
| # the string must follow this pattern "\033[<code>m" | |
| # lookup other supported color codes here | |
| # https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit | |
| logging.DEBUG: "\033[36m", # Cyan | |
| logging.INFO: "\033[32m", # Green | |
| logging.WARNING: "\033[33m", # Yellow | |
| logging.ERROR: "\033[31m", # Red | |
| logging.CRITICAL: "\033[35m" # Magenta | |
| } | |
| def format(self, record): | |
| "Add color to the otherwise regularly formatted record." | |
| color = self.LEVEL_COLOR.get(record.levelno, self.RESET_STYLE) | |
| formatted = super().format(record) | |
| return f"{color}{formatted}{self.RESET_STYLE}" | |
| use_formatter = ColorFormatter if colored else logging.Formatter | |
| formatter = use_formatter( | |
| "%(asctime)s - %(name)s - %(levelname)s - %(message)s", | |
| datefmt="%Y-%m-%d %H:%M:%S" | |
| ) | |
| handler = logging.StreamHandler() | |
| handler.setFormatter(formatter) | |
| logger = logging.getLogger(__package__) | |
| logger.setLevel(level) | |
| logger.addHandler(handler) | |
| logger.propagate = False | |
| return logger |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment