如何监视php日志并自动恢复服务?

Bash

1 前言

最近经常遇到PHP报内存”Out of memory”错误并阿里云服务器无响应(甚至SSH服务也无法使用),详细日志如下,

2020/06/07 20:56:56 [error] 1001#1001: *34883 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Out of memory (allocated 23068672) (tried to allocate 20480 bytes) in /var/www/www.cmdschool.org/wp-includes/wp-db.php on line 1989" while reading upstream, client: 66.249.68.30, server: www.cmdschool.org, request: "GET /archives/10058 HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "www.cmdschool.org"

注:以上未找到根本原因并解决之前,笔者希望先通过自动恢复服务以免影响扩大,于是此脚本应运而生。

2 最佳实践

2.1 创建脚本

vim ~/scripts/autoManager.sh

加入如下内容,

#!/bin/bash

logFile="/var/log/php-fpm/autoManager.log"
nginxLog="/var/log/nginx/error.log"
errorMsg="PHP Fatal error:  Out of memory"

nowTime=`date +"%Y/%m/%d %H:%M:%S"`
key=`echo "$nowTime" | cut -b 1-15`
errorSum=`grep "$key" $nginxLog | grep "$errorMsg" | wc -l`
if [ "$errorSum" != "0" ]; then
  logSum=`grep "$key" $logFile | wc -l`
  if [ "$logSum" = "0" ]; then
    echo "$nowTime Error found, restarting php-fpm" |tee -a $logFile
    systemctl restart php-fpm
    echo "$nowTime Php-fpm has been restarted" | tee -a $logFile
  fi
fi

注:
– 以上脚本以十分钟为单位搜索是否有特定的日志,如果有则重启特定的服务并输出日志
– 如果发现十分钟内已经重启过,则跳过重启的执行脚本

2.2 配置计划任务

crontab -e

加入如下内容,

*/1 * * * * sh ~/scripts/autoManager.sh
没有评论

发表回复

Bash
如何用Tigase监控Elasticsearch集群?

1 前言 一个问题,一篇文章,一出故事。 笔者生产中有一套Elasticsearch集群,笔者为了能 …

Bash
如何用Base Shell获取ES集群状态?

1 前言 一个问题,一篇文章,一出故事。 笔者想要通过Base Shell获取Elasticsear …

Bash
如何熟悉grep命令?

截取括弧“()”中的字符串, echo “This is a test (sample string …