Skip to content

Feature: Ability to automatically add color to format strings #1344

@rawrke

Description

@rawrke

Description 📝

Add the ability to automatically insert color variables in format strings. This would automatically put color tags around curly braces within a log message, and then render it to a color.

For instance, if the passed string to the logger is "a: {}, b: {}, c: {}", then loguru will add a preconfigured color tag to the string before sending off to a sink, like so: "a: <m>{}</m>, b: <m>{}</m>, c: <m>{}</m>". In this case, the tags <m></m> represent the color magenta.

Example 📇

NOTE: The below example does not reflect the required configuration to enable this feature. A feature flag would likely be required to preserve backwards compatibility.

import sys
from loguru import logger
import math

logger.remove()

# Enable color rendering within a message
logger = logger.opt(colors=True)

# Add a sample logger
logger.add(
    sys.stdout,
    colorize=True,
    format="<g>[{time:YYYY-MM-DD HH:mm:ss}]</g><level>[{level}]</level> {message}",
    level="DEBUG"
)

temp = {"name": "Bob", "occupation": "Builder"}
logger.debug("Houston, we have a {}", "cat")
logger.debug("Mapping: {a}, π: {pi:.4f}", a=temp, pi=math.pi)

And the output, note that the contents within the curly braces {} are automatically colored and italicized. This would be customizable based on user desires.

Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureRequest for adding a new feature

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions