Your script runs every night at 2 am and emails a sales report. One morning the email doesn't arrive. What happened? Did it crash, did the data file go missing, or did the email server refuse it? If the script only used print, that output vanished when the terminal closed. If it used logging, there's a file that says exactly what happened, when, and how serious it was. That's the reason to learn Python logging for beginners: it's print that remembers.
The built-in logging module records messages with a time and a level (debug, info, warning, error, critical). You can send them to the screen, a file or both, and turn the detail up or down without touching the rest of your code. Every serious Python program, from Django sites to data pipelines, uses it.
What you need first: Python exceptions and Python modules and packages.
Key terms
- Log: a record of what a program did, usually one line per event, with a time.
- Log level: how serious a message is: DEBUG, INFO, WARNING, ERROR or CRITICAL.
- Logger: the object you call to write log messages, such as
logger.info(...). - Handler: decides where messages go: the screen, a file, an email.
- Formatter: decides what each line looks like, such as time, level and message.
Why not just use print?
print is fine while you're learning or quickly checking a value. For a program that others use, or that runs on its own, it falls short:
print | logging | |
|---|---|---|
| Shows the time | No | Yes, if you ask for it |
| Shows how serious it is | No | Yes, every message has a level |
| Turn detail on or off | Delete or comment out lines | Change one setting |
| Save to a file | Extra code | One setting |
| Include the full traceback of an error | Extra code | logger.exception(...) |
A good rule: use print for output the user is meant to see, such as a result or a menu. Use logging for messages about what the program is doing.
The five log levels
| Level | Number | Use it for | Example |
|---|---|---|---|
DEBUG | 10 | Details for finding bugs | "Row 41 parsed: {'name': 'Ahana'}" |
INFO | 20 | Normal progress | "Loaded 1,204 orders" |
WARNING | 30 | Something odd, but the program carries on | "3 rows had no price; skipped" |
ERROR | 40 | Something failed | "Could not send email" |
CRITICAL | 50 | The program can't continue | "Database unreachable; stopping" |
The logger has a minimum level. Messages below it are ignored. By default that minimum is WARNING, which surprises everyone the first time:
import logging
logging.debug("Starting up")
logging.info("Loaded 1,204 orders")
logging.warning("3 rows had no price")
logging.error("Could not send email")
WARNING:root:3 rows had no price
ERROR:root:Could not send email
The debug and info messages didn't appear. The format is LEVEL:logger name:message, and root is the name of the default logger. Log messages go to the error stream (stderr), not to normal output, so in some editors they appear in red. That's normal; it doesn't mean something broke.
Setting up logging with basicConfig
logging.basicConfig sets the minimum level and the format in one call. Call it once, at the start of your program, before any logging happens:
import logging
logging.basicConfig(
level=logging.INFO,
format="%(levelname)s | %(message)s",
)
logging.debug("Not shown: below INFO")
logging.info("Report started")
logging.warning("Using yesterday's exchange rate")
INFO | Report started
WARNING | Using yesterday's exchange rate
The format string uses placeholders inside %( )s. The ones you'll use most:
| Placeholder | Shows |
|---|---|
%(asctime)s | Date and time, like 2026-12-03 02:00:01,532 |
%(levelname)s | INFO, WARNING and so on |
%(name)s | The logger's name |
%(message)s | Your message |
%(filename)s, %(lineno)d | File and line number of the logging call |
%(funcName)s | The function that logged it |
A typical real-world format is "%(asctime)s %(levelname)s %(name)s: %(message)s". We leave asctime out of the examples here only so the outputs match yours; in real programs, always include the time.
Logging to a file
Add filename= and the messages go to a file instead of the screen:
import logging
from pathlib import Path
logging.basicConfig(
filename="report.log",
level=logging.INFO,
format="%(levelname)s %(message)s",
encoding="utf-8",
)
logging.info("Report started")
logging.info("Sent to ahana@example.com")
print(Path("report.log").read_text(encoding="utf-8"))
INFO Report started
INFO Sent to ahana@example.com
By default, new lines are added to the end of the file each run (mode "a"), so the log builds up over days. Pass filemode="w" to start a fresh file each run. Log files can grow huge on a server; logging.handlers.RotatingFileHandler starts a new file once one reaches a set size.
Adding values to messages
Pass values as extra arguments, with %s where each goes:
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
orders = 1204
city = "Pune"
logging.info("Loaded %s orders for %s", orders, city)
INFO Loaded 1204 orders for Pune
f-strings work too, as in logging.info(f"Loaded {orders} orders"), and plenty of code uses them. The %s style has one advantage: if the message's level is switched off, Python never builds the string at all. That matters for debug messages inside loops that run lakhs of times.
Logging exceptions
Inside an except block, logging.exception logs your message at ERROR level plus the full traceback, so you can see exactly where it failed:
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
def average(marks):
return sum(marks) / len(marks)
try:
average([])
except ZeroDivisionError:
logging.exception("Could not calculate the average")
logging.info("Carrying on with the next class")
ERROR Could not calculate the average
Traceback (most recent call last):
ZeroDivisionError: division by zero
INFO Carrying on with the next class
We've shortened the traceback here; yours also shows the file names and lines in between. The program didn't crash: the error was recorded and the script carried on. That's the pattern for jobs that process many items, where one bad item shouldn't stop the rest.
Named loggers: one per module
The logging.info(...) calls so far use the root logger. In a program with several modules, give each module its own logger, named after the module:
import logging
logger = logging.getLogger(__name__)
__name__ is the module's name ("__main__" when you run the file directly, "billing" when billing.py is imported). Each log line then says which module wrote it, through %(name)s:
import logging
logging.basicConfig(level=logging.INFO, format="%(name)s %(levelname)s %(message)s")
billing_log = logging.getLogger("billing")
email_log = logging.getLogger("email")
billing_log.info("Invoice 1042 created")
email_log.warning("Mail server slow; retrying")
billing INFO Invoice 1042 created
email WARNING Mail server slow; retrying
The usual pattern in a project:
- In every module:
logger = logging.getLogger(__name__), thenlogger.info(...)and so on. - In the main script only: one
logging.basicConfig(...)call that sets the level, format and destination for everything.
Libraries you install use their own named loggers. If one is too chatty, quieten it alone: logging.getLogger("urllib3").setLevel(logging.WARNING).
Screen and file at the same time
basicConfig can take a list of handlers, so messages go to both places:
import logging
import sys
from pathlib import Path
logging.basicConfig(
level=logging.INFO,
format="%(levelname)s %(message)s",
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler("app.log", mode="w", encoding="utf-8"),
],
)
logging.info("Shown on screen and saved")
logging.shutdown()
print("File says:", Path("app.log").read_text(encoding="utf-8").strip())
INFO Shown on screen and saved
File says: INFO Shown on screen and saved
logging.shutdown() makes sure everything is written to the file before we read it back. Python calls it automatically when a program ends.
Where logging is used
- Scheduled scripts and automation: the log file is the only record of what happened while nobody was watching.
- Web servers: Django, Flask and FastAPI log every request; you add your own messages to the same system.
- Data pipelines: logging how many rows were read, skipped and saved at each step makes problems easy to trace.
- Machine learning training: logging the loss after each epoch, with times, to compare runs.
Common mistakes
- Expecting
logging.infoto show by default. The default level is WARNING; setlevel=logging.INFO. - Calling
basicConfigafter logging has already happened, or calling it in several modules. Only the first call takes effect (unless you passforce=True); call it once in the main script. - Logging passwords, OTPs, card numbers or Aadhaar numbers. Log files get shared and copied. Mask sensitive values or leave them out.
- Using
logging.errorinsideexceptwhen you want the traceback. Uselogging.exception. - Leaving hundreds of
printcalls in a finished program instead of switching to logging.
Practice
- Set up logging so INFO and above are shown in the format
[LEVEL] message, then log one info and one error message.
Show the answer
import logging
logging.basicConfig(level=logging.INFO, format="[%(levelname)s] %(message)s")
logging.info("Backup started")
logging.error("Backup folder not found")
[INFO] Backup started
[ERROR] Backup folder not found
- Which of these messages appear if the level is set to
logging.WARNING: debug, info, warning, error, critical?
Show the answer
Warning, error and critical. A message appears when its level number is at least the logger's level: WARNING is 30, so DEBUG (10) and INFO (20) are hidden.
- Process this list of prices, logging a warning for each one that can't be converted and an info message with the total at the end.
raw_prices = ["120", "abc", "45.5", "", "80"]
Show the answer
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
raw_prices = ["120", "abc", "45.5", "", "80"]
total = 0.0
for i, raw in enumerate(raw_prices):
try:
total += float(raw)
except ValueError:
logging.warning("Row %s: bad price %r, skipped", i, raw)
logging.info("Total of valid prices: %s", total)
WARNING Row 1: bad price 'abc', skipped
WARNING Row 3: bad price '', skipped
INFO Total of valid prices: 245.5
- Why might this log line be a problem in a real app?
import logging
phone, pin = "9876543210", "4821"
logging.info("User %s logged in with PIN %s", phone, pin)
Show the answer
It writes a secret PIN into the log file, which may be read by developers, stored on other servers or leaked. Never log passwords, PINs, OTPs or full card numbers. Log only the user's ID, or a masked phone number like 98XXXXX210.
- Write a function
divide(a, b)that logs the full traceback withlogging.exceptionwhenbis 0, and returnsNonein that case.
Show the answer
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
logger = logging.getLogger(__name__)
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
logger.exception("divide(%s, %s) failed", a, b)
return None
print(divide(10, 4))
print(divide(1, 0))
2.5
ERROR divide(1, 0) failed
Traceback (most recent call last):
ZeroDivisionError: division by zero
None
The traceback is shortened here, as before.
Interview questions
Why use logging instead of print in production code?
Logging adds severity levels, timestamps and source information; it can be filtered by level without changing code; it can send output to files, the console or external services through handlers; and it can record full tracebacks. print does none of this.
What are the standard logging levels in Python?
DEBUG (10), INFO (20), WARNING (30), ERROR (40) and CRITICAL (50). A logger set to a level ignores messages below it. The root logger's default level is WARNING.
Why use logging.getLogger(__name__) in each module?
It creates a logger named after the module, so log lines show where they came from, and the level of each module's logger can be adjusted separately. Loggers form a hierarchy by dotted name, so settings on a package's logger apply to its modules too.
Key takeaways
- Use
printfor output meant for users, andloggingfor messages about what the program is doing. - Five levels: DEBUG, INFO, WARNING, ERROR and CRITICAL. The default level is WARNING.
- Call
logging.basicConfig(level=..., format=..., filename=...)once, in the main script. - Include
%(asctime)sin real formats, and uselogger.exceptioninsideexceptto keep the traceback. - Use
logging.getLogger(__name__)in each module, and never log secrets.
Frequently asked questions
Why is my logging.info message not showing?
The root logger's level is WARNING by default, so INFO and DEBUG are hidden. Call logging.basicConfig(level=logging.INFO) at the start of the program. If it still doesn't show, something may have called basicConfig earlier; pass force=True to replace that set-up.
Where does Python logging write by default?
To standard error (stderr) on the terminal, in the format LEVEL:name:message. Pass filename= to basicConfig to write to a file instead.
Is logging slow?
Not noticeably for normal use. Messages below the current level are skipped quickly, especially with %s-style arguments. Writing thousands of lines a second to a file can slow a program down, so keep DEBUG messages out of very hot loops in production.
What to learn next
- Start modelling real things with Python classes and objects.
- Revise error handling in Python exceptions.
- Find the files your logs mention with Python pathlib.