Log4j 사용자 정의 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.");
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
레코드를 업데이트하고 업데이트 전에 동일한 레코드를 삭제하는 방법(nest js & mongoDB)ID로 레코드를 업데이트하고 싶지만 업데이트 전에 동일한 레코드에 이전에 저장된 데이터를 삭제하고 싶습니다. 프로세스는 무엇입니까? 컨트롤러.ts 서비스.ts 나는 이것을 해결하기 위해 이런 식으로 노력하고 있습니다...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.