Java连接mongodb存取数据时调整日志输出级别

通过JDBC的方式连接mongodb进行数据存取时在终端上打印以下日志

Nov 22, 2017 7:01:12 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[172.16.0.102:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Nov 22, 2017 7:01:12 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by WritableServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=172.16.0.102:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
Nov 22, 2017 7:01:12 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:1041760}] to 172.16.0.102:27017
Nov 22, 2017 7:01:12 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=172.16.0.102:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 4, 10]}, minWireVersion=0, maxWireVersion=5, maxDocumentSize=16777216, roundTripTimeNanos=642876}
Nov 22, 2017 7:01:13 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:1041761}] to 172.16.0.102:27017
Nov 22, 2017 7:01:13 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Closed connection [connectionId{localValue:2, serverValue:1041761}] to 172.16.0.102:27017 because the pool has been closed.

这些是java自带的日志输出的,我们看到打印出的日志级别是INFO的,不是报错信息,在部署到正式版的时候,通常是不需要打印这些日志,那么我们可以通过提高日志级别来控制不需要的日志输出,实现方法如下

public static MongoClient getJDBCConnection4Mongo(){

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

        MongoCredential credential = null;

        MongoClient mongoClient = null;

        try{
            credential = MongoCredential.createCredential(mongoUser, mongoDB, mongoPass.toCharArray());

            mongoClient = new MongoClient(new ServerAddress(mongoHost, Integer.valueOf(mongoPort)), Arrays.asList(credential));

        }catch(Exception e){
            ExceptionUtils.handleException(e);
        }

        return mongoClient;
    }

其中下面两行代码就是设置日志级别的,这样就不会打印INFO级别的日志了。

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

当然,如果将日志级别设置的太高会导致错误日志也不会输出,所以最好是将日志级别设置为Level.SEVERE,这样出现错误时都会被打印出来。

In general SEVERE messages should describe events that are of considerable importance and which will prevent normal program execution. They should be reasonably intelligible to end users and to system administrators. This level is initialized to 1000.

猜你喜欢

转载自blog.csdn.net/shiyong1949/article/details/78610500