View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.mongodb2;
18  
19  import org.apache.logging.log4j.Level;
20  import org.apache.logging.log4j.Logger;
21  import org.apache.logging.log4j.core.appender.AppenderLoggingException;
22  import org.apache.logging.log4j.core.appender.nosql.AbstractNoSqlConnection;
23  import org.apache.logging.log4j.core.appender.nosql.NoSqlConnection;
24  import org.apache.logging.log4j.core.appender.nosql.NoSqlObject;
25  import org.apache.logging.log4j.status.StatusLogger;
26  import org.bson.BSON;
27  import org.bson.Transformer;
28  
29  import com.mongodb.BasicDBObject;
30  import com.mongodb.DB;
31  import com.mongodb.DBCollection;
32  import com.mongodb.Mongo;
33  import com.mongodb.MongoException;
34  import com.mongodb.WriteConcern;
35  
36  /**
37   * The MongoDB implementation of {@link NoSqlConnection}.
38   */
39  public final class MongoDbConnection extends AbstractNoSqlConnection<BasicDBObject, MongoDbObject> {
40  
41      private static final Logger LOGGER = StatusLogger.getLogger();
42  
43      static {
44          BSON.addEncodingHook(Level.class, new Transformer() {
45              @Override
46              public Object transform(final Object o) {
47                  if (o instanceof Level) {
48                      return ((Level) o).name();
49                  }
50                  return o;
51              }
52          });
53      }
54  
55      private final DBCollection collection;
56      private final WriteConcern writeConcern;
57  
58      public MongoDbConnection(final DB database, final WriteConcern writeConcern, final String collectionName,
59              final Boolean isCapped, final Integer collectionSize) {
60          if (database.collectionExists(collectionName)) {
61              LOGGER.debug("Gettting collection {}", collectionName);
62              collection = database.getCollection(collectionName);
63          } else {
64              final BasicDBObject options = new BasicDBObject();
65              options.put("capped", isCapped);
66              options.put("size", collectionSize);
67              LOGGER.debug("Creating collection {} (capped = {}, size = {})", collectionName, isCapped, collectionSize);
68              this.collection = database.createCollection(collectionName, options);
69          }
70          this.writeConcern = writeConcern;
71      }
72  
73      @Override
74      public void closeImpl() {
75          // LOG4J2-1196
76          final Mongo mongo = this.collection.getDB().getMongo();
77          LOGGER.debug("Closing {} client {}", mongo.getClass().getSimpleName(), mongo);
78          mongo.close();
79      }
80  
81      @Override
82      public MongoDbObject[] createList(final int length) {
83          return new MongoDbObject[length];
84      }
85  
86      @Override
87      public MongoDbObject createObject() {
88          return new MongoDbObject();
89      }
90  
91      @Override
92      public void insertObject(final NoSqlObject<BasicDBObject> object) {
93          try {
94              final BasicDBObject unwrapped = object.unwrap();
95              LOGGER.debug("Inserting object {}", unwrapped);
96              this.collection.insert(unwrapped, this.writeConcern);
97          } catch (final MongoException e) {
98              throw new AppenderLoggingException("Failed to write log event to MongoDB due to error: " + e.getMessage(),
99                      e);
100         }
101     }
102 
103 }