Realtime Monitor Kinsta Access Logs

Create ~/private/realtime-access-logs.sh with the following. Then chmod +x ~/private/realtime-access-logs.sh to grant execute permissions and ~/private/realtime-access-logs.sh to run. This will continiously monitor Kinsta’s access logs and show realtime activity for the top IPs. To exit press Command + C.

#!/bin/bash

if ! which gum &> /dev/null
then
    cd ~/private
    if [ -f "gum_0.14.4_Linux_x86_64/gum" ]
    then
        gum() {
          ~/private/gum_0.14.4_Linux_x86_64/gum "$@"
        }
    fi
    if ! gum --version &> /dev/null
    then
       wget --quiet https://github.com/charmbracelet/gum/releases/download/v0.14.4/gum_0.14.4_Linux_x86_64.tar.gz
       tar -xf gum_0.14.4_Linux_x86_64.tar.gz
       gum() {
          ~/private/gum_0.14.4_Linux_x86_64/gum "$@"
       }
   fi
   cd ~/public
fi

limit=$1
if [[ "$limit" == "" ]]; then
	limit=25
fi
log=~/logs/access.log
log_count=$( cat $log | wc -l )
offset=$(($log_count - 100))

while true; do
  overview="PHP Workers,Log,From,To\n"
  output="Hits,Pages,IP Address,User Agent\n"
  top_ips=$( sed -n "$offset,\$p" "$log" | awk '{print $2}' | sort | uniq -c | sort -nr | head -n $limit | awk '{print $2}' )
  for ip in ${top_ips}; do
        ip_hit_count=$( sed -n "$offset,\$p" "$log" | grep "$ip" | wc -l | sed 's/^[ \t]*//;s/[ \t]*$//' )
        ip_page_count=$( sed -n "$offset,\$p" "$log" | grep "$ip" | awk '{print $6}' | sort | uniq -c | sort -nr | wc -l | sed 's/^[ \t]*//;s/[ \t]*$//' )
        ip_user_agent=$( sed -n "$offset,\$p" "$log" | grep "$ip" | tail -1 | awk -F\" '{print $6}' | cut -c 1-125 )
        ip_user_agent=${ip_user_agent//,/}
        output+="$ip_hit_count,$ip_page_count,$ip,$ip_user_agent\n"
  done
  php_workers=$( ps -e --format "pid uname comm %cpu %mem time" --sort "time" --no-headers | grep php-fpm.* | grep -v "grep" | grep -v "root" | wc -l )
  first_line=$( sed -n "$offset,\$p" "$log" | head -n 1 | awk -F'[][]' '{print $2}')
  last_line=$( sed -n "$offset,\$p" "$log" | tail -n 1 | awk -F'[][]' '{print $2}')
  overview+="$php_workers,$log,$first_line,$last_line\n"
  clear
  echo -e "$overview" | gum table --print
  echo -e "$output" | gum table --print
  sleep 2
done