Delgan / loguru

Python logging made (stupidly) simple
MIT License
18.69k stars 682 forks source link

Adding data to log after API has started. #1143

Closed vlad-hill closed 1 month ago

vlad-hill commented 1 month ago

Hey, I'm working on a flask api script, and me and my team wanted to enrich our logs a bit. Until now, we were just using logger.info/error and the message inside without much concern.

We've come to the conclusion that we need to add some extra information in there, like the user's email who will log in to our platform.

Here's the situation: We have a Flask API. When we run the API, we have a Swagger page where the user can log in. However, here's the catch: we have 2 types of login, one local login and another using a key.

At this moment, Swagger is already running, and we can click on the login endpoint and enter the data. So i need to get the email data right after the login but this is where i started to ask myself, we already got like 4 logger.info til this point, is this going to work? So i get on a youtube video and get the information that the .bind is the thing

Captura de Tela 2024-05-17 às 18 52 27

I already had a logger.py that had a def for timezone, so I did a test here. I added the .format and made a test def to see if I could get the client's email and add into the log.

Using this def in my auth.py file, responsible for user login, I managed to get his email, but in a way that ended up being quite messy cause you know.

Captura de Tela 2024-05-17 às 19 06 41

I tried without the log = set_log just the set_log alone and didnt worked so, turning into a variable and using "log"over logger.info, it worked and i got the client email added to the log

Captura de Tela 2024-05-17 às 19 08 55

But maybe its just cause iam python/loguru noob but i didnt found a way to make this go to all my files, you know? Like i get this email in my auth file and i register this in logger.bind then all my files have my email along in the extra zone, i dont know if its just lack of understanding about the lib, but i wanted to know if there is a way that i can simply get the email, change in a file like logger.py and all my files that have logger.info/error will have the email along Maybe 20 endpoints that are currently full logged doesnt help, but im extremely curious how to make this work, i need to have the way i did in every file is something im missing about the bind method? Any word of advice would be everything, thanks m8!

Delgan commented 1 month ago

You need to use either logger.configure() to bind the value globally, or [logger.contextualize()]().