Mayil-AI-Sandbox / loguru-Jan2023

MIT License
0 stars 0 forks source link

Adding data to log after API has started. (hashtag1143) #164

Open vikramsubramanian opened 2 months ago

vikramsubramanian commented 2 months 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 <img width="925" alt="Captura de Tela 2024-05-17 às 18 52 27" src="

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. <img width="925" alt="Captura de Tela 2024-05-17 às 19 06 41" src=" 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 <img width="730" alt="Captura de Tela 2024-05-17 às 19 08 55" src=" 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! )

mayil-ai[bot] commented 2 months ago

Some past issues to consider:

Here are some code snippets that may help you get started:

To enrich logs with user email information after the user logs in, follow these steps:

  1. Centralized Logger Configuration:
    • Modify logger.py to configure the logger and provide a function to bind user-specific context.
# logger.py
from loguru import logger

def configure_logger():
    logger.add("path/to/logfile.log", format="{time:YYYY-MM-DD at HH:mm:ss} {message} | {extra[email]}")
    return logger

def bind_user_email(email):
    return logger.bind(email=email)
  1. Capture User Email After Login:
    • Modify the login handling code to bind the user email to the logger after a successful login.
# auth.py
from flask import Flask, request, jsonify
from logger import configure_logger, bind_user_email

app = Flask(__name__)
logger = configure_logger()

@app.route('/login', methods=['POST'])
def login():
    # Assume user authentication logic here
    user_email = request.json.get('email')  # Extract user email from request
    if authenticate_user(request.json):  # Placeholder for actual authentication logic
        logger_with_email = bind_user_email(user_email)
        logger_with_email.info("User logged in")
        return jsonify({"message": "Login successful"}), 200
    else:
        logger.error("Login failed")
        return jsonify({"message": "Login failed"}), 401

def authenticate_user(credentials):
    # Placeholder for actual authentication logic
    return True

if __name__ == '__main__':
    app.run(debug=True)
  1. Ensure Consistent Logging Across Files:
    • Use the logger_with_email instance in other parts of the application to ensure the email context is included in all logs.
# some_other_module.py
from logger import bind_user_email

def some_function(user_email):
    logger_with_email = bind_user_email(user_email)
    logger_with_email.info("Some action performed")
  1. Avoid Duplicate Logs:
    • Ensure that logger.add() is called only once during the configuration step to avoid duplicate log entries.
# logger.py
from loguru import logger

def configure_logger():
    if not logger._core.handlers:
        logger.add("path/to/logfile.log", format="{time:YYYY-MM-DD at HH:mm:ss} {message} | {extra[email]}")
    return logger

💡 To rerun Mayil, comment mayil-ai rerun. Mayil will incorporate any new context added to the ticket. Include details in your rerun comment to guide Mayil!