remove GNU-specific `sort -V`, fix log concatenation order for {,e}searchlog
[logtools.git] / countconn
1 #!/bin/sh
2
3 trap "exit 1" USR1
4
5 USAGE="usage: ${0} [-dm] [-l #]"
6
7 usage() {
8 printf "%s\n" "$USAGE" >&2; exit 2
9 }
10
11 err() {
12 printf "error: server not detected, needs to be set manually\n" >&2
13 printf "set \$SERVER or modify the script itself\n" >&2
14 kill -USR1 "$$"
15 }
16
17 CUTCMD="-d: -f2,3"
18 TAILN=30
19
20 while getopts "dl:m" flag; do
21 case "$flag" in
22 d) CUTCMD="-d/ -f1,2" ;;
23 m) CUTCMD="-d: -f2,3" ;;
24 l)
25 if [ "$OPTARG" -eq "$OPTARG" ]; then
26 TAILN="$OPTARG"
27 else
28 usage
29 fi ;;
30 *) usage ;;
31 esac
32 done
33
34 # ... && ... || is not an if-then-else, but this works because
35 # there's no way for only one printf to fail
36 [ -z "$SERVER" ] && SERVER=$(which > /dev/null 2>&1 apache2 && printf "apache2" || which > /dev/null 2>&1 nginx && printf "nginx" || err)
37
38 CURDAY=$(tail -n1 /var/log/"$SERVER"/access.log | grep -oE "[0-9]{2}/.*/[0-9]{4}:")
39
40 { cat /var/log/"$SERVER"/access.log /var/log/"$SERVER"/access.log.1; gzip -cd $(ls /var/log/"$SERVER"/access.log.*.gz | sed 's/.*\.\([0-9]*\)\.gz/\1 &/' | sort -n | cut -d' ' -f2-); } | awk -v curday="$CURDAY" '$0 ~ curday { if (match($0, /[0-9]{2}\/.*\/[0-9]{4}:[0-9]{2}:[0-9]{2}:[0-9]{2}/)) { print substr($0, RSTART, RLENGTH) } next } { exit }' | cut $CUTCMD | uniq -c | tail -n"$TAILN"