[Python] How to use Loguru defaults + and extra information?

Discussão em 'Python' iniciado por Stack, Agosto 3, 2025.

  1. Stack

    Stack Membro Participativo

    I'm still researching 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: [​IMG]

    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.

    Continue reading...

Compartilhe esta Página