Simple Script to Monitor Nginx HTTP Codes

Nginx[1] is a popular reverse proxy and a load balancer tool used in the web industry. There are multiple UI based tools to monitor the performance of the Nginx server and the health of the underline servers to which nginx is serving traffic. Following is a simple shell script that I wrote for monitoring the status of nginx upstreams by looking at the nginx access logs.


#!/bin/bash
tail_Command="tail "
array=()
while IFS= read -r -d $'\0'; do
array+=("$REPLY")
done < <(find /path/to/nginx/access/log/root -type f -name "*access.log" -print0)
for i in "${array[@]}"
do
echo "===============================================================================================\n"
echo "LOG FILE: $i"
echo "===============================================================================================\n"
cat "$i" | cut -d '"' -f3 | cut -d ' ' -f2 | sort | uniq -c | sort -rn
echo "-----------------------------------------------------------------------------------------------\n"
tail_Command+=" -f $i"
done
#echo "$tail_Command"
tail_Command+=' | grep --color -e "HTTP/1\.1\" 5.." -e "HTTP/1\.1\" 4.."'
eval "$tail_Command"

You have to execute this inside the nginx log root directory and it will first find all the access log files, print the count of different http status codes found in each log and multi-tail all the logs for 4XX and 5XX errors.

Cheers..!

[1] https://www.nginx.com/resources/glossary/nginx/