pythonloggingloguru

How to use Loguru defaults + and extra information?


I'm still reaseaching about Loguru, but I can't find an easy way to do this. I want to use the default options from Loguru, I believe they are great, but I want to add information to it, I want to add the IP of a request that will be logged.

If I try this:

import sys
from loguru import logger
logger.info("This is log info!")
# This is directle from Loguru page
logger.add(sys.stderr, format="{extra[ip]} {extra[user]} {message}")
context_logger = logger.bind(ip="192.168.0.1", user="someone")
context_logger.info("Contextualize your logger easily")
context_logger.bind(user="someone_else").info("Inline binding of extra attribute")
context_logger.info("Use kwargs to add context during formatting: {user}", user="anybody")

That logs this: enter image description here

I know that with logger.remove(0) I will remove the default logs, but I want to use it to obtain something like this: 2022-02-03 15:16:54.920 | INFO | __main__:<module>:79 - XXX.XXX.XX.X - Use kwargs to add context during formatting: anybody, with XXX.XXX.XX.X being the IP. Using the default config (for color and the rest of thing) and adding a little thing to the format.

I'm trying to access the default configs, but I haven't been able to import them and use them with logger.add. I think I will have to configure everything from scratch.

Hope someone can help me, thanks.


Solution

  • I made the same question in the Github Repository and this was the answer by Delgan (Loguru maintainer):

    I think you simply need to add() your handler using a custom format containing the extra information. Here is an example:

    logger_format = (
        "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
        "<level>{level: <8}</level> | "
        "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | "
        "{extra[ip]} {extra[user]} - <level>{message}</level>"
    )
    logger.configure(extra={"ip": "", "user": ""})  # Default values
    logger.remove()
    logger.add(sys.stderr, format=logger_format)
    

    Extra: if you want to use TRACE level use this when adding the configurations:

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