Skip to content

Instantly share code, notes, and snippets.

@bensig
Last active September 25, 2024 07:32
Show Gist options
  • Save bensig/34ff72bdf15880a9102bc7f1307964a7 to your computer and use it in GitHub Desktop.
Save bensig/34ff72bdf15880a9102bc7f1307964a7 to your computer and use it in GitHub Desktop.
Check docker logs for matching keywords - can be used to alert ant
#!/bin/bash
# Initialize empty variables
CONTAINER=""
ERROR_KEYWORDS=""
# Parse arguments using flags
while [ "$1" != "" ]; do
case $1 in
-container ) shift
CONTAINER=$1
;;
-keywords ) shift
ERROR_KEYWORDS=$1
;;
* ) echo "Usage: $0 -container <container_name> -keywords <error_keywords>"
exit 3 # UNKNOWN status
esac
shift
done
# Print the received arguments for debugging (optional)
echo "Container: $CONTAINER"
echo "Keywords: $ERROR_KEYWORDS"
# Check if both required arguments are provided
if [ -z "$CONTAINER" ] || [ -z "$ERROR_KEYWORDS" ]; then
echo "Usage: $0 -container <container_name> -keywords <error_keywords>"
exit 3 # UNKNOWN status
fi
# Fetch the logs from the last 5 minutes
LOGS=$(docker logs --since 5m "$CONTAINER" 2>&1)
# Search the logs for the specified error keywords
ERROR_LOGS=$(echo "$LOGS" | grep -iE "$ERROR_KEYWORDS")
# If we found any errors in the logs
if [ ! -z "$ERROR_LOGS" ]; then
echo "CRITICAL: Errors found in container logs for $CONTAINER"
echo "$ERROR_LOGS"
exit 2 # CRITICAL status
else
echo "OK: No errors found in container logs for $CONTAINER"
exit 0 # OK status
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment