Blame view

scripts/daily_log_router.sh 1.12 KB
28e57bb1   tangwang   日志体系优化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
  #!/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)
    }
  }
  '