自定义Appender实际应用
场景一:利用log4j MongoDB插件 向 MongoDB数据库写入数据
1.项目引入 jar 包:spring-data-mongodb-log4j:1.8.0,及 log4j 1.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; } }
场景二:项目中某项操作或执行记录,通过自定义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.");