1.查看buffer/cache
free -m
2.查找工具
查找buff/cache占用过大的程序
下载hcache(https://github.com/silenceshell/hcache)
chmod 755 hcache
./hcache --top 10
3. 修改rsyslog配置
vim /usr/lib/systemd/system/rsyslog.service
MemoryAccounting=yes
MemoryMax=80M
MemoryHigh=8M
重启
systemctl daemon-reload
systemctl restart rsyslog
4.提高rsyslog日志级别
将*.info改为*.err
vi /etc/rsyslog.conf
重启
systemctl daemon-reload
systemctl restart rsyslog
5.修改Journal配置
vim /etc/systemd/journald.conf
Storage=persistent
SystemMaxUse=1G
SystemMaxFileSize=10M
MaxRetentionSec=1month
ForwardToSyslog=no
ForwardToWall=no
Storage含义:
volatile 代表日志只存在内存中,即/run/log/journal/
persistent 代表日志只存在磁盘中,即/var/log/journal/
auto 代表日志存在磁盘中,或者内存中,取决于你是否创建/var/log/journal/目录,部分系统是需要手动mkdir -p /var/log/journal/,systemctl restart systemd-journald来解放内存。
none 日志不保留,全部drop,当你决定不使用systemd-journald的时候,你可以使用。
重启
systemctl restart systemd-journald
5.定时清理
定时清理脚本,在linux上vi并写入cleanLinuxCache.sh,给可执行权限
# min free memory set
memory_free_min=${1:-"300"}
# memeory useage
memory_used=`free -m | awk 'NR==2' | awk '{print $3}'`
memory_free=`free -m | awk 'NR==2' | awk '{print $4}'`
# storage log
year_month=$(date +"%Y-%m")
current_path=$(cd $(dirname $0); pwd)
script_name=$(basename "${0}" ".sh")
log_path="${current_path}/logs/${script_name}-${year_month}.log"
current_time=$(date +"%Y-%m-%d %H:%M:%S")
echo "${current_time} 开始执行脚本,设置的最小空闲内存为${memory_free_min}MB" >> $log_path
echo "${current_time} 清理缓存前已使用内存:${memory_used}MB,空闲内存:${memory_free}MB" >> $log_path
# clean when memory_free less than memory_free_min
if [ $memory_free -le $memory_free_min ]
then
echo "${current_time} 空闲内存不足${memory_free_min}MB,开始清理buffer/cache" >> $log_path
sync && echo 1 > /proc/sys/vm/drop_caches
sync && echo 2 > /proc/sys/vm/drop_caches
sync && echo 3 > /proc/sys/vm/drop_caches
USED_CLEAN=`free -m | awk 'NR==2' | awk '{print $3}'`
FREE_CLEAN=`free -m | awk 'NR==2' | awk '{print $4}'`
echo "${current_time} 清理buffer/cache后,空闲内存:${FREE_CLEAN}MB" >> $log_path
else
echo "${current_time} 空闲内存大于${memory_free_min}MB,不需要清理buffer/cache" >> $log_path
fi
设置定时任务
crontab -e
*/10 * * * * /root/script/cleanLinuxCache.sh
执行日志
[root@VM_0_12_centos logs]# cat cleanLinuxCache-2024-03.log
2024-03-20 11:39:44 开始执行脚本,设置的最小空闲内存为300MB
2024-03-20 11:39:44 清理缓存前已使用内存:448MB,空闲内存:442MB
2024-03-20 11:39:44 空闲内存大于300MB,不需要清理buffer/cache