Interview Prep/Python for DevOps/Exceptions, context managers, files & logging

How should logging be configured in a library vs an application?

IntermediateConceptExceptions, context managers, files & logging
Answer

Libraries and modules only create loggers: log = logging.getLogger(__name__). They never call basicConfig or add handlers, so the application stays in control.

The application entry point configures logging once:

logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO"),
                    format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logging.getLogger("botocore").setLevel(logging.WARNING)

Calling basicConfig in an imported module is why "my log level change does nothing": only the first basicConfig call has effect (unless force=True).

All Python for DevOps questions Roadmap: Python for automation

More on Exceptions, context managers, files & logging