Mayil-AI-Sandbox / loguru-Jan2023

MIT License
0 stars 0 forks source link

Using custom logger across multiple modules (hashtag1162) #151

Open vikramsubramanian opened 2 months ago

vikramsubramanian commented 2 months ago

Hello,

I have a programme with a bunch of modules. In the main module a have a custom logger:

    from loguru import logger

    fmt = "[{time}] [{level}] - {extra} {name}:{function}:{line} - {message}"
    logger.remove()
    logger.add(format=fmt, sink="path/to/file")
    custom_logger = logger.bind(param_1=var_1, param_2=var_2)

I want to use my custom logger to catch all errors within all modules. For base logger I could just import logger in all modules and then use decorarator for all functions. What would be the best practice for custom logger? Should I pass it as the argument to submodules' functions and then explicitly callcustom_logger.error()withinexcept `blocks?

    from loguru import logger

    import submodule_1

    fmt = "[{time}] [{level}] - {extra} {name}:{function}:{line} - {message}"
    logger.remove()
    logger.add(format=fmt, sink="path/to/file")
    custom_logger = logger.bind(param_1=var_1, param_2=var_2)
    submodule_1.run(custom_logger)

)

mayil-ai[bot] commented 2 months ago

Some past issues to consider:

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

To efficiently manage logging across your entire application and ensure that all errors are captured and logged consistently, follow these steps:

  1. Centralize Logger Configuration:
    • Create a dedicated module for logger configuration.
# logger_config.py
from loguru import logger

# Define the log format
fmt = "[{time}] [{level}] - {extra} {name}:{function}:{line} - {message}"

# Remove default logger configuration
logger.remove()

# Add custom configuration
logger.add("path/to/file", format=fmt)

# Bind custom parameters
custom_logger = logger.bind(param_1="value1", param_2="value2")

def get_logger():
    return custom_logger
  1. Use the Logger in Submodules:
    • Import the logger from logger_config.py in your submodules.
# submodule_1.py
from logger_config import get_logger

# Get the custom logger
custom_logger = get_logger()

@custom_logger.catch
def run():
    # Your code here
    pass
  1. Main Module:
    • Ensure your main module imports and uses the logger correctly.
# main.py
from submodule_1 import run

if __name__ == "__main__":
    run()

By following these steps, you can efficiently manage logging across your entire application, ensuring that all errors are captured and logged consistently.

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