OSPython.028: Python Logging Basics

Colored-pencil comic-book illustration of a programmer reviewing Python application logs.

Python logging records what a program is doing while it runs. Instead of scattering print() calls through production code, the standard logging module lets you label messages by severity and control which messages appear.

Corey Schafer demonstrates Python’s standard logging module, levels, formatting, and log files.

Start With One Logger

Python includes logging in its standard library, so a basic script needs no extra package. Import the module, configure a level, and write messages that describe useful events.

import logging

logging.basicConfig(level=logging.INFO)

logging.info("Application started")
logging.warning("Temperature is approaching the limit")

The key difference from print() is control. Logging gives each message a severity level and can later route messages to a console, file, or other handler without rewriting every call.

Understand The Five Common Levels

The standard levels are DEBUG, INFO, WARNING, ERROR, and CRITICAL. DEBUG is detailed diagnostic information; INFO records normal events; WARNING marks a potential problem; ERROR reports a failed operation; CRITICAL marks a severe failure.

logging.debug("Reading configuration")
logging.info("Service connected")
logging.warning("Retry count is high")
logging.error("Request failed")
logging.critical("Service cannot continue")

The configured logging level acts as a threshold. With level=logging.INFO, INFO and more severe messages appear, while DEBUG messages are filtered out.

Add Useful Context

A useful log says what happened and gives enough context to investigate it. Python can automatically include timestamps, severity, and logger names.

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(message)s"
)

logging.info("Worker connected")

This becomes especially useful after the program grows beyond one terminal session. Logs can show the sequence of events that happened before an error.

Logging And Exceptions Work Together

Logging does not replace exception handling. The earlier Python exceptions lesson explains try, except, else, and finally. Logging can record the failure when an exception is handled.

try:
    value = int("not-a-number")
except ValueError:
    logging.exception("Could not convert input")

logging.exception() is useful inside an exception handler because it records an ERROR-level message with traceback information.

Practical Example

Suppose a Python script polls an API. The previous REST API lesson covered requests, status codes, timeouts, and errors. Logging can now record whether each polling cycle succeeded without changing the API logic itself.

status_code = 200

if status_code == 200:
    logging.info("API poll succeeded")
else:
    logging.error("API poll failed: %s", status_code)

Basic Troubleshooting

If a message does not appear, first check the configured level. A DEBUG message will not appear when the threshold is INFO. Also confirm that configuration occurs before the messages you expect to capture.

Avoid logging passwords, API keys, authentication tokens, or other secrets. Logs often survive longer than terminal output and may be read by other systems or people.

Exercise

Create a short script that configures INFO logging, writes one INFO message, then deliberately catches a ValueError and records it with logging.exception(). Change the threshold to DEBUG and observe what changes.

Knowledge Check

  1. Why use logging instead of only print()?
  2. Which level is normally used for detailed diagnostic information?
  3. What happens to DEBUG messages when the configured level is INFO?
  4. Why is logging.exception() useful inside an exception handler?

Answers

  1. Logging provides severity levels and configurable output.
  2. DEBUG.
  3. They are filtered out.
  4. It records the error message plus traceback information.

Next Lesson

This lesson intentionally stops at logging basics. File handlers, rotating logs, and application-wide logger configuration belong in later focused lessons rather than being compressed into this one.

References

Primary reference: Python Logging HOWTO. For structured data used by many logged applications, review OSPython.026: JSON Serialization and Deserialization.

BitcoinVersus.Tech

Editor’s Note

We volunteer daily to help keep the information on this platform verifiably accurate. If you would like to support our independent research, please donate here: 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb

BitcoinVersus.tech is not a financial advisor. Content is provided for informational purposes.

2 responses to “OSPython.028: Python Logging Basics”

  1. […] with OSPython.028: Python Logging Basics if you need a refresher on DEBUG, INFO, WARNING, ERROR, and […]

    Like

  2. […] This lesson builds directly on OSPython.029: Logging to Files with FileHandler. If you need the logging levels first, review OSPython.028: Python Logging Basics. […]

    Like

Leave a comment