Part 11 / Topic 8 of 12
Logging
Logging means recording what your program does, with a level of importance and a time. Unlike print, you can switch messages on or off and send them to a file, without changing your code.
Like a flight's black box: it records quietly, and you read it when something goes wrong.
print |
logging |
|
|---|---|---|
| Turn off debug messages | Delete the lines | Change one level= |
| Shows time, level, module | No | Yes, with a format string |
| Write to a file | Extra code | filename= |
| Goes to | stdout | stderr by default (the error stream) |
Levels (lowest to highest)
| Level | Use for |
|---|---|
DEBUG |
Details for developers, e.g. each step of a loop |
INFO |
Normal events, e.g. "Order placed" |
WARNING |
Something odd, the program goes on (the default level) |
ERROR |
Something failed |
CRITICAL |
The program cannot go on |
Only messages at or above the chosen level are shown.
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
logger = logging.getLogger(__name__)
logger.debug("Stock check details") # hidden: DEBUG is below INFO
logger.info("Order placed: %d x %s", 3, "Pen")
logger.warning("Only %d notebooks left", 2)
Output (on stderr):
INFO __main__: Order placed: 3 x Pen
WARNING __main__: Only 2 notebooks left
basicConfig(...)sets up logging once, at the start of the program (not in a module that others import).getLogger(__name__)gives each module its own logger, named after the module ("shop","grade_calculator";"__main__"for the script you ran).- Pass values as arguments (
"%d x %s", 3, "Pen") instead of an f-string. The text is only built if the message is shown. logger.exception("...")insideexceptlogs at ERROR level and adds the traceback.
Format string and logging to a file
| Placeholder | Shows |
|---|---|
%(asctime)s |
date and time |
%(levelname)s |
INFO, WARNING, … |
%(name)s |
logger name |
%(message)s |
your message |
import logging
logging.basicConfig(
filename="demo_app.log", # write here instead of the screen
encoding="utf-8",
level=logging.DEBUG,
format="%(asctime)s %(levelname)-8s %(name)s: %(message)s",
)
logging.getLogger(__name__).info("Shop opened")
%(levelname)-8s pads the level to 8 characters so the columns line up. To log to the screen and a file at the same time, pass handlers=[...]; see 05_logging_basics.py.
Read more: the official logging HOWTO.
Done here? The practice set for Part 11 — 7 exercises with solutions — is on the part page.