Sub topic 1
Why use logging instead of print
Prerequisites
This chapter assumes you can do the following:
- Write Python functions and import modules.
- Use
try/exceptto handle exceptions. - Run scripts from a terminal and tell standard output from standard error.
- Read a small class definition. Classes appear in later chapters, not here.
You do not need prior knowledge of the logging module. This chapter explains why it exists and shows its basic behavior. The chapters that follow cover each part in detail.
The print habit and where it breaks
Most programs start with print calls to see what the code is doing:
def charge(order_id, amount):
print("charging", order_id, amount)
if amount <= 0:
print("bad amount!", order_id)
return False
print("calling gateway")
return True
charge("A-100", 25.0)
charge("A-101", 0)This works while you sit at the terminal and debug one script. It stops working once the program runs somewhere you are not watching, such as a server, a scheduled job, or a library inside someone else's program. At that point print has these problems:
- No severity. A routine progress note and a failed payment look the same. You cannot ask for only the serious messages.
- No on/off switch. To silence debugging output you have to edit the code and delete or comment out lines. You then re-add them when the next bug appears.
- No metadata. There is no timestamp, no source module, and no line number unless you format them yourself in every call.
- One destination.
printwrites to standard output. Sending messages to a file, a network service, or several places at once means rewriting every call. - Mixed streams. Program output and diagnostic messages share
stdout. If your script writes results that another program reads through a pipe, your debug lines corrupt that data. - No control for callers. If you publish a library that prints, every user of that library gets your output, and they cannot turn it off.
The logging module in the standard library addresses each of these.
The same code with logging
Here is the same function using logging:
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger(__name__)
def charge(order_id, amount):
logger.info("Charging order %s for %.2f", order_id, amount)
if amount <= 0:
logger.warning("Order %s has a non-positive amount: %.2f", order_id, amount)
return False
logger.debug("Calling payment gateway for order %s", order_id)
return True
charge("A-100", 25.0)
charge("A-101", 0)Running it as a script prints something like this. Your timestamps will differ.
2026-11-26 11:31:26,844 INFO __main__: Charging order A-100 for 25.00
2026-11-26 11:31:26,845 INFO __main__: Charging order A-101 for 0.00
2026-11-26 11:31:26,845 WARNING __main__: Order A-101 has a non-positive amount: 0.00Several things changed:
- Each line has a timestamp, a severity (
INFO,WARNING), and the name of the module that wrote it. The format string toldloggingto add them, so no call site repeats that work. - The
debugmessage does not appear. The configured threshold isINFO, so anything less severe is dropped. To see it, changelevel=logging.INFOtolevel=logging.DEBUG. You edit one line instead of deletingprintcalls. - The output goes to standard error by default, so it does not mix with data your program writes to standard output.
The model in one picture
When you call logger.info(...), you are not writing text anywhere yet. You create a record, and a pipeline decides what happens to it.
This split is the main reason logging is more flexible than print:
- Your code decides what happened. It says "this is a warning about order A-101" and nothing else.
- Configuration decides what to do about it. That means which severities to keep, where to send them, and what they look like.
You can change the second part without touching the first. A developer can run with DEBUG on a laptop, and production can run with WARNING and a file destination. The code that emits messages is identical in both.
What you gain, concretely
| Need | With `print` | With `logging` |
|---|---|---|
| Filter by importance | Not possible | Set a level threshold |
| Turn off debug output | Edit the code | Change one configuration value |
| Timestamps and source | Format by hand every time | Set once in a formatter |
| Write to a file and the console | Rewrite every call | Attach two handlers |
| Record a traceback | Manual `traceback` calls | `logger.exception(...)` |
| Keep a library quiet by default | Not possible | Libraries emit records, applications choose output |
| Assert on messages in tests | Capture `stdout` | `assertLogs` |
Several of these items have their own chapters later in this tutorial.
Passing arguments instead of building strings
Look at how the earlier example passed values:
logger.info("Charging order %s for %.2f", order_id, amount)The message template and the values are separate arguments. logging merges them only if the record is actually going to be emitted. If the level would drop the message, the formatting never happens.
Compare the two styles:
import logging
logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(__name__)
items = list(range(1000))
# Deferred formatting: the message is never built, because DEBUG is below WARNING.
logger.debug("Processing %d items", len(items))
# Eager formatting: the f-string is built before logger.debug is even called.
logger.debug(f"Processing {len(items)} items")Both calls produce no output here. The second one still does the string work first. For a cheap len() that cost is negligible, but it adds up with expensive values or with calls inside hot loops. The first form also keeps the template constant, so tools that group similar messages can recognize them.
Common mistakes at this stage
- Using
printfor diagnostics in code that others import. Callers cannot silence it. Use a logger. - Calling
logging.info(...)directly in every module. These module-level functions use the root logger and hide where a message came from. The next chapters show how to use named loggers. - Expecting
debugandinfoto appear with no configuration. Without configuration, the default threshold isWARNING. Callinglogger.info("hello")in a bare script prints nothing. - Logging secrets. Passwords, tokens, and personal data in a log file outlive the process and are often copied to other systems. Do not log them.
A good rule: use print for the output that is the point of your program, such as a report or a result. Use logging for messages about what the program is doing.
Exercises
Exercise
A script writes its results to standard output so that another program can read them through a pipe. It also has print("connecting to database") for progress. What goes wrong, and which change fixes it?
Show answer
The progress line goes to the same stream as the results, so the reading program receives it as if it were data. Replace the progress print with logger.info("Connecting to database"). After logging.basicConfig(...) the message goes to standard error by default, so standard output carries only the results.
Exercise
You run a script that calls logger.info("Started") on a logger from logging.getLogger(__name__), but you never call basicConfig. Nothing is printed. Why, and what is the smallest change that shows the message?
Show answer
With no configuration, the default threshold is WARNING, so INFO records are dropped. Adding logging.basicConfig(level=logging.INFO) before the call lets the message through.