Browse topics

Logging basics

Version
3.14
Review
Draft

Summary#

Create a named logger with getLogger and configure output once in the application. The root logger starts at WARNING. A named logger without its own level normally inherits an effective level from its ancestors. Pass values as separate arguments so the logger formats the message only when needed.

Syntax#

python
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
logger.info("processed %s items", count)
logger.exception("failed")  # inside an except block

Example#

python
import logging
import sys

logging.basicConfig(
    level=logging.INFO,
    stream=sys.stdout,
    format="%(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("billing")

logger.debug("hidden detail")
logger.info("charged %s cents", 250)

logging.basicConfig(level=logging.DEBUG)
logger.debug("still hidden")
logger.warning("retrying")

Expected output#

Text
INFO billing: charged 250 cents
WARNING billing: retrying

Common mistakes#

basicConfig does nothing when the root logger already has handlers. A module-level call such as logging.warning can add one before your setup runs. Configure logging first, or pass force=True to replace the handlers. Libraries should leave this configuration to the application.

Version applicability#

The syntax and example work on all Python 3 releases. The force argument of basicConfig requires Python 3.8 or later.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0