tomcat-watchdog模板:
#!/bin/bash
2 #以下为多行注释
3 : << !
4 作用:tomcat watch dog,用于在tomcat进程退出后,自动拉起tomcat
5 函数说明:
6 log_info:打印日志的函数,入参为需要在日志中打印的msg
7 start_tom:启动tomcat的函数
8 check_tom_run:每隔10s检测tomcat进程是否存在
9 log_backup:备份tomcat监控日志
10 !
11
12 curr_path=`pwd`
13 #tomcat的安装路径
14 tom_path=/home/stephen/InstallPath/apache-tomcat-8.5.39
15
16
17 #定义打印日志的函数
18 function log_info(){
19 local curr_time=`date "+%Y-%m-%d %H:%M:%S"`
20 log_file=${curr_path}/tom_running.log
21 #判断日志文件是否存在
22 if [ -e ${log_file} ]
23 then
24 #检测文件是否可写
25 if [ -w ${log_file} ]
26 then
27 #若文件无写权限则使用chmod命令赋予权限
28 chmod 770 ${log_file}
29 fi
30 else
31 #若日志文件不存在则创建
32 touch ${log_file}
33 fi
34 #写日志
35 local info=$1
36 echo "${curr_time} `whoami` [Info] ${info}">>${log_file}
37 }
38
39 function start_tom(){
40 log_info "Begin to start tomcat."
41 cd ${tom_path}/bin
42 log_info "cd ${tom_path}/bin"
43 sh startup.sh
44 log_info "sh startup.sh"
45 #使用ps命令+awk获取tomcat的PID
46 tom_pid=`ps -aux|grep apache-tomcat|grep -v grep|awk '{print $2}'`
47 if [ -z ${tom_pid} ]
48 then
49 sh startup.sh
50 fi
51 log_info "End to start tomcat."
52 }
53
54 #如果tomcat_pid为零,则说明tomcat进程不存在,需要去重启
55 function check_tom_run()
56 {
57 tom_pid=`ps -aux|grep apache-tomcat|grep -v grep|awk '{print $2}'`
58 echo ${tom_pid}
59 if [ -z ${tom_pid} ]
60 then
61 echo "tomcat process is not running."
62 #调用函数start_tom
63 start_tom
64 log_info "tomcat process is not running."
65 #打印日志
66 else
67 echo "tomcat process is running"
68 #打印日志
69 log_info "tomcat process is running"
70 fi
71 }
72 #备份日志
73 function log_backup(){
74 cd ${curr_path}
75 log_name=tom_running.log
76 #获取当前日志的大小
77 log_size=`ls -all|grep -v ${log_name}.|grep ${log_name}|awk '{print $5}'`
78 echo ${log_size}
79 #当日志大于150MB时进行备份并清空旧的日志
80 expect_size=`expr 150 \* 1024 \* 1024`
81 echo ${expect_size}
82 if [ ${log_size} -gt ${expect_size} ]
83 then
84 log_info "Begin to backup log."
85 local ct=`date "+%Y-%m-%d-%H-%M-%S"`
86 cp ${log_name} ${log_name}.${ct}
87 log_info "cp ${log_name} ${log_name}.${ct}"
88 #使用gzip命令压缩日志
89 gzip -q ${log_name}.${ct} ${log_name}.${ct}.gz
90 #清空旧日志
91 cat /dev/null > ${log_name}
92 log_info "cat /dev/null > ${log_name}"
93 fi
94 }
95
96 #隔30s循环执行check_tom_1run
97 while [ 1 ]
98 do
99 check_tom_run
100 log_backup
101 #休眠30s
102 sleep 30
103 done