daily_log_router.sh 1.12 KB
#!/bin/bash
#
# Route incoming log stream into per-day files.
#
# Usage:
#   command 2>&1 | ./scripts/daily_log_router.sh <service> <log_dir> [retention_days]
#

set -euo pipefail

if [ "$#" -lt 2 ]; then
  echo "Usage: $0 <service> <log_dir> [retention_days]" >&2
  exit 1
fi

SERVICE_NAME="$1"
LOG_DIR="$2"
RETENTION_DAYS="${3:-30}"

mkdir -p "${LOG_DIR}"

awk -v dir="${LOG_DIR}" -v service="${SERVICE_NAME}" -v retention_days="${RETENTION_DAYS}" '
function rotate_file(day) {
  return sprintf("%s/%s-%s.log", dir, service, day)
}

function update_symlink(day) {
  cmd = sprintf("ln -sfn \"%s-%s.log\" \"%s/%s.log\"", service, day, dir, service)
  system(cmd)
}

function cleanup_old_logs() {
  cmd = sprintf("find \"%s\" -maxdepth 1 -type f -name \"%s-*.log\" -mtime +%d -delete >/dev/null 2>&1", dir, service, retention_days)
  system(cmd)
}

{
  day = strftime("%Y-%m-%d")
  target = rotate_file(day)

  if (target != current_target) {
    update_symlink(day)
    cleanup_old_logs()
    current_target = target
  }

  print >> current_target
  fflush(current_target)
}

END {
  if (current_target != "") {
    close(current_target)
  }
}
'