import logging
19 Logging (Basic)
19.1 Default Configuration
Default logging level is WARNING
.
"Small detail. Useful for troubleshooting.")
logging.debug("This is informative.")
logging.info("This is a warning message.")
logging.warning("Uh oh. Something went wrong.")
logging.error("We have a big problem!") logging.critical(
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.INFO) logging.basicConfig(level
"Small detail. Useful for troubleshooting.")
logging.debug("This is informative.")
logging.info("This is a warning message.")
logging.warning("Uh oh. Something went wrong.")
logging.error("We have a big problem!") logging.critical(
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
="log.txt", filemode="w") logging.basicConfig(filename
"Small detail. Useful for troubleshooting.")
logging.debug("This is informative.")
logging.info("This is a warning message.")
logging.warning("Uh oh. Something went wrong.")
logging.error("We have a big problem!") logging.critical(
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:
format, *args) logging.info(
=logging.INFO)
logging.basicConfig(level
= 14
num_fruits = "oranges"
fruit_name
logging.info("We ate %d of your %s. Thanks!",
num_fruits, fruit_name )
Use named fields:
= {"count": 14, "name": "oranges"}
fruit_info
logging.info("We ate %(count)d of your %(name)s. Thanks!",
fruit_info)