loguru icon indicating copy to clipboard operation
loguru copied to clipboard

Weird behavior when using f-string in _Logger__message

Open clairecp opened this issue 1 year ago • 1 comments

Hello Delgan, I've stumbled onto this weird behavior, I'm wondering if this is intended in any way?

from loguru import logger
import sys

logger.add(sys.stderr, level="TRACE")

lala = {"lk": "lk"}
extra = {"KJN": "JN"}
logger.log("TRACE", _Logger__message="lklk", details="", **extra)  # this is  ok
logger.log("TRACE", _Logger__message=f"lala={lala}", details="", **extra)  # this is not ok

Thank you !

clairecp avatar Sep 21 '23 13:09 clairecp

Hello.

When positional or keyword arguments are passed to the logging function, Loguru will formats them into the message. For example:

logger.info("My name is {name}", name="John")
# Output: "[INFO] My name is John"

This is equivalent to the str.format() built-in Python method.

In your second example, since you're using f-string, the message f"lala={lala}" becomes "lala={\"lk\": \"lk\"}" even before being sent to Loguru. Additionally, because arguments such as details and extra are provided, Loguru will call str.format() on the message, similarly to:

"lala={\"lk\": \"lk\"}".format(details="", **extra)

This causes an error, because of the {} in the string.

A possible workaround is to use Loguru's formatting rather than an f-string:

logger.log("TRACE", "lala={}", lala, details="", **extra)

Alternatively, you can also use bind() like this to disable Loguru formatting:

logger.bind(details="", **extra).log("TRACE", f"lala={lala}")

Delgan avatar Sep 21 '23 21:09 Delgan