Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] How to use Loguru defaults + and extra information? #586

Closed
antusystem opened this issue Feb 4, 2022 · 7 comments
Closed

[Question] How to use Loguru defaults + and extra information? #586

antusystem opened this issue Feb 4, 2022 · 7 comments
Labels
question Further information is requested

Comments

@antusystem
Copy link

Hi, 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:
1yVgp

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.

@antusystem antusystem changed the title How to use Loguru defaults + and extra information? [QUESTION] How to use Loguru defaults + and extra information? Feb 4, 2022
@antusystem antusystem changed the title [QUESTION] How to use Loguru defaults + and extra information? [Question] How to use Loguru defaults + and extra information? Feb 4, 2022
@Delgan
Copy link
Owner

Delgan commented Feb 6, 2022

Hi @antusystem.

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)

@Delgan Delgan added the question Further information is requested label Feb 6, 2022
@antusystem
Copy link
Author

antusystem commented Feb 6, 2022

Thanks I believe that works for me, I just need to configure the IP and USER for every run, think that with bind or opt I can change that easily, I believe I see it in the tutorial, I will check it later.

Another question I just remember (and try it but I want to be sure). To log at TRACE level I would do this: logger.add(sys.stderr, format=logger_format, level="TRACE") ? I believe yes, I just run code with it and it does show 2 logs, like in my first question. Thanks for your help.

EDIT: I saw the code in my first post and yes, with logger.bind(user="someone_else").info("Inline binding of extra attribute") can be a good way of login the user or ip not in a global scope, I believe configure has global scope

@Delgan
Copy link
Owner

Delgan commented Feb 9, 2022

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 and configure() to set the default value globally. 👍

@rmaruseve
Copy link

Hi @Delgan,

I added one extra parameter with configure () and with this implementation, it was not possible to log the dict message.

logger.configure(extra=dict(ex=""))
logger.remove()
logger.add(sys.stdout, format="[{level.name: ^8}] [{extra[ex]}] {message}")

logger.info({'status': 200, 'json': 'json'}, ex= "ex")
Exception has occurred: AttributeError
'dict' object has no attribute 'format'

Regular logging with string works.

@Delgan
Copy link
Owner

Delgan commented Mar 1, 2022

@rmaruseve Hi.

Usually, arguments passed to a log function are intended to be used to format the message:

logger.info("Return code: {code}", code=200)
# => "Return code: 200"

In your case, the message isn't a str as expected but a dict, hence the error when Loguru tries to call message.format(*args, **kwargs).

You can use .bind() instead to save arguments to the extra dict:

logger.bind(ex="ex").info({'status': 200, 'json': 'json'})

Later I will provide a way to optionally disable message formatting, but it's not yet implemented.

@Delgan Delgan closed this as completed May 2, 2022
@Ericwonne
Copy link

Ericwonne commented Dec 15, 2022

@Delgan hello, thanks for any reply in advance.
for the code you gave above:

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)

I did a practice, finding if ip and user is "" by default and not given in a log record, they will be shown as 0, which is not anticipated, so can we adjust that (to empty string)?

@Delgan
Copy link
Owner

Delgan commented Dec 15, 2022

@Ericwonne Not sure what you mean, the values are actually displayed as "" not 0 when I try on my computer.

Please open a new ticket with a fully reproducible example so I can better help you. 👍

SvenRohrTNG added a commit to dahlker/codeassistant-vscode-endpoint-server that referenced this issue Aug 17, 2023
Each process now writes to its own log file.

Documentation is in https://loguru.readthedocs.io/en/stable/overview.html
For hints on how to format log message, see
Delgan/loguru#586
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

4 participants