Closed kawahwookiee closed 7 months ago
It is advise to configure the logger
globally in the entry point of your script, using logger.configure()
as follows:
from loguru import logger
if __name__ == "__main__":
logger.remove() Remove default handler.
logger.configure(extra={"instance_id": 42}) # Set default value for custom field.
logger.add("file.log", format="{extra[instance_id]} {message}") # Add handler with custom field.
logger.bind(instance_id=150).info("Some message") # Override the instance if needed.
However, if the instance_id
is static during the whole time of the application, you can also just integrate it in the format
directly.
It works! thks.
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?