104 — Logging and Exit Codes

Intermediate

Replace bare print() calls with Python's stdlib logging module to emit structured, level-based output, then use sys.exit() with meaningful non-zero codes so CI/CD pipelines can detect failures automatically.

Learning Objectives

1
Set up a logger with logging.basicConfig() and logging.getLogger()
2
Replace diagnostic print() calls with the correct log level: DEBUG, INFO, WARNING, or ERROR
3
Connect the --verbose flag to DEBUG-level log output
4
Add a logger.warning() for conditions that need attention but are not failures
5
Use sys.exit(1) after logger.error() so the process signals failure to the calling shell or pipeline
6
Test exit codes with shell operators to simulate CI/CD failure detection
7
Override the log level at runtime using the LOG_LEVEL environment variable
Step 1

Set up the lesson 104 workspace

Create a directory for this lesson, copy `deploy_check.py` from Lesson 103, and confirm the virtual environment is active. Lesson 104 evolves the script by replacing print() with logging and adding explicit sys.exit() calls.

Commands to Run

mkdir -p ~/devops-python/lesson-104
cd ~/devops-python/lesson-104
cp ~/devops-python/lesson-103/deploy_check.py .
source ~/devops-python/lesson-101/devops-env/bin/activate
cat deploy_check.py

What This Does

You are starting from the Lesson 103 version of deploy_check.py, which uses argparse for argument parsing.

By the end of this lesson the script will use the logging module for all diagnostic output and exit with a non-zero code when it encounters an application-level error.

The logging module is part of the Python standard library — no pip install required.

Expected Outcome

Your terminal prompt shows (devops-env). cat deploy_check.py shows the Lesson 103 script: shebang, argparse setup with environment, --format, and --verbose arguments, and print() calls for output.

Pro Tips

  • 1
    If you did not complete Lesson 103, copy its final script from the lesson or create `deploy_check.py` with the argparse setup — the exact starting content matters for the later steps.
  • 2
    The `source` path assumes the venv is at `~/devops-python/lesson-101/devops-env/`. Adjust if you placed it elsewhere.
Was this step helpful?

All Steps (0 / 8 completed)