Custom, styled loglevel prefixes without markup=True #2798
-
Hey, I am using rich to style log messages which works beautifully for the most part, but I'm having issues with getting styled custom loglevel prefixes without enabling Example code: import logging
import logging.handlers
from rich.logging import RichHandler
LEVEL_PREFIX = {
"DEBUG": " \\[d] ",
"INFO": " [bold]\\[+][/] ",
"WARNING": " [yellow]\\[!][/] ",
"ERROR": " [red]\\[-][/] ",
"CRITICAL": " [red bold]\\[x][/] ",
}
package_logger = logging.getLogger(__name__)
package_logger.setLevel("DEBUG") # send everything to handlers
# stream handler with custom formatter
fmt = "{levelprefix!s}{message!s}"
ch = RichHandler(level="DEBUG", rich_tracebacks=True, show_time=False, show_level=False, show_path=False)
class PrefixFormatter(logging.Formatter):
def format(self, record, *args):
# register custom field
record.levelprefix = LEVEL_PREFIX.get(record.levelname, "")
return super().format(record, *args)
ch_fmt = PrefixFormatter(fmt, style="{")
ch.setFormatter(ch_fmt)
package_logger.handlers = [ch]
package_logger.warning("hi there!") Which prints
as expected. Is there any way to apply styling only to the prefixes? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
I would like to do something similar. I'd like to add the logger name to the format string, and apply custom styling such as making it bold or applying a color to separate it from the log message string. Something like: formatter = logging.Formatter("{name} {message}", style="{")
handler = RichHandler()
handler.setFormatter(formatter) with custom styling applied to |
Beta Was this translation helpful? Give feedback.
I solved this for my use case by calling
rich.markup.escape
inside a custom formatter:That way you can use
markup=True
but ignore control codes in messages.