co.dewald.log.MongoDBAppender.java Source code

Java tutorial

Introduction

Here is the source code for co.dewald.log.MongoDBAppender.java

Source

/**
 * <p>
 * This file is part of the MongoDBAppender library.
 * </p>
 * <p> The MongoDBAppender library is free software: you can redistribute it and/or modify it under the terms of the 
 * GNU Lesser General Public License as published by the Free Software Foundation.
 * </p>
 * <p> The MongoDBAppender library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
 * License for more details.
 * </p>
 * <p> You should have received a copy of the GNU Lesser General Public License along with the MongoDBAppender library.  
 * If not, see <http://www.gnu.org/licenses/lgpl.html/>.
 */
package co.dewald.log;

import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LocationInfo;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.ThrowableInformation;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.WriteConcern;

/**
 * MongoDB Appender for Log4J 1.x
 * 
 * 
 * @author Dewald Pretorius
 */
public class MongoDBAppender extends AppenderSkeleton {
    private static final DBObject index = new BasicDBObject("timestamp", -1);

    MongoClient mongo;
    DB db;
    DBCollection logs;

    private String host;
    private String database;
    private String collection;

    /**
     * 
     */
    public MongoDBAppender() {
        super();

        host = "localhost";
        database = "log4j";
        collection = "logs";
    }

    /**
     * @param isActive
     */
    public MongoDBAppender(boolean isActive) {
        super(isActive);
    }

    /**
     *
     */
    public void close() {
        if (mongo != null) {
            mongo.close();
            mongo = null;
        }
    }

    /**
     * @return false
     */
    public boolean requiresLayout() {
        return false;
    }

    /**
     * @param event
     */
    protected void append(LoggingEvent event) {
        try {
            if (!init())
                return;

            BasicDBObject log = new BasicDBObject("timestamp", new Date(event.timeStamp));
            log.append("logger", event.getLoggerName());
            log.append("level", event.getLevel().toString());
            log.append("thread", event.getThreadName());
            log.append("message", event.getRenderedMessage());

            if (event.getLocationInformation() != null) {
                LocationInfo info = event.getLocationInformation();

                log.append("file", info.getFileName());
                log.append("line", info.getLineNumber());
                log.append("class", info.getClassName());
                log.append("method", info.getMethodName());
            }

            if (event.getThrowableInformation() != null) {
                ThrowableInformation info = event.getThrowableInformation();
                BasicDBList throwable = new BasicDBList();

                throwable.addAll(Arrays.asList(info.getThrowableStrRep()));
                log.append("throwable", throwable);
            }

            if (event.getNDC() != null)
                log.append("ndc", event.getNDC());

            try {
                event.getMDCCopy();
                @SuppressWarnings("rawtypes")
                Map properties = event.getProperties();

                if (properties != null && !properties.isEmpty()) {
                    log.append("mdc", new BasicDBObject(properties));
                }
            } catch (NoSuchMethodError backwardsCompatible) {
                backwardsCompatible.printStackTrace();
            }

            this.logs.insert(log);
        } catch (Throwable irony) {
            irony.printStackTrace();
        }
    }

    /**
     * @param host
     */
    public void setHost(String host) {
        this.host = host;
        close();
    }

    /**
     * @param database
     */
    public void setDatabase(String database) {
        this.database = database;

        if (mongo != null) {
            db = mongo.getDB(database);
            setCollection(collection);
        }
    }

    /**
     * @param collection
     */
    public void setCollection(String collection) {
        this.collection = collection;

        if (mongo != null) {
            logs = db.getCollection(collection);
            logs.createIndex(index); // timestamp is indexed in descending order
        }
    }

    /**
     * @return initialised state.
     */
    protected boolean init() {
        if (mongo != null)
            return true;

        try {
            mongo = new MongoClient(host);
            db = mongo.getDB(database);
            logs = db.getCollection(collection);

            mongo.setWriteConcern(WriteConcern.NORMAL);
            logs.createIndex(index); // timestamp is indexed in descending order

            return true;
        } catch (final UnknownHostException e) {
            System.out.println("BAD: Nothing can be logged to MongoDB!");
            e.printStackTrace();
            return false;
        }
    }

    //@formatter:off

    public String getHost() {
        return host;
    }

    public String getDatabase() {
        return database;
    }

    public String getCollection() {
        return collection;
    }
}