如何防止从java连接到mongodb时登录控制台?

2022-09-03 09:36:14

我关注了这个mongodb文档。这是我的代码

public class JMongoDBCDemo
{
    MongoClient mongoClient;
    DB db;
    DBCollection coll;
    public JMongoDBCDemo()
    {
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
        db = mongoClient.getDB( "messenger" );
        coll = db.getCollection("users");
        DBObject myDoc = coll.findOne();
        System.out.println(myDoc);
        mongoClient.close();
        System.out.println("Got a collection...");
    }
    public static void main(String[] args){
            JMongoDBCDemo mongoDemo = new JMongoDBCDemo();
    }
}

下面是输出

Apr 05, 2015 12:17:47 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Apr 05, 2015 12:17:47 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
Apr 05, 2015 12:17:47 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:3}] to localhost:27017
Apr 05, 2015 12:17:47 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[2, 6, 1]}, minWireVersion=0, maxWireVersion=2, maxDocumentSize=16777216, roundTripTimeNanos=389140}
Apr 05, 2015 12:17:47 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:4}] to localhost:27017
{ "_id" : { "$oid" : "55201cec68fb70b6affba026"} , "name" : "prasad" , "password" : "123456"} //This is my output
Apr 05, 2015 12:17:47 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Closed connection [connectionId{localValue:2, serverValue:4}] to localhost:27017 because the pool has been closed.
Got a collection... //my output

根据文档,它应该像打印

{ "_id" : { "$oid" : "55201cec68fb70b6affba026"} , "name" : "prasad" , "password" : "123456"}
Got a collection... 

因此,任何人都可以帮助我在控制台中阻止这些日志。


答案 1

感谢@jyemin通过使用MongoDB官方文档链接

Logger mongoLogger = Logger.getLogger( "org.mongodb.driver" );
mongoLogger.setLevel(Level.SEVERE); 

现在控制台中没有日志。


答案 2

我试过这个java.util.logging.Logger.getLogger("org.mongodb.driver").setLevel(Level.OFF);

它不起作用,它仍然记录com.mongodb.diagnostics.logging.JULLogger log

我把它改成了JULLogger,它工作了

java.util.logging.Logger.getLogger("JULLogger").setLevel(Level.OFF);