Skip to content
This repository was archived by the owner on Aug 3, 2026. It is now read-only.

Commit d35ec24

Browse files
committed
chore: refine script
1 parent 2df7345 commit d35ec24

1 file changed

Lines changed: 6 additions & 1 deletion

File tree

script/log_alert.sh

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ set -euo pipefail
44
MODE="${1:-tg}" # tg | slack
55
LOG_FILE="${2:-/var/log/app.log}" # log file path
66
PATTERN="${3:-ERROR|FATAL|EXCEPTION}"
7+
MAX_ALERTS="${4:-100}" # stop sending after this many alerts
8+
[[ "$MAX_ALERTS" =~ ^[0-9]+$ ]] || { echo "max_alerts must be a non-negative integer"; exit 1; }
79

810
HOST="$(hostname)"
911
now() { date -u +"%Y-%m-%dT%H:%M:%SZ"; }
@@ -29,13 +31,15 @@ send_slack() {
2931

3032
case "$MODE" in
3133
tg|slack) ;;
32-
*) echo "Usage: $0 <tg|slack> [log_file] [pattern]"; exit 1 ;;
34+
*) echo "Usage: $0 <tg|slack> [log_file] [pattern] [max_alerts]"; exit 1 ;;
3335
esac
3436

3537
# -n0 = only new lines from now on. Change to -n +1 to replay existing lines.
38+
count=0
3639
tail -n0 -F "$LOG_FILE" \
3740
| grep --line-buffered -E -i "$PATTERN" \
3841
| while IFS= read -r line; do
42+
if ((count >= MAX_ALERTS)); then printf '[stopped] max_alerts=%s reached\n' "$MAX_ALERTS"; exit 0; fi
3943
msg="[$(now)] [$HOST] $line"
4044
if [[ "$MODE" == "tg" ]]; then
4145
send_tg "$msg"
@@ -44,4 +48,5 @@ tail -n0 -F "$LOG_FILE" \
4448
send_slack "$msg"
4549
printf '[sent][slack] %s\n' "$msg"
4650
fi
51+
count=$((count + 1))
4752
done

0 commit comments

Comments
 (0)