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 */
017package org.apache.logging.log4j.mongodb2;
018
019import org.apache.logging.log4j.Level;
020import org.apache.logging.log4j.Logger;
021import org.apache.logging.log4j.core.appender.AppenderLoggingException;
022import org.apache.logging.log4j.core.appender.nosql.AbstractNoSqlConnection;
023import org.apache.logging.log4j.core.appender.nosql.NoSqlConnection;
024import org.apache.logging.log4j.core.appender.nosql.NoSqlObject;
025import org.apache.logging.log4j.status.StatusLogger;
026import org.bson.BSON;
027import org.bson.Transformer;
028
029import com.mongodb.BasicDBObject;
030import com.mongodb.DB;
031import com.mongodb.DBCollection;
032import com.mongodb.Mongo;
033import com.mongodb.MongoException;
034import com.mongodb.WriteConcern;
035
036/**
037 * The MongoDB implementation of {@link NoSqlConnection}.
038 */
039public final class MongoDbConnection extends AbstractNoSqlConnection<BasicDBObject, MongoDbObject> {
040
041    private static final Logger LOGGER = StatusLogger.getLogger();
042
043    static {
044        BSON.addEncodingHook(Level.class, new Transformer() {
045            @Override
046            public Object transform(final Object o) {
047                if (o instanceof Level) {
048                    return ((Level) o).name();
049                }
050                return o;
051            }
052        });
053    }
054
055    private final DBCollection collection;
056    private final WriteConcern writeConcern;
057
058    public MongoDbConnection(final DB database, final WriteConcern writeConcern, final String collectionName,
059            final Boolean isCapped, final Integer collectionSize) {
060        if (database.collectionExists(collectionName)) {
061            LOGGER.debug("Gettting collection {}", collectionName);
062            collection = database.getCollection(collectionName);
063        } else {
064            final BasicDBObject options = new BasicDBObject();
065            options.put("capped", isCapped);
066            options.put("size", collectionSize);
067            LOGGER.debug("Creating collection {} (capped = {}, size = {})", collectionName, isCapped, collectionSize);
068            this.collection = database.createCollection(collectionName, options);
069        }
070        this.writeConcern = writeConcern;
071    }
072
073    @Override
074    public void closeImpl() {
075        // LOG4J2-1196
076        final Mongo mongo = this.collection.getDB().getMongo();
077        LOGGER.debug("Closing {} client {}", mongo.getClass().getSimpleName(), mongo);
078        mongo.close();
079    }
080
081    @Override
082    public MongoDbObject[] createList(final int length) {
083        return new MongoDbObject[length];
084    }
085
086    @Override
087    public MongoDbObject createObject() {
088        return new MongoDbObject();
089    }
090
091    @Override
092    public void insertObject(final NoSqlObject<BasicDBObject> object) {
093        try {
094            final BasicDBObject unwrapped = object.unwrap();
095            LOGGER.debug("Inserting object {}", unwrapped);
096            this.collection.insert(unwrapped, this.writeConcern);
097        } catch (final MongoException e) {
098            throw new AppenderLoggingException("Failed to write log event to MongoDB due to error: " + e.getMessage(),
099                    e);
100        }
101    }
102
103}