Skip to content
CloudOps
Newsletter Sign up
All prompts
AI for Bash & Python Automation Difficulty: Beginner ClaudeChatGPT

Bash Leveled Logging Library Prompt

Build a small, sourceable Bash logging library with DEBUG/INFO/WARN/ERROR levels, timestamps, TTY-aware color, and a LOG_LEVEL threshold — so your scripts emit consistent, greppable output to stderr.

Target user
Engineers standardizing log output across a fleet of Bash automation scripts
Difficulty
Beginner
Tools
Claude, ChatGPT

The prompt

You are a senior platform engineer who insists every Bash script in the org logs the same way: leveled, timestamped, on stderr, colorized only when a human is watching. You write a tiny logging library that scripts source.

I will provide:
- The scripts I want to standardize (or just my desired levels and format)
- Where output goes (terminal, journald via systemd, CI logs, files)
- Whether I need structured (key=value or JSON) output for log shippers

Your job:

1. **Level functions** — `log_debug`, `log_info`, `log_warn`, `log_error` (and optional `log_fatal` that exits non-zero). All write to **stderr** so stdout stays clean for data/piping. Explain why stderr is the right channel.

2. **Threshold** — honor a `LOG_LEVEL` env var (default INFO). Messages below the threshold are suppressed. Show the numeric-rank comparison.

3. **Format** — `2026-06-11T14:03:22Z [INFO] message`. Use UTC ISO-8601. Include the script basename and optionally PID. Make the format a single function so it's easy to change once.

4. **Color, but smart** — colorize the level only when stderr is a TTY (`[[ -t 2 ]]`) and `NO_COLOR` is unset. Never emit escape codes into files or journald. WARN=yellow, ERROR=red, DEBUG=dim.

5. **systemd/journald mode** — offer an alternate format that emits `<3>`/`<4>`/`<6>` sd-daemon priority prefixes so `journalctl -p` filtering works, toggled by an env var.

6. **Structured option** — show a `LOG_FORMAT=json` variant emitting one JSON object per line (ts, level, msg, plus arbitrary `key=val` extras), safely escaping the message.

7. **Strict-mode safe** — works under `set -euo pipefail`; logging must never abort the script.

Output: (a) a self-contained `log.sh` to source, (b) a usage example showing level filtering and a piped command keeping stdout clean, (c) the journald and JSON variants, (d) a one-line note on testing log output in bats.

Bias toward: stderr by default, minimal dependencies (no external tools), and color that disappears the moment output is redirected.
Newsletter

Free: the DevOps AI Incident-Triage Cheat Sheet

Subscribe and we’ll send you the one-page cheat sheet — plus weekly AI prompts, automation ideas, and tool reviews for infrastructure engineers. One email a week. No spam, unsubscribe anytime.

  • AI Incident-Triage Cheat Sheet (PDF)
  • Access to 1,300+ DevOps AI prompts
  • One practical workflow email per week