Log4j 사용자 정의 Appender(둘)

21041 단어 mongodblog4jappender
사용자 정의 Appender 실제 적용
 
장면1:log4j MongoDB 플러그인을 이용하여 MongoDB 데이터베이스에 데이터를 쓰기
 
1. 프로젝트 도입jar 패키지:spring-data-mongodb-log4j:1.8.0 및log4j1.2이상jar 패키지
2.log4j.properties 구성
 
 
log4j.rootLogger=INFO, stdout

log4j.appender.stdout=org.springframework.data.mongodb.log4j.MongoLog4jAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n
log4j.appender.stdout.host = localhost
log4j.appender.stdout.port = 27017
log4j.appender.stdout.database = logs
#log4j.appender.stdout.collectionPattern = %X{year}%X{month}
log4j.appender.stdout.collectionPattern = sys_logs
log4j.appender.stdout.applicationId = my.application
log4j.appender.stdout.warnOrHigherWriteConcern = FSYNC_SAFE

 
3. 응용 프로그램
 
Logger log = Logger.getRootLogger();
log.info("I am ready.") ;

 
 
설명:
org.springframework.data.mongodb.log4j.MongoLog4jAppender

이 중
extends AppenderSkeleton

 
사용자 정의 Appender는 다음과 같습니다.
 
package org.springframework.data.mongodb.log4j;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.WriteConcern;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.MDC;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent;
public class MongoLog4jAppender extends AppenderSkeleton {
    public static final String LEVEL = "level";
    public static final String NAME = "name";
    public static final String APP_ID = "applicationId";
    public static final String TIMESTAMP = "timestamp";
    public static final String PROPERTIES = "properties";
    public static final String TRACEBACK = "traceback";
    public static final String MESSAGE = "message";
    public static final String YEAR = "year";
    public static final String MONTH = "month";
    public static final String DAY = "day";
    public static final String HOUR = "hour";
    protected String host = "localhost";
    protected int port = 27017;
    protected String database = "logs";
    protected String collectionPattern = "%c";
    protected PatternLayout collectionLayout;
    protected String applicationId;
    protected WriteConcern warnOrHigherWriteConcern;
    protected WriteConcern infoOrLowerWriteConcern;
    protected Mongo mongo;
    protected DB db;
    public MongoLog4jAppender() {
        this.collectionLayout = new PatternLayout(this.collectionPattern);
        this.applicationId = System.getProperty("APPLICATION_ID", (String)null);
        this.warnOrHigherWriteConcern = WriteConcern.SAFE;
        this.infoOrLowerWriteConcern = WriteConcern.NORMAL;
}

    public MongoLog4jAppender(boolean isActive) {
        super(isActive);
        this.collectionLayout = new PatternLayout(this.collectionPattern);
        this.applicationId = System.getProperty("APPLICATION_ID", (String)null);
        this.warnOrHigherWriteConcern = WriteConcern.SAFE;
        this.infoOrLowerWriteConcern = WriteConcern.NORMAL;
}

    public String getHost() {
        return this.host;
}

    public void setHost(String host) {
        this.host = host;
}

    public int getPort() {
        return this.port;
}

    public void setPort(int port) {
        this.port = port;
}

    public String getDatabase() {
        return this.database;
}

    public void setDatabase(String database) {
        this.database = database;
}

    public String getCollectionPattern() {
        return this.collectionPattern;
}

    public void setCollectionPattern(String collectionPattern) {
        this.collectionPattern = collectionPattern;
        this.collectionLayout = new PatternLayout(collectionPattern);
}

    public String getApplicationId() {
        return this.applicationId;
}

    public void setApplicationId(String applicationId) {
        this.applicationId = applicationId;
}

    public void setWarnOrHigherWriteConcern(String wc) {
        this.warnOrHigherWriteConcern = WriteConcern.valueOf(wc);
}

    public String getWarnOrHigherWriteConcern() {
        return this.warnOrHigherWriteConcern.toString();
}

    public String getInfoOrLowerWriteConcern() {
        return this.infoOrLowerWriteConcern.toString();
}

    public void setInfoOrLowerWriteConcern(String wc) {
        this.infoOrLowerWriteConcern = WriteConcern.valueOf(wc);
}

    protected void connectToMongo() throws UnknownHostException {
        this.mongo = new Mongo(this.host, this.port);
        this.db = this.mongo.getDB(this.database);
}

    protected void append(LoggingEvent event) {
        if(null == this.db) {
            try {
                this.connectToMongo();
} catch (UnknownHostException var9) {
                throw new RuntimeException(var9.getMessage(), var9);
}
        }

        BasicDBObject dbo = new BasicDBObject();
        if(null != this.applicationId) {
            dbo.put("applicationId", this.applicationId);
MDC.put("applicationId", this.applicationId);
}

        dbo.put("name", event.getLogger().getName());
dbo.put("level", event.getLevel().toString());
Calendar tstamp = Calendar.getInstance();
tstamp.setTimeInMillis(event.getTimeStamp());
dbo.put("timestamp", tstamp.getTime());
Map props = event.getProperties();
        if(null != props && props.size() > 0) {
            BasicDBObject traceback = new BasicDBObject();
Iterator now = props.entrySet().iterator();
            while(now.hasNext()) {
                Entry coll = (Entry)now.next();
traceback.put(coll.getKey().toString(), coll.getValue().toString());
}

            dbo.put("properties", traceback);
}

        String[] traceback1 = event.getThrowableStrRep();
        if(null != traceback1 && traceback1.length > 0) {
            BasicDBList now2 = new BasicDBList();
now2.addAll(Arrays.asList(traceback1));
dbo.put("traceback", now2);
}

        dbo.put("message", event.getRenderedMessage());
Calendar now1 = Calendar.getInstance();
MDC.put("year", Integer.valueOf(now1.get(1)));
MDC.put("month", String.format("%1$02d", new Object[]{Integer.valueOf(now1.get(2) + 1)}));
MDC.put("day", String.format("%1$02d", new Object[]{Integer.valueOf(now1.get(5))}));
MDC.put("hour", String.format("%1$02d", new Object[]{Integer.valueOf(now1.get(11))}));
String coll1 = this.collectionLayout.format(event);
MDC.remove("year");
MDC.remove("month");
MDC.remove("day");
MDC.remove("hour");
        if(null != this.applicationId) {
            MDC.remove("applicationId");
}

        WriteConcern wc;
        if(event.getLevel().isGreaterOrEqual(Level.WARN)) {
            wc = this.warnOrHigherWriteConcern;
} else {
            wc = this.infoOrLowerWriteConcern;
}

        this.db.getCollection(coll1).insert(dbo, wc);
}

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

    }

    public boolean requiresLayout() {
        return true;
}
}

 
장면2: 프로젝트의 어떤 조작이나 실행 기록, 사용자 정의 Appender를 통해 파일이나 프린터 컨트롤 등에 쓰기
 
1.log4j.properties 구성
 
 
log4j.logger.historyLog=INFO, history
log4j.additivity.historyLog= false
log4j.appender.history=com.xxx.HistoryLogAppender
log4j.appender.history.host = localhost
log4j.appender.history.port = 27017
log4j.appender.history.database = logs
log4j.appender.history.collectionPattern = %X{year}%X{month}
#log4j.appender.history.collectionPattern = sys_logs
log4j.appender.history.hs_name=hs_name

그중com.xxx.HistoryLogAppender는 프로젝트에서 상속을 통과합니다.
 
 
extends AppenderSkeleton {

구현된 사용자 정의 Appender
 
2. 응용 프로그램
 
Logger cutsomLog = Logger.getLogger("historyLog");
cutsomLog.info("I am ready.");

 

좋은 웹페이지 즐겨찾기