zno2

MongoDBAppender

 

 

分三步:

1. client

2. appender

3. 配置文件

 

logback-test.xml

<configuration>

    <appender name="MONGO" class="cn.zno.mongodb.MongoDBAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <mongoClient class="cn.zno.mongodb.CustomMongoClient">
            <uri><![CDATA[mongodb://xiaoming:123456@localhost:27017/?authSource=logtest&authMechanism=MONGODB-CR]]></uri>
            <dbName>logtest</dbName>
            <collectionName>news</collectionName>
        </mongoClient>
    </appender>

    <root level="INFO">
        <appender-ref ref="MONGO" />
    </root>

</configuration>

 

MongoDBAppender.java

package cn.zno.mongodb;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

import org.bson.Document;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;

public class MongoDBAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {

    public static final String UNKNOW_HOST = "unknow host";

    private CustomMongoClient mongoClient;

    @Override
    protected void append(ILoggingEvent eventObject) {
        if (mongoClient.getCollection() == null) {
            mongoClient.init();
            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                public void run() {
                    mongoClient.destroy();
                }
            }, "mongo shutdown"));
        }

        Document document = new Document();
        document.append("message", eventObject.getFormattedMessage());
        document.append("logger", eventObject.getLoggerName());
        document.append("thread", eventObject.getThreadName());
        document.append("timestamp", new Date(eventObject.getTimeStamp()));
        document.append("level", eventObject.getLevel().toString());
        document.append("pid", getPid());
        document.append("ip", getIp());

        mongoClient.getCollection().insertOne(document);
    }

    private String getIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return UNKNOW_HOST;
        }
    }

    private String getPid() {
        return ManagementFactory.getRuntimeMXBean().getName();
    }

    public CustomMongoClient getMongoClient() {
        return mongoClient;
    }

    public void setMongoClient(CustomMongoClient mongoClient) {
        this.mongoClient = mongoClient;
    }
}

 

CustomMongoClient.java

package cn.zno.mongodb;

import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;

public class CustomMongoClient {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    
    private MongoClient mongoClient;
    private MongoCollection<Document> mongoCollection;

    private String uri;
    private String dbName;
    private String collectionName;

    public void init() {
        MongoClientURI mongoClientURI = new MongoClientURI(uri);
        mongoClient = new MongoClient(mongoClientURI);
        mongoCollection = mongoClient.getDatabase(dbName).getCollection(collectionName);
        logger.info("MongoClient init");
    }

    public void destroy() {
        mongoClient.close();
        logger.info("MongoClient closed");
    }

    public MongoCollection<Document> getCollection() {
        return this.mongoCollection;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getDbName() {
        return dbName;
    }

    public void setDbName(String dbName) {
        this.dbName = dbName;
    }

    public String getCollectionName() {
        return collectionName;
    }

    public void setCollectionName(String collectionName) {
        this.collectionName = collectionName;
    }
}

 

如何使用:

logger.error("这是一个错误!");

结果:

 

需要关注的字段

create table loginfo
(
   id                   char(10),
   app_name             char(10),
   server_ip            char(10),
   server_port          char(10),
   env                  char(10),
   jvm                  char(10),
   thread_id            char(10),
   thread_name          char(10),
   trace_id             char(10),
   trace_step           char(10),
   level                char(10),
   logger               char(10),
   line_no              char(10),
   msg                  char(10),
   create_time          char(10),
   create_millis        char(10)
);

 

posted on 2016-08-06 07:48  zno2  阅读(716)  评论(0编辑  收藏  举报

导航