MongoDB 日志切換(Rotate Log Files)實(shí)戰(zhàn)
金林網(wǎng)站建設(shè)公司成都創(chuàng)新互聯(lián),金林網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為金林超過千家提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\外貿(mào)網(wǎng)站制作要多少錢,請(qǐng)找那個(gè)售后服務(wù)好的金林做網(wǎng)站的公司定做!
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})”
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})
創(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信號(hào):
kill –SIGUSR1find /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。