#!/bin/bash
# 定义日志文件路径
log_file="/path/to/memory_monitor.log"
# 获取当前时间
current_time=$(date +'%Y-%m-%d %H:%M:%S')
# 将当前时间写入日志文件
echo "[$current_time] Memory Monitoring Report" >> "$log_file"
echo "+------+------------------------------------------+-----------------+-----------------+" >> "$log_file"
echo "| PID | JAR名称 | 内存使用(MB) | Xmx参数(MB) |" >> "$log_file"
echo "+------+------------------------------------------+-----------------+-----------------+" >> "$log_file"
# 获取所有Java进程的PID
java_pids=$(ps aux | grep java | grep -v grep | awk '{print $2}')
# 遍历每个进程,获取其Jar包名称、内存使用情况和Xmx参数
for pid in $java_pids; do
# 获取进程的命令行,包含Jar包路径
cmdline=$(cat /proc/$pid/cmdline 2>/dev/null | tr '\0' ' ')
# 从命令行中提取Jar包名称
jar_name=$(echo "$cmdline" | grep -oP '[^ ]*\.jar' | awk -F '/' '{print $NF}')
# 如果没有找到Jar包名称,则跳过
if [ -z "$jar_name" ]; then
continue
fi
# 获取进程使用的内存大小(单位:KB),并转换为MB
mem_usage=$(pmap -x $pid 2>/dev/null | tail -n 1 | awk '{print $4/1024}')
# 获取进程的-Xmx参数
xmx_param=$(echo "$cmdline" | grep -oP '(\-Xmx[0-9]+[mMgGkK])' | awk '{print substr($1, 5)}')
# 如果没有找到-Xmx参数,则默认为空
if [ -z "$xmx_param" ]; then
xmx_param="N/A"
fi
# 输出PID、Jar包名称、内存使用情况和Xmx参数(右对齐),并写入日志文件
printf "| %-5s | %-40s | %-15.2f | %-15s |\n" "$pid" "$jar_name" "$mem_usage" "$xmx_param" >> "$log_file"
done
# 输出表格底部和结束,并写入日志文件
echo "+------+------------------------------------------+-----------------+-----------------+" >> "$log_file"
echo "" >> "$log_file"
# 打印日志文件路径
echo "Memory monitoring report has been appended to: $log_file"
再通过crontab设置定时任务定时执行该脚本
root@localhost:~# cat memory_monitor.log
[2024-08-06 14:42:22] Memory Monitoring Report
+------+------------------------------------------+-----------------+-----------------+
| PID | JAR名称 | 内存使用(MB) | Xmx参数(MB) |
+------+------------------------------------------+-----------------+-----------------+
| 36151 | testa-0.0.1-SNAPSHOT.jar | 457.35 | 600m |
| 36153 | testtesDsta-0.0.1-SNAPSHOT.jar | 497.46 | 700m |
| 36155 | helloaa-0.0.1-SNAPSHOT.jar | 328.83 | 300m |
+------+------------------------------------------+-----------------+-----------------+