001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache license, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the license for the specific language governing permissions and 015 * limitations under the license. 016 */ 017 package org.apache.logging.log4j.core.appender.db.nosql.mongo; 018 019 import org.apache.logging.log4j.Logger; 020 import org.apache.logging.log4j.core.appender.db.nosql.NoSQLConnection; 021 import org.apache.logging.log4j.core.appender.db.nosql.NoSQLObject; 022 import org.apache.logging.log4j.status.StatusLogger; 023 024 import com.mongodb.BasicDBObject; 025 import com.mongodb.DB; 026 import com.mongodb.DBCollection; 027 import com.mongodb.Mongo; 028 import com.mongodb.MongoException; 029 import com.mongodb.WriteConcern; 030 import com.mongodb.WriteResult; 031 032 /** 033 * The MongoDB implementation of {@link NoSQLConnection}. 034 */ 035 public final class MongoDBConnection implements NoSQLConnection<BasicDBObject, MongoDBObject> { 036 private static final Logger LOGGER = StatusLogger.getLogger(); 037 038 private final DBCollection collection; 039 private final Mongo mongo; 040 private final WriteConcern writeConcern; 041 042 public MongoDBConnection(final DB database, final WriteConcern writeConcern, final String collectionName) { 043 this.mongo = database.getMongo(); 044 this.collection = database.getCollection(collectionName); 045 this.writeConcern = writeConcern; 046 } 047 048 @Override 049 public MongoDBObject createObject() { 050 return new MongoDBObject(); 051 } 052 053 @Override 054 public MongoDBObject[] createList(final int length) { 055 return new MongoDBObject[length]; 056 } 057 058 @Override 059 public void insertObject(final NoSQLObject<BasicDBObject> object) { 060 try { 061 final WriteResult result = this.collection.insert(object.unwrap(), this.writeConcern); 062 if (result.getN() < 1) { 063 LOGGER.error("Failed to write log event to MongoDB due to invalid result [{}].", result.getN()); 064 } 065 } catch (final MongoException e) { 066 LOGGER.error("Failed to write log event to MongoDB due to error.", e); 067 } 068 } 069 070 @Override 071 public void close() { 072 this.mongo.close(); 073 } 074 075 @Override 076 public boolean isClosed() { 077 return !this.mongo.getConnector().isOpen(); 078 } 079 }