Open vikramsubramanian opened 3 months ago
To implement the feature described in the Jira ticket, you need to customize the default logger instance provided by Loguru to include additional context (e.g., instance_id
) and settings (opts
). Here's how you can achieve this:
logger.configure()
method to apply the settings globally.logger.bind()
method to add the instance_id
to the extra
context of the logger.Here's a high-level overview of the steps in code:
from loguru import logger
def configure_logger(instance_id):
# Configure the logger with custom settings (opts)
logger.configure(
handlers=[
dict(sink=sys.stderr, format="<green>{time}</green> <level>{message}</level>", level="INFO")
# Add other handler configurations if needed
],
levels=[
dict(name="CUSTOM", no=25, color="<yellow>", icon="🔥"),
# Add other custom levels if needed
],
# Add other configurations if needed
)
# Bind 'instance_id' to the logger's extra context
logger = logger.bind(instance_id=instance_id)
return logger
# Usage in the main script or entry point of each instance
instance_specific_logger = configure_logger(instance_id="your_instance_id_here")
# Now, you can use 'instance_specific_logger' across your modules
In each module where logging is required, you would import instance_specific_logger
and use it for logging:
from path.to.module.with.configured.logger import instance_specific_logger as logger
logger.info("This log will have the 'instance_id' attached.")
Remember to replace "your_instance_id_here"
with the actual instance_id
you retrieve from your config file for each script instance.
This approach ensures that all log messages across your modules will include the instance_id
and any other custom fields you bind to the logger. The configure_logger
function should be called once at the startup of each script instance to set up the logger appropriately.
As an example: I have several instances of the same script each running with its own config file that contains
instance_id
. The scripts use multiple classes spread across several modules. I would like to override the default logger adding custom fields (i.e.instance_id
), settingopts
, etc. when the script starts up, and be able to use this custom logger instance everywhere in the code, just likefrom loguru import logger
. Anyone tried something like this before and succeeded? )