Mayil-AI-Sandbox / loguru-Jan2023

MIT License
0 stars 0 forks source link

Support printf-style formatting? (hashtag1151) #159

Open vikramsubramanian opened 2 months ago

vikramsubramanian commented 2 months ago

I'm looking into migrating an existing project from Python's built-in logging facilities to loguru. The code base uses printf-style formatting quite extensively, e.g.

logger.info("Loading project %s", project.name)

Unfortunately loguru doesn't seem to be plug&play in this situation, unless I'm missing something. Is there a way to have loguru support percent-style formatting? )

mayil-ai[bot] commented 2 months ago

Some past issues to consider:

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

Loguru does not natively support printf-style (%s) formatting. Instead, it uses {} style formatting. Here are the steps to adapt your existing code:

  1. Using str.format() Method: Convert the printf-style formatting to the str.format() method.

    from loguru import logger
    
    project_name = "example_project"
    logger.info("Loading project {}".format(project_name))
  2. Using f-strings (Python 3.6+): If you are using Python 3.6 or later, you can use f-strings for a more concise approach.

    from loguru import logger
    
    project_name = "example_project"
    logger.info(f"Loading project {project_name}")
  3. Custom Wrapper Function: Create a wrapper function to handle the conversion from printf-style to Loguru's style.

    from loguru import logger
    
    def log_info(message, *args):
       formatted_message = message % args
       logger.info(formatted_message)
    
    project_name = "example_project"
    log_info("Loading project %s", project_name)

By following these steps, you can smoothly transition your logging from the built-in logging module to Loguru while maintaining the readability and functionality of your log messages.

💡 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!