Skip to content

Instantly share code, notes, and snippets.

@skewty
Created February 3, 2023 23:32
Show Gist options
  • Save skewty/ea8ee4f90f80715c821ec184e6e15365 to your computer and use it in GitHub Desktop.
Save skewty/ea8ee4f90f80715c821ec184e6e15365 to your computer and use it in GitHub Desktop.
Python logging using Emoji for loglevel
import logging
class EmojiFormatter(logging.Formatter):
"""Formatter that adds `levelemoji` field. Override emojis used my modifying EMOJI_MAP.
Example:
logging.basicConfig(format="%(asctime)s %(levelemoji)s %(message)s")
"""
# the INFO level should have the "Information" (U+2139) emoji but it doesn't seem to work in the next line
EMOJI_MAP = {"DEBUG": "🐛", "INFO": "ℹ️", "WARNING": "⚠️", "ERROR": "⛔", "EXCEPTION": "💣️", "CRITICAL": "💀"}
def formatMessage(self, record: logging.LogRecord) -> str:
setattr(record, "levelemoji", self.EMOJI_MAP.get(record.levelname, "❓"))
return super().formatMessage(record)
def setup_emoji_logging(*args, **kwargs):
logging.basicConfig(*args, **kwargs)
emoji_formatter = EmojiFormatter(
fmt=kwargs.get("format", "%(asctime)s,%(msecs).03d %(levelemoji)s %(message)s"),
datefmt=kwargs.get("datefmt", "%Y-%m-%d %H:%M:%S"),
style=kwargs.get("style", "%"),
)
for handler in logging.root.handlers:
handler.setFormatter(emoji_formatter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment