
package com.weds.framework.utils.elk; import java.util.Map; import java.util.concurrent.CompletableFuture; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggingEvent; import com.weds.framework.core.utils.JsonUtil; import com.weds.framework.core.utils.redis.RedisService; /** * * <p>Title: ApiAppender</p> * <p>Description: 重写Appender 调用log4就时,将记录存入redis</p> * <p>Company: Leyou(China) Chain Store Co.,Ltd</p> * <p>版权所有: Copyright?1999-2016 leyou.com. All Rights Reserved</p> * @author Illidan * @date 2016年5月19日 上午10:25:59 * @version V1.0 */ public class ApiAppender extends AppenderSkeleton{ /** * Jredis连接redis的client */ private RedisService redisService; /** * 记录接口方法调用次数日志需要先写入redis中,redis的key不能为空,这个key需要同步在logstash配置文件中配置 */ private String writeLogKey; @Override public void close() { // TODO Auto-generated method stub } @Override public boolean requiresLayout() { // TODO Auto-generated method stub return false; } /** * 重写日志输出输出 */ @Override protected void append(LoggingEvent event) { LocationInfo locationInfo = event.getLocationInformation(); Map<String,Object> map =(Map<String,Object>)event.getMessage(); map.put("levl", event.getLevel().toString()); writeLogAsync(writeLogKey,map); } /** * 异步记录日志 * @param key 记录到redis的中key,key需要同步在logstash配置文件中配置 * @param value 日志的值,Map格式 */ public void writeLogAsync(String key,Map<String,Object> map){ CompletableFuture.runAsync(() -> { writeLog(key,map); }); } /** * * @Title: writeLogAsync * @Description: 异步存储日志 * @param * @return void 返回类型 * @throws * @author Illidan * @date 2016年5月18日 下午1:51:56 */ public void writeLogAsync(String key,String value){ CompletableFuture.runAsync(() -> { writeLog(key,value); }); } /** *记录日志到redis的List集合中,值为Map集合方式 * @param key 记录redis的key,key需要同步在logstash配置文件中配置 * @param map value为Map值 */ public void writeLog(String key,Map<String,Object> map){ String value = JsonUtil.obj2string(map); writeLog(key, value); } /** * 记录日志到redis的List集合中 * @param key 记录redis的key,key需要同步在logstash配置文件中配置 * @param value 记录的值 */ public void writeLog(String key, String value) { if(key != null){ redisService =(RedisService)SpringContextUtil.getBean("redisService",RedisService.class); redisService.setList(key, value); } } public RedisService getRedisService() { return redisService; } public void setRedisService(RedisService redisService) { this.redisService = redisService; } public String getWriteLogKey() { return writeLogKey; } public void setWriteLogKey(String writeLogKey) { this.writeLogKey = writeLogKey; } }