19  Logging (Basic)

import logging

19.1 Default Configuration

Default logging level is WARNING.

logging.debug("Small detail. Useful for troubleshooting.")
logging.info("This is informative.")
logging.warning("This is a warning message.")
logging.error("Uh oh. Something went wrong.")
logging.critical("We have a big problem!")
WARNING:root:This is a warning message.
ERROR:root:Uh oh. Something went wrong.
CRITICAL:root:We have a big problem!

19.2 Config with basicConfig()

19.2.1 Arguments

Arguments:

  • filename: Write log messages to the given file, rather than stderr.

  • filemode: Set to “a” to append to the log file (the default), or “w” to overwrite.

  • format: Use a custom format string for the log messages.

Format:

Attribute Format Description
asctime %(asctime)s Human-readable date/time
funcName %(funcName)s Name of function containing the logging call
lineno %(lineno)d The line number of the logging call
message %(message)s The log message
pathname %(pathname)s Full pathname of the source file of the logging call
levelname %(levelname)s Text logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL)
name %(name)s The logger’s name

19.2.2 Example: Change Log Level

Change The Logging Level to INFO.

logging.basicConfig(level=logging.INFO)
logging.debug("Small detail. Useful for troubleshooting.")
logging.info("This is informative.")
logging.warning("This is a warning message.")
logging.error("Uh oh. Something went wrong.")
logging.critical("We have a big problem!")
WARNING:root:This is a warning message.
ERROR:root:Uh oh. Something went wrong.
CRITICAL:root:We have a big problem!

19.2.3 Logging During Development

Here is the reccomended configuration for development:

# Wipes out previous log entries when program restarts
logging.basicConfig(filename="log.txt", filemode="w")
logging.debug("Small detail. Useful for troubleshooting.")
logging.info("This is informative.")
logging.warning("This is a warning message.")
logging.error("Uh oh. Something went wrong.")
logging.critical("We have a big problem!")
WARNING:root:This is a warning message.
ERROR:root:Uh oh. Something went wrong.
CRITICAL:root:We have a big problem!

19.3 Passing Argument

Recommend to pass arguments in the following way:

logging.info(format, *args)
logging.basicConfig(level=logging.INFO)

num_fruits = 14
fruit_name = "oranges"

logging.info(
    "We ate %d of your %s. Thanks!",
    num_fruits, fruit_name
    )

Use named fields:

fruit_info = {"count": 14, "name": "oranges"}
logging.info(
    "We ate %(count)d of your %(name)s. Thanks!",
    fruit_info)