[Question] How to use Loguru defaults + and extra information?
See original GitHub issueHi, 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 tried 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:
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.
Issue Analytics
- State:
- Created 2 years ago
- Comments:7 (4 by maintainers)
Top GitHub Comments
Hi @antusystem.
I think you simply need to
add()
your handler using a customformat
containing the extra information. Here is an example:Indeed, you need to specify
level="TRACE"
if you want all logs of"TRACE"
level or above to be propagated to the handler (the default is"DEBUG"
).You can use
bind()
where you need to set an user locally andconfigure()
to set the default value globally. 👍