Logging Function in Shell

Level 5207 keystrokes

A small log function writes each message with a timestamp and a level to stderr using printf, so logs stay separate from the script's normal output. The timestamps vary.

Shell code

# log LEVEL MESSAGE
1log() {
# Copy the two arguments into function-local variables
2 local level="$1" msg="$2"
# Current time as YYYY-MM-DD HH:MM:SS
3 local ts=$(date '+%Y-%m-%d %H:%M:%S')
# printf fills each %s in order; >&2 sends the line to stderr
4 printf '[%s] [%s] %s\n' "$ts" "$level" "$msg" >&2
5}
# Log three messages with different levels
6log INFO "Application starting"
7log WARN "Low memory"
8log ERROR "Connection failed"

Output

[2024-01-15 10:30:45] [INFO] Application starting
[2024-01-15 10:30:45] [WARN] Low memory
[2024-01-15 10:30:45] [ERROR] Connection failed
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • "× 16
  • %× 9
  • $× 6
  • '× 4
  • =× 3
  • -× 2
  • :× 2
  • (× 2
  • )× 2
  • [× 2

More Shell examples at level 5

← Shell typing practice