您好,登錄后才能下訂單哦!
MongoDB 日志切換(Rotate Log Files)實(shí)戰(zhàn)
1. 在mongo shell下,執(zhí)行l(wèi)ogRotate命令:
use admin db.runCommand({logRotate:1})
需要在mongos,mongod,config server運(yùn)行。
該方式的變種:
a) 在unix shell下運(yùn)行:
mongo localhost/admin –eval “dbo.runCommand({logRotate:1})”
#!/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})
創(chuàng)建腳本logRotate.sh:
#!/bin/sh # Clear old logs rm /var/log/mongodb/mongod.log.* # Rotate logs mongo logRotate.js
d) logRotate.sh //寫到計(jì)劃任務(wù)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 <mongod process id> find /var/log/mongodb/mongodb.log.* -mtime +7 –delete
該方法的變種:
a) 用python寫的定時(shí)腳本,每天產(chǎn)生一個(gè)新的log,超過7天的log自行刪除。
#!/bin/env python import sys import os import commands import datetime,time #get mongo pid mongo_pid = commands.getoutput("/sbin/pidof mongod") print mongo_pid #send Sig to mongo if mongo_pid != '': cmd = "/bin/kill -USR1 %s" %(mongo_pid) print cmd mongo_rotate = commands.getoutput(cmd) else: print "mongod is not running..." #clean log which > 7 days str_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: continue ws1 = 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編輯定時(shí)任務(wù)
0 2 * * * /root/mongo_log_rotate.py >/root/null 2>&1
3. 日志管理工具logrotate
自動(dòng)化的最好方式是使用logrotate,其中copytruncate參數(shù)能更好工作。
拷貝以下代碼到/etc/logrotate.d/mongodb文件中,確保腳本中的路徑和文件名正確。
# vi /etc/logrotate.d/mongodb /var/log/mongodb/*.log { daily rotate 7 compress dateext missingok notifempty sharedscripts copytruncate postrotate /bin/kill -SIGUSR1 `cat /var/lib/mongo/mongod.lock 2> /dev/null` 2> /dev/null || true endscript } # logrotate –f /etc/logrotate.d/mongodb
4. Mongodb bug
mongodb穩(wěn)定性差強(qiáng)人意。在切換過程中也會(huì)導(dǎo)致mongodb進(jìn)程終止。
具體內(nèi)容可以查看下mongodb bug系統(tǒng):SERVER-4739、SERVER-3339。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。