mongodb 日志切换(rotate log files)实战 1. 在mongo shell下,执行logrotate命令: useadmindb.runcommand({logrotate:1}) 需要在mongos,mongod,config server运行。 该方式的变种: a) 在unix shell下运行: mongolocalhost/admin–eval“dbo.runcomma
mongodb 日志切换(rotate log files)实战
1. 在mongo shell下,执行logrotate命令:
use admin db.runcommand({logrotate:1})
需要在mongos,mongod,config server运行。
该方式的变种:
a) 在unix shell下运行:
mongo localhost/admin –eval “dbo.runcommand({logrotate:1})”
b) bash脚本:
#!/bin/sh ### log rotate mongo localhost/admin –evel “db.runcommand({logrotate:1})” ### compress newly rotated for f in /var/log/mongodb/mongod.log.--t--; do 7za a “$f.z” “$f” rm –f “$f” done
c) 将如下脚本保存到logrotate.js文件:
db.getmongo().getdb(“admin”).runcommand({logrotate:1})
创建脚本logrotate.sh:
#!/bin/sh # clear old logs rm /var/log/mongodb/mongod.log.* # rotate logs mongo logrotate.js
d) logrotate.sh //写到计划任务crontab即可(需要expect软件包)
#!/usr/bin/expect –f spawn /usr/local/mongodb/bin/mongo admin -udev -ptest –quiet expect > send db.runcommand(logrotate) send \r\n expect > send exit
2. 使用sigusr1信号:
kill –sigusr1 find /var/log/mongodb/mongodb.log.* -mtime +7 –delete
该方法的变种:
a) 用python写的定时脚本,每天产生一个新的log,超过7天的log自行删除。
#!/bin/env pythonimport sysimport osimport commandsimport datetime,time#get mongo pidmongo_pid = commands.getoutput(/sbin/pidof mongod)print mongo_pid#send sig to mongoif mongo_pid != '':cmd = /bin/kill -usr1 %s %(mongo_pid)print cmdmongo_rotate = commands.getoutput(cmd)else:print mongod is not running...#clean log which > 7 daysstr_now = time.strftime(%y-%m-%d)dat_now = time.strptime(str_now,%y-%m-%d)array_dat_now = datetime.datetime(dat_now[0],dat_now[1],dat_now[2])lns = commands.getoutput(/bin/ls --full-time /var/log/mongodb/|awk '{print $6, $9}')for ln in lns.split('\n'):ws = ln.split()if len(ws) != 2:continuews1 = time.strptime(ws[0],%y-%m-%d)ws2 = datetime.datetime(ws1[0],ws1[1],ws1[2])if (array_dat_now - ws2).days > 7:v_del = commands.getoutput(/bin/rm -rf /var/log/mongodb//%s % (ws[1]))
在root下crontab –e编辑定时任务
0 2 * * * /root/mongo_log_rotate.py >/root/null 2>&1
3. 日志管理工具logrotate
自动化的最好方式是使用logrotate,其中copytruncate参数能更好工作。
拷贝以下代码到/etc/logrotate.d/mongodb文件中,确保脚本中的路径和文件名正确。
# vi /etc/logrotate.d/mongodb/var/log/mongodb/*.log {dailyrotate 7compressdateextmissingoknotifemptysharedscriptscopytruncatepostrotate/bin/kill -sigusr1 `cat /var/lib/mongo/mongod.lock 2> /dev/null` 2> /dev/null || trueendscript}# logrotate –f /etc/logrotate.d/mongodb
4. mongodb bug
mongodb稳定性差强人意。在切换过程中也会导致mongodb进程终止。
具体内容可以查看下mongodb bug系统:server-4739、server-3339。