Python Logging
Like a Pro
Replace print() with levels, handlers, formatters, and rotating files. Nine interactive lessons that teach production-ready logging β by @PoeticGlenn.
What you will learn
The five standard log levels, how to configure the root logger and named loggers, attach console and file handlers, control message format, rotate log files, and follow practices that keep logs useful in real applications.
Why Logging Exists
print() is fine while you are exploring. In anything that runs longer than a few minutes β a web service,
a scheduled job, a data pipeline β you need messages that can be filtered by importance, written to files,
timestamped, and left running without flooding the terminal. That is what the standard library
logging module is for.
Logging gives you five severity levels, multiple destinations (console, files, network), structured message formats, and the ability to turn verbosity up or down without changing source code. Once you learn the core ideas β Logger, Handler, Formatter, Level β the rest of the module falls into place.
π€ print() vs logging
Why production code almost never relies on print for diagnostics
β The print() Habit
Print statements are always on, have no severity, and disappear when stdout is not captured. They also mix freely with real program output.
def process_order(order_id): print("Starting order", order_id) # always visible # ... work ... print("Order done") # no severity print("WARNING: low stock") # still just a string process_order(42)
β The logging Approach
Same idea with levels, so you can silence debug noise in production while still recording warnings and errors.
import logging logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") def process_order(order_id): logging.info("Starting order %s", order_id) # ... work ... logging.info("Order done") logging.warning("Low stock for order %s", order_id) process_order(42) logging.debug("This will not appear β level is INFO")
%s style: the message is only formatted if the level is enabled. That avoids expensive string work for disabled debug messages.π The Five Standard Levels
DEBUG β INFO β WARNING β ERROR β CRITICAL
π 1.1 Level Hierarchy
Each level has a numeric severity. A logger (or handler) only emits records at or above its configured level.
import logging print("DEBUG ", logging.DEBUG) print("INFO ", logging.INFO) print("WARNING ", logging.WARNING) print("ERROR ", logging.ERROR) print("CRITICAL", logging.CRITICAL) # Show filtering logging.basicConfig(level=logging.WARNING, format="%(levelname)-8s %(message)s", force=True) logging.debug("detail for developers") logging.info("normal progress") logging.warning("something unexpected") logging.error("a failure that was handled") logging.critical("system is unusable")
force=True (Python 3.8+) reconfigures even if basicConfig was already called β useful in notebooks and interactive runners.π 1.2 When to Use Each Level
- βDEBUG β detailed diagnostic information, usually only interesting during development
- βINFO β confirmation that things are working as expected (startup, completed jobs)
- βWARNING β something unexpected happened, but the software is still working
- βERROR β a serious problem; the software failed to perform a function
- βCRITICAL β a very serious error; the program itself may be unable to continue
βΆοΈ Basic Usage
Getting useful output in under a minute
π 2.1 basicConfig β The Quick Start
One call configures the root logger with a stream handler and a simple format.
import logging logging.basicConfig( level=logging.DEBUG, format="%(asctime)s | %(levelname)-8s | %(message)s", datefmt="%H:%M:%S", force=True, ) logging.debug("Connecting to database") logging.info("User logged in: alice") logging.warning("Disk space below 10%") logging.error("Failed to send email")
π 2.2 Named Loggers
Prefer logging.getLogger(__name__) so each module has its own logger and you can control verbosity per package.
import logging logging.basicConfig(level=logging.DEBUG, format="%(name)s | %(levelname)s | %(message)s", force=True) # Simulate two modules log_auth = logging.getLogger("myapp.auth") log_db = logging.getLogger("myapp.db") log_auth.info("Login attempt for user=bob") log_db.debug("Executing query: SELECT * FROM users") log_db.warning("Slow query (1.2s)") # Silence one package logging.getLogger("myapp.db").setLevel(logging.WARNING) log_db.debug("This debug line is now suppressed") log_db.warning("This warning still appears")
myapp.db does not affect myapp.auth. Setting it on myapp would affect both children.βοΈ Configuration Styles
basicConfig, dictConfig, and programmatic setup
π 3.1 Programmatic Handlers (explicit control)
Create a logger, attach a handler, and set a formatter yourself. This is the most flexible approach.
import logging import sys # Fresh logger for this example logger = logging.getLogger("demo") logger.setLevel(logging.DEBUG) logger.handlers.clear() # avoid duplicate handlers on re-run handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.INFO) formatter = logging.Formatter( "%(asctime)s [%(levelname)s] %(name)s: %(message)s", datefmt="%H:%M:%S", ) handler.setFormatter(formatter) logger.addHandler(handler) logger.debug("Not shown β handler level is INFO") logger.info("Application started") logger.error("Something failed", exc_info=False)
π 3.2 Useful Format Fields
Common placeholders you will use in format strings:
- β
%(asctime)sβ timestamp - β
%(levelname)sβ DEBUG / INFO / WARNING / β¦ - β
%(name)sβ logger name - β
%(message)sβ the log message - β
%(filename)s/%(lineno)dβ source location - β
%(funcName)sβ function that issued the log - β
%(process)d/%(threadName)sβ process / thread info
π€ Handlers β Where Logs Go
Console, files, and rotating files
π 4.1 StreamHandler (console)
Writes to sys.stderr by default. You already used it via basicConfig.
import logging import sys logger = logging.getLogger("console_demo") logger.handlers.clear() logger.setLevel(logging.DEBUG) sh = logging.StreamHandler(sys.stdout) sh.setFormatter(logging.Formatter("%(levelname)s β %(message)s")) logger.addHandler(sh) logger.info("Visible on stdout") logger.warning("Also visible")
π 4.2 FileHandler & RotatingFileHandler (concepts)
Typical production pattern: one rotating file for the application, console for interactive use.
import logging from logging.handlers import RotatingFileHandler import sys logger = logging.getLogger("app") logger.handlers.clear() logger.setLevel(logging.DEBUG) # Console β human readable console = logging.StreamHandler(sys.stdout) console.setLevel(logging.INFO) console.setFormatter(logging.Formatter("%(levelname)-8s %(message)s")) # In a real script you would also add: # file_handler = RotatingFileHandler("app.log", maxBytes=1_000_000, backupCount=3) # file_handler.setLevel(logging.DEBUG) # file_handler.setFormatter(...) # logger.addHandler(file_handler) logger.addHandler(console) logger.debug("Only goes to file (if configured)") logger.info("Goes to console and file") logger.error("Goes to both")
RotatingFileHandler keeps the last backupCount files when the current file exceeds maxBytes. TimedRotatingFileHandler rotates on a schedule instead.π¨ Formatters & Structured Messages
Make logs readable for humans and machines
π 5.1 Custom Format Strings
import logging import sys logger = logging.getLogger("fmt") logger.handlers.clear() logger.setLevel(logging.DEBUG) fmt = logging.Formatter( fmt="%(asctime)s | %(levelname)-8s | %(filename)s:%(lineno)d | %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) h = logging.StreamHandler(sys.stdout) h.setFormatter(fmt) logger.addHandler(h) logger.info("Service ready") logger.warning("Retry count exceeded")
π 5.2 Extra Fields & exc_info
Pass structured context with the extra dict, and attach exception info with exc_info=True.
import logging import sys logger = logging.getLogger("ctx") logger.handlers.clear() logger.setLevel(logging.DEBUG) fmt = logging.Formatter("%(levelname)s user=%(user)s | %(message)s") h = logging.StreamHandler(sys.stdout) h.setFormatter(fmt) logger.addHandler(h) logger.info("Login success", extra={"user": "alice"}) logger.warning("Rate limit near", extra={"user": "bob"}) try: 1 / 0 except ZeroDivisionError: logger.exception("Division failed") # includes traceback
logger.exception(...) is a convenience for logger.error(..., exc_info=True) inside an except block. It records the current exception automatically.β Best Practices
Habits that keep logs useful instead of noisy
π Guidelines
- βUse
logging.getLogger(__name__)in every module - βConfigure logging once at application startup (not in libraries)
- βPrefer
%s/%dstyle over f-strings so disabled levels stay cheap - βLog the exception with
logger.exceptionorexc_info=True, not only the message - βKeep DEBUG off in production; leave WARNING and above on
- βNever log secrets (passwords, tokens, full credit-card numbers)
- βUse rotating or timed handlers so log files cannot grow without bound
- βLibraries should only add handlers if the user has not configured logging (or document that they do)
π 6.1 A Minimal Production-Ready Snippet
Pattern you can copy into a real script (file parts commented for the browser runner).
import logging import sys def setup_logging(level=logging.INFO): root = logging.getLogger() root.handlers.clear() root.setLevel(level) console = logging.StreamHandler(sys.stdout) console.setFormatter(logging.Formatter( "%(asctime)s %(levelname)-8s [%(name)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S", )) root.addHandler(console) # Uncomment locally: # from logging.handlers import RotatingFileHandler # fh = RotatingFileHandler("app.log", maxBytes=2_000_000, backupCount=5) # fh.setFormatter(...) # root.addHandler(fh) setup_logging(logging.DEBUG) log = logging.getLogger(__name__) log.info("Application starting") log.debug("Config loaded") log.warning("Using default credentials β change them")
π Quick Navigation
Jump to any lesson
β Frequently Asked Questions
Common questions about the logging module
Usually because a handler was added more than once (e.g. calling configuration code on every request) or because both a child logger and the root logger have handlers and propagate is still True. Clear handlers before re-configuring, or set logger.propagate = False.
No. Libraries should only create named loggers and emit messages. Configuration belongs to the application that uses the library. If a library needs a fallback, it can add a NullHandler so that βNo handlers could be foundβ warnings are avoided.
A record must pass the loggerβs level first. If it does, it is offered to each handler, which applies its own level filter. Setting the logger to DEBUG and a console handler to INFO is a common way to send everything to a file while keeping the console quieter.
Inside an except block use logger.exception("message") or logger.error("message", exc_info=True). Both attach the current exception information to the log record.
Yes. The standard library logging module is designed to be used from multiple threads. Handlers take locks around the actual emit operation.
π Next Steps
You now have a practical foundation for application logging
β What You Covered
- Why
print()is not enough for anything that runs longer than a few minutes - The five standard levels and when each is appropriate
basicConfigand named loggers withgetLogger(__name__)- Programmatic setup with Handler + Formatter
- StreamHandler, FileHandler, and RotatingFileHandler patterns
- Format fields,
extra, andlogger.exception - Production-oriented best practices
Related modules: Exception Handling, Modules & Packages, and the main Curriculum.