1. 程式人生 > >Java連線mongodb存取資料時調整日誌輸出級別

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.