Python Logging Basics
Logging is a record of what a program did, kept for the developer. print shows values to the user of a program.
Five levels, five numbers
Each level has a number. A bigger number means a more serious problem.
import logging
print(logging.DEBUG, logging.INFO)
print(logging.WARNING, logging.ERROR)
print(logging.CRITICAL)Your first logger
basicConfig sets the lowest level to show. The logger sends the messages.
import logging, sys
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout, format="%(levelname)s: %(message)s")
logger = logging.getLogger(__name__)
logger.info("App started")The silent levels
This setup never sets a level. Watch which message appears and which one does not.
import logging, sys
logging.basicConfig(stream=sys.stdout, format="%(levelname)s: %(message)s")
logger = logging.getLogger("demo")
logger.info("You will not see this")
logger.warning("You will see this")Example
import logging, sys
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout, format="%(levelname)s: %(message)s")
logger = logging.getLogger(__name__)
logger.debug("Loading settings")
logger.info("App started")
logger.warning("Disk space is low")
logger.error("Could not save the file")
logger.critical("App must stop")Key points
- Logger: an object that receives log messages, one for each part of a program
- Level: how serious a message is, from DEBUG up to CRITICAL
- Use logging.getLogger(__name__) to make a logger named after the current module
- Use logging.basicConfig(...) once, near the start, to set up logging
- The root logger starts at WARNING, so INFO and DEBUG stay silent at first
- print always shows
- A program uses logging to keep a record of what it did.
In this example, basicConfig sets the level to DEBUG and sends output to sys.stdout. The format keeps only the level and the message. The logger then sends one message at each of the five levels. DEBUG is the lowest level, so every message shows. The last two levels report real trouble. CRITICAL is the most serious level of all.
Note
A log message shows only when its level reaches the level you set.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Your program calls logger.info(...) and nothing appears. No code changed the logging setup. Why is the message missing?