Home Database Mysql Tutorial MongoDB日志切换(RotateLogFiles)实战

MongoDB日志切换(RotateLogFiles)实战

Jun 07, 2016 pm 02:55 PM
mongodb switch log

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})
Copy after login


需要在mongos,mongod,config server运行。


该方式的变种:

a) 在unix shell下运行:

mongo localhost/admin –eval “dbo.runCommand({logRotate:1})”
Copy after login


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
Copy after login

c) 将如下脚本保存到logRotate.js文件:

db.getMongo().getDB(“admin”).runCommand({logRotate:1})
Copy after login


创建脚本logRotate.sh:

#!/bin/sh    
# Clear old logs    
rm /var/log/mongodb/mongod.log.*    
# Rotate logs    
mongo logRotate.js
Copy after login

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"
Copy after login

2. 使用SIGUSR1信号:

kill –SIGUSR1 <mongod process id>    
find /var/log/mongodb/mongodb.log.* -mtime +7 –delete
Copy after login


该方法的变种:

a) 用python写的定时脚本,每天产生一个新的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]))
Copy after login

在root下crontab –e编辑定时任务

0 2 * * * /root/mongo_log_rotate.py >/root/null 2>&1
Copy after login

3. 日志管理工具logrotate

自动化的最好方式是使用logrotate,其中copytruncate参数能更好工作。

拷贝以下代码到/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
Copy after login

 

4. Mongodb bug    
mongodb稳定性差强人意。在切换过程中也会导致mongodb进程终止。    
具体内容可以查看下mongodb bug系统:SERVER-4739、SERVER-3339。


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Which version is generally used for mongodb? Which version is generally used for mongodb? Apr 07, 2024 pm 05:48 PM

It is recommended to use the latest version of MongoDB (currently 5.0) as it provides the latest features and improvements. When selecting a version, you need to consider functional requirements, compatibility, stability, and community support. For example, the latest version has features such as transactions and aggregation pipeline optimization. Make sure the version is compatible with the application. For production environments, choose the long-term support version. The latest version has more active community support.

The difference between nodejs and vuejs The difference between nodejs and vuejs Apr 21, 2024 am 04:17 AM

Node.js is a server-side JavaScript runtime, while Vue.js is a client-side JavaScript framework for creating interactive user interfaces. Node.js is used for server-side development, such as back-end service API development and data processing, while Vue.js is used for client-side development, such as single-page applications and responsive user interfaces.

Operation tutorial for switching from win11 home version to professional version_Operation tutorial for switching from win11 home version to professional version Operation tutorial for switching from win11 home version to professional version_Operation tutorial for switching from win11 home version to professional version Mar 20, 2024 pm 01:58 PM

How to convert Win11 Home Edition to Win11 Professional Edition? In Win11 system, it is divided into Home Edition, Professional Edition, Enterprise Edition, etc., and most Win11 notebooks are pre-installed with Win11 Home Edition system. Today, the editor will show you the steps to switch from win11 home version to professional version! 1. First, right-click on this computer on the win11 desktop and properties. 2. Click Change Product Key or Upgrade Windows. 3. Then click Change Product Key after entering. 4. Enter the activation key: 8G7XN-V7YWC-W8RPC-V73KB-YWRDB and select Next. 5. Then it will prompt success, so you can upgrade win11 home version to win11 professional version.

Where is the database created by mongodb? Where is the database created by mongodb? Apr 07, 2024 pm 05:39 PM

The data of the MongoDB database is stored in the specified data directory, which can be located in the local file system, network file system or cloud storage. The specific location is as follows: Local file system: The default path is Linux/macOS:/data/db, Windows: C:\data\db. Network file system: The path depends on the file system. Cloud Storage: The path is determined by the cloud storage provider.

What are the advantages of mongodb database What are the advantages of mongodb database Apr 07, 2024 pm 05:21 PM

The MongoDB database is known for its flexibility, scalability, and high performance. Its advantages include: a document data model that allows data to be stored in a flexible and unstructured way. Horizontal scalability to multiple servers via sharding. Query flexibility, supporting complex queries and aggregation operations. Data replication and fault tolerance ensure data redundancy and high availability. JSON support for easy integration with front-end applications. High performance for fast response even when processing large amounts of data. Open source, customizable and free to use.

How to use shortcut keys for switching workbooks in excel How to use shortcut keys for switching workbooks in excel Mar 20, 2024 pm 01:50 PM

In the application of excel software, we are accustomed to using shortcut keys to make some operations easier and faster. Sometimes there is related data between multiple tables in excel. When we view it, we have to constantly switch between tasks. If there is a faster switching method, it will save a lot of wasted time on switching, which will greatly help improve work efficiency. What method can be used to complete quick switching? To address this issue, the editor will talk about it today The content is: How to use the shortcut keys for switching workbooks in Excel. 1. First, you can see multiple workbooks at the bottom of the open excel table. You need to quickly switch between different workbooks, as shown in the figure below. 2. Then press the Ctrl key on the keyboard without moving, and select the job to the right if you need to

What does mongodb mean? What does mongodb mean? Apr 07, 2024 pm 05:57 PM

MongoDB is a document-oriented, distributed database system used to store and manage large amounts of structured and unstructured data. Its core concepts include document storage and distribution, and its main features include dynamic schema, indexing, aggregation, map-reduce and replication. It is widely used in content management systems, e-commerce platforms, social media websites, IoT applications, and mobile application development.

Understanding full-width and half-width: a look at switching techniques Understanding full-width and half-width: a look at switching techniques Mar 25, 2024 pm 01:36 PM

In daily life, we often encounter the problem of full-width and half-width, but few people may have a deep understanding of their meaning and difference. Full-width and half-width are actually concepts of character encoding methods, and they have special applications in computer input, editing, typesetting, etc. This article will delve into the differences between full-width and half-width, switching techniques, and real-life applications. First of all, the definitions of full-width and half-width in the field of Chinese characters are: a full-width character occupies one character position, and a half-width character occupies half a character position. In a computer, pass

See all articles