Delgan / loguru

Python logging made (stupidly) simple
MIT License
20k stars 702 forks source link

the problem with the log color using the coloring function #1205

Open 1liochka1 opened 2 months ago

1liochka1 commented 2 months ago
class Color(Enum):
    scarlet = "scarlet"
    pink = "pink"
    orange = "orange"
    blue = "blue"
    purple = "purple"

from colorama import init, Fore, Style
init()

def colorize(color: Color, text: str) -> str:
    match color:
        case Color.scarlet:
            return f"{Fore.RED}{text}{Style.RESET_ALL}"
        case Color.pink:
            return f"{Fore.MAGENTA}{text}{Style.RESET_ALL}"
        case Color.blue:
            return f"{Fore.CYAN}{text}{Style.RESET_ALL}"
        case Color.orange:
            return f"{Fore.YELLOW}{text}{Style.RESET_ALL}"
        case _:
            return f"{Fore.MAGENTA}{text}{Style.RESET_ALL}"

logger.info(f'111111111111111   {colorize(Color.orange, "2222222222222")}    11111111111111111111')

hi, I'm trying to write a part of a function that will color some phrases of my blog and for some reason, when using this function, all the text that comes after using this coloring turns red. Can you help me? thanks

image

Delgan commented 1 month ago

Loguru has its own internal management of argument colorization, so it's best not to mix it with another one.

When you do:

logger.info("11111   22222    11111")

Loguru will internally converts the message to (roughly):

f"{Fore.WHITE}11111   22222    11111{Style.RESET_ALL}"

With Fore.WHITE being the color of the current log level.

Now, because your logged message already cotnain Fore color instructions, the result would be:

f"{Fore.WHITE}11111   {Fore.YELLOW}22222{Style.RESET_ALL}    11111{Style.RESET_ALL}"

Loguru didn't expected colors to be part of the message. As a result, {Style.RESET_ALL} is called earlier that it should be.

The {Fore.WHITE} is missing to retrieve the log level color, and you end up with the default color of your console, which is red.