MongoDB 日志切换(Rotate Log Files)实战
1. 在mongo shell下,执行logRotate命令:
|
1
2
|
use admin
db.runCommand({logRotate:1})
|
需要在mongos,mongod,config server运行。
该方式的变种:
a) 在unix shell下运行:
|
1
|
mongo localhost
/admin
–
eval
“dbo.runCommand({logRotate:1})”
|
|
1
2
3
4
5
6
7
8
9
|
#!/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文件:
|
1
|
db.getMongo().getDB(“admin”).runCommand({logRotate:1})
|
创建脚本logRotate.sh:
|
1
2
3
4
5
|
#!/bin/sh
# Clear old logs
rm
/var/log/mongodb/mongod
.log.*
# Rotate logs
mongo logRotate.js
|
d) logRotate.sh //写到计划任务crontab即可(需要expect软件包)
|
1
2
3
4
5
6
7
|
#!/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信号:
|
1
2
|
kill
–SIGUSR1 <mongod process
id
>
find
/var/log/mongodb/mongodb
.log.* -mtime +7 –delete
|
该方法的变种:
a) 用python写的定时脚本,每天产生一个新的log,超过7天的log自行删除。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
#!/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编辑定时任务
|
1
|
0 2 * * *
/root/mongo_log_rotate
.py >
/root/null
2>&1
|
3. 日志管理工具logrotate
自动化的最好方式是使用logrotate,其中copytruncate参数能更好工作。
拷贝以下代码到/etc/logrotate.d/mongodb文件中,确保脚本中的路径和文件名正确。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
# 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稳定性差强人意。在切换过程中也会导致mongodb进程终止。
具体内容可以查看下mongodb bug系统:SERVER-4739、SERVER-3339。
本文转自UltraSQL51CTO博客,原文链接: http://blog.51cto.com/ultrasql/1620675,如需转载请自行联系原作者