Sikau

Project: Laptop to production · Day 1 · about 40 min

A log report script

grep, sort, uniq and cut in a strict bash script with useful exit codes.

From laptop to production

This combined project brings Linux, GitHub Actions and Docker together. You'll write a bash tool that reads the café's logs, run it every night in CI, package the API in a lean, healthy container, and ship releases with one script.

  • Day 1: a log report script (Linux)
  • Day 2: CI that tests and checks the logs nightly (GitHub Actions)
  • Day 3: a production Dockerfile (Docker)
  • Day 4: a one-command release (bash + Docker)

logreport.sh

#!/usr/bin/env bash
set -euo pipefail

log="${1:?usage: logreport.sh LOGFILE}"
if [[ ! -f "$log" ]]; then
  echo "logreport: no such file: $log" >&2
  exit 2
fi

errors=$(grep -ci ' error ' "$log" || true)
warnings=$(grep -c ' WARN ' "$log" || true)
slowest=$(grep -oE '[0-9]+ms' "$log" | sort -n | tail -n 1)

echo "errors: $errors"
echo "warnings: $warnings"
echo "slowest: $slowest"

if (( errors > 0 )); then
  top=$(grep -i ' error ' "$log" | cut -d' ' -f4- | sed 's/ order=.*//' | sort | uniq -c | sort -rn | head -n 1)
  count=$(echo $top | cut -d' ' -f1)
  message=$(echo $top | cut -d' ' -f2-)
  echo "top error: $message ($count)"
  exit 1
fi
echo "top error: none"

The rest of this lesson

  • Exit codes as an APIexplain
  • Grep counts without surprisesexplain
  • Pipeline outputpredict
  • What should it exit with?match
  • Write the reportwrite code
  • Badge quizquiz
  • What you builtrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 4 lessons of Project: Laptop to production