Tutorials Logic, IN info@tutorialslogic.com

Python Logging: Track What a Program Is Doing

Python Logging

Logging records what a program is doing while it runs.

Unlike print, logs can include levels such as debug, info, warning, and error.

Use logging when a script or application needs useful runtime history without mixing debug text into normal output.

Log Levels

Levels describe how important a message is. Debug messages are detailed; error messages show real failures.

  • Use debug for developer-only details.
  • Use info for normal progress.
  • Use warning or error when something needs attention.

Basic Logging

Basic Logging
import logging

logging.basicConfig(level=logging.INFO)

logging.info("Starting report")
logging.warning("No category filter selected")
Output
INFO:root:Starting report
WARNING:root:No category filter selected

The level controls which messages appear.

Exception Logs

logging.exception records a message plus the traceback for the current exception.

  • Use it inside an except block.
  • Keep the message specific to the failed action.
  • Do not swallow an error silently unless recovery is intentional.

Log a Failed Conversion

Log a Failed Conversion
import logging

value = "free"

try:
    price = int(value)
except ValueError:
    logging.exception("Could not convert price: %s", value)

The log includes the message and traceback, which is better than a vague print.

Before you move on

Can You Use Python Logging?

5 checks
  • You can choose a useful log level.
  • You can configure basic logging once near program startup.
  • You can log exceptions with tracebacks.
  • You can keep normal output separate from diagnostic output.
  • You can remove temporary prints after replacing them with logs.

Log Messages That Mislead

  • Logging everything as error

    Use info for normal progress and error only for actual failures.
  • Using vague messages

    Name the failed action and include the important value safely.
  • Configuring logging many times

    Configure logging once at program startup.

Try this next

Record Useful Events

0 of 3 completed

  1. Take a small script with print checks and replace them with logging.info or logging.debug.
  2. Catch a ValueError and record the failed input with logging.exception.
  3. Write one message each for debug, info, warning, and error in a file-processing script.

Questions About Python Logging

Use print for program output learners or users should see. Use logging for diagnostic information about the program itself.

INFO is a good starting level because it shows useful progress without showing every tiny detail.

No. Logging helps you see what happened. You still need validation, error handling, or code changes to fix the cause.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.