我想通过运行 .py 脚本来设置 mongodb.conf 文件中各个组件的日志级别。我通常只对数据库使用基本命令,如 update_one 或 insert ,没有任何问题。我收到的错误:
“TypeError:“Collection”对象不可调用。如果您打算在“Database”对象上调用“setloglevel”方法,则会失败,因为不存在此类方法。
我尝试过setLogLevel; set_log_level 和其他一些。无法对 pymongo 文档或在线中的任何内容进行罚款。
如何设置日志级别?可以吗?提前致谢。
代码:
def setlvl():
## Connection to the Mongo Service ##
try:
conn=pymongo.MongoClient("myip_address")
print("Connected successfully!!!")
except pymongo.errors.ConnectionFailure:
print("Could not connect to MongoDB: %s" % e )
print("Connection:",conn)
## Connect to the DataBase ##
db = conn.mydatabase
print("database:", db)
## Update log level ##
loglvl = db.setloglevel
result=loglvl(5, "storage")
setlvl()
最佳答案
“setLogLevel”是一个用Javascript实现的mongo shell函数。您可以通过在 mongo shell 中键入其名称(不带括号)来查看任何 mongo shell 函数的实现:
> db.setLogLevel
function (logLevel, component) {
return this.getMongo().setLogLevel(logLevel, component);
}
好的,让我们更深入地了解一下实现:
> db.getMongo().setLogLevel
function (logLevel, component) {
componentNames = [];
if (typeof component === "string") {
componentNames = component.split(".");
} else if (component !== undefined) {
throw Error("setLogLevel component must be a string:" + tojson(component));
}
var vDoc = {verbosity: logLevel};
// nest vDoc
for (var key, obj; componentNames.length > 0;) {
obj = {};
key = componentNames.pop();
obj[key] = vDoc;
vDoc = obj;
}
var res = this.adminCommand({setParameter: 1, logComponentVerbosity: vDoc});
if (!res.ok)
throw _getErrorWithCode(res, "setLogLevel failed:" + tojson(res));
return res;
}
现在我们看到 shell 在管理数据库上运行“setParameter”函数。请参阅 setParameter 文档:
https://docs.mongodb.com/manual/reference/command/setParameter/
由于“setParameter”是一个 MongoDB 命令,我们可以在 PyMongo 中运行它,就像使用 PyMongo 运行任何 MongoDB 命令一样:
from bson import SON
from pymongo import MongoClient
c = MongoClient()
result = c.admin.command(SON([
("setParameter", 1),
("logComponentVerbosity", {
"storage": {
"verbosity": 5,
"journal": {
"verbosity": 1
}
}
})]))
print(result)
关于mongodb - PyMongo 设置日志级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42632816/