这个问题既简单又基本。如何将所有查询记录在mongodb中的“尾部”日志文件中?

我试过:

设置概要级别 设置启动慢ms参数 使用-vv选项Mongod

/var/log/mongodb/mongodb.log一直显示当前活动连接的数量…


当前回答

如果您希望查询被记录到mongodb日志文件,您必须同时设置这两个 日志级别和分析,例如:

db.setLogLevel(1)
db.setProfilingLevel(2)

(参见https://docs.mongodb.com/manual/reference/method/db.setLogLevel)

只设置概要不会将查询记录到文件中,因此您只能从

db.system.profile.find().pretty()

其他回答

MongoDB有一个复杂的性能分析功能。日志记录发生在系统中。配置文件收集。日志内容如下:

db.system.profile.find()

有3个日志级别(源):

Level 0 - the profiler is off, does not collect any data. mongod always writes operations longer than the slowOpThresholdMs threshold to its log. This is the default profiler level. Level 1 - collects profiling data for slow operations only. By default slow operations are those slower than 100 milliseconds. You can modify the threshold for “slow” operations with the slowOpThresholdMs runtime option or the setParameter command. See the Specify the Threshold for Slow Operations section for more information. Level 2 - collects profiling data for all database operations.

要查看数据库运行在哪个分析级别,请使用

db.getProfilingLevel()

并查看状态

db.getProfilingStatus()

要更改分析状态,使用该命令

db.setProfilingLevel(level, milliseconds)

其中level指的是分析级别,毫秒是需要记录查询持续时间的ms。若要关闭日志记录,请使用

db.setProfilingLevel(0)

在系统概要集合中查找耗时超过一秒的所有查询(按时间戳降序排序)的查询将为

db.system.profile.find( { millis : { $gt:1000 } } ).sort( { ts : -1 } )

我做了一个命令行工具来激活分析器活动,并以“尾部”的方式查看日志——>“mongotail”:

$ mongotail MYDATABASE
2020-02-24 19:17:01.194 QUERY  [Company] : {"_id": ObjectId("548b164144ae122dc430376b")}. 1 returned.
2020-02-24 19:17:01.195 QUERY  [User] : {"_id": ObjectId("549048806b5d3db78cf6f654")}. 1 returned.
2020-02-24 19:17:01.196 UPDATE [Activation] : {"_id": "AB524"}, {"_id": "AB524", "code": "f2cbad0c"}. 1 updated.
2020-02-24 19:17:10.729 COUNT  [User] : {"active": {"$exists": true}, "firstName": {"$regex": "mac"}}
...

但更有趣的功能(也像tail一样)是使用-f选项“实时”查看更改,偶尔使用grep过滤结果以查找特定操作。

参见文档和安装说明:https://github.com/mrsarm/mongotail

(也可以从Docker运行,特别是如果你想从Windows https://hub.docker.com/r/mrsarm/mongotail执行它)

db.adminCommand( { getLog: "*" } )

Then

db.adminCommand( { getLog : "global" } )

一旦使用db.setProfilingLevel(2)设置了分析级别。

下面的命令将打印最后执行的查询。 您也可以更改限制(5)以查看更少/更多的查询。 $nin -过滤概要文件和索引查询 此外,使用查询投影{'query':1}仅用于查看查询字段

db.system.profile.find(
{ 
    ns: { 
        $nin : ['meteor.system.profile','meteor.system.indexes']
    }
} 
).limit(5).sort( { ts : -1 } ).pretty()

只有查询投影的日志

db.system.profile.find(
{ 
    ns: { 
        $nin : ['meteor.system.profile','meteor.system.indexes']
    }
},
{'query':1}
).limit(5).sort( { ts : -1 } ).pretty()

将profilinglevel设置为2是记录所有查询的另一个选项。