Delgan / loguru

Python logging made (stupidly) simple
MIT License
19.62k stars 695 forks source link

Customising default global logger #1090

Closed kawahwookiee closed 7 months ago

kawahwookiee commented 7 months ago

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), setting opts, etc. when the script starts up, and be able to use this custom logger instance everywhere in the code, just like from loguru import logger. Anyone tried something like this before and succeeded?

Delgan commented 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.

lix19937 commented 4 months ago

It works! thks.