import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentHashMap; /** * Created by */ public class LogWrapperFactory { private static ConcurrentMap<String, LogWrapper> concurrentMap = new ConcurrentHashMap<String, LogWrapper>(); public static LogWrapper getLogWrapper(Class clazz){ //使用java8语法优化代码 concurrentMap.computeIfAbsent(clazz.getName(), k->new LogWrapper(clazz)); return concurrentMap.get(clazz.getName()); } }
import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Strings; import org.apache.commons.collections.CollectionUtils; /** * Created by */ public class LogWrapper { private Logger logger; private ThreadLocal<List<Map<String, Object>>> tagThreadLocal = new ThreadLocal<List<Map<String, Object>>>(); public LogWrapper(Class clazz) { this.logger = LoggerFactory.getLogger(clazz.getName()); if (null == tagThreadLocal.get()) { tagThreadLocal.set(new ArrayList<Map<String, Object>>()); } } public void clearTags() { this.tagThreadLocal.set(new ArrayList()); } public LogWrapper addTag(String tagName, Object tagValue) { List<Map<String, Object>> list = (List) tagThreadLocal.get(); list = Optional.ofNullable(list).orElse(new ArrayList<Map<String, Object>>()); Map<String, Object> tmap = new HashMap<String, Object>(); tmap.put(tagName, tagValue); list.add(tmap); tagThreadLocal.set(list); return this; } public LogWrapper TAG(Object tagValue) { addTag("TYPE", tagValue); return this; } public LogWrapper KBCODE(Object tagValue) { addTag("KBCODE", tagValue); return this; } public LogWrapper SERIALNO(Object tagValue) { addTag("SERIALNO", tagValue); return this; } private void commonWriteLog(LogType logType, String firstParam) { StringBuilder tagsBuilder = new StringBuilder("[ThreadName=" + Thread.currentThread().getName()+"]"); List<Map<String, Object>> list = (List) tagThreadLocal.get(); if (CollectionUtils.isNotEmpty(list)) { list.stream().forEach(itemMap->{itemMap.forEach((k,v)->{tagsBuilder.append("[" + Strings.nullToEmpty(k) + "=" + Strings.nullToEmpty(String.valueOf(v)) + "]");});}); } switch (logType) { case INFO: logger.info(tagsBuilder.toString() + Strings.nullToEmpty(firstParam)); break; case WARN: logger.warn(tagsBuilder.toString() + Strings.nullToEmpty(firstParam)); break; case ERROR: logger.error(tagsBuilder.toString() + Strings.nullToEmpty(firstParam)); break; default: logger.info(tagsBuilder.toString() + Strings.nullToEmpty(firstParam)); } clearTags(); } private void commonWriteLog(LogType logType, String firstParam, Object... content) { StringBuilder tagsBuilder = new StringBuilder("[ThreadName=" + Thread.currentThread().getName()+"]"); List<Map<String, Object>> list = (List<Map<String, Object>>) tagThreadLocal.get(); if (CollectionUtils.isNotEmpty(list)) { list.stream().forEach(itemMap->{itemMap.forEach((k,v)->{tagsBuilder.append("[" + Strings.nullToEmpty(k) + "=" + Strings.nullToEmpty(String.valueOf(v)) + "]");});}); } switch (logType) { case INFO: logger.info(tagsBuilder.toString() + Strings.nullToEmpty(firstParam), content); break; case WARN: logger.warn(tagsBuilder.toString() + Strings.nullToEmpty(firstParam), content); break; case ERROR: logger.error(tagsBuilder.toString() + Strings.nullToEmpty(firstParam), content); break; default: logger.info(tagsBuilder.toString() + Strings.nullToEmpty(firstParam), content); } clearTags(); } public void info(String firstParam) { commonWriteLog(LogType.INFO, firstParam); } public void info(String firstParam, Object... content) { commonWriteLog(LogType.INFO, firstParam, content); } public void warn(String firstParam) { commonWriteLog(LogType.WARN, firstParam); } public void warn(String firstParam, Object... content) { commonWriteLog(LogType.WARN, firstParam, content); } public void error(String firstParam) { commonWriteLog(LogType.ERROR, firstParam); } public void error(String firstParam, Object content) { commonWriteLog(LogType.ERROR, firstParam, content); } public static void main(String[] args) throws Exception{ // new Thread(() -> { // LogWrapper log = LogWrapperFactory.getLogWrapper(LogWrapper.class); // log.addTag("abc", "abc").addTag("def", "def").info("i am {},welcome!{}", "flory", "ttt"); // }).start(); // // new Thread(() -> { // LogWrapper log2 = LogWrapperFactory.getLogWrapper(WarrantController.class); // log2.addTag("123", "123").addTag("456", "456").info("i am {},welcome!{}", "flory", "ttt"); // }).start(); // LogWrapper log3 = LogWrapperFactory.getLogWrapper(WarrantController.class); // log3.addTag("abc", "abc").addTag("def", "def").info("i am {},welcome!{}", "flory", "ttt"); } private enum LogType { INFO(1, "info"), WARN(2, "warn"), ERROR(3, "error"); private Integer code; private String msg; LogType(Integer code, String msg) { this.code = code; this.msg = msg; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } } }
使用示例:
import com.alibaba.fastjson.JSON; import com.google.common.base.Throwables; import com.pingan.bloan.genesis.logwrapper.LogWrapper; import com.pingan.bloan.genesis.logwrapper.LogWrapperFactory; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Created by */ public class HttpExecute { private static LogWrapper loggerWrapper = LogWrapperFactory.getLogWrapper(HttpExecute.class); private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; private static final String UTF_8 = "UTF-8"; /** * post方法 * * @param url * @param paramMap * @return */ public static String executePost(String url, Map<String, Object> paramMap) { HttpResponse response = null; String sResponse = ""; try { loggerWrapper.TAG("executePost").info("start visit outside resource, url:{}, prams:{}", url, JSON.toJSONString(paramMap)); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); HttpEntity entity = new StringEntity(JSON.toJSONString(paramMap), UTF_8); httpPost.setEntity(entity); RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout(10000).build(); httpPost.setConfig(requestConfig); httpPost.addHeader("Content-Type", CONTENT_TYPE); httpPost.addHeader("Accept", CONTENT_TYPE); loggerWrapper.TAG("HttpClientService").info("httpClient config finished, start invoking..."); response = httpClient.execute(httpPost); loggerWrapper.TAG("HttpClientService").info("httpClient finished response:{}", JSON.toJSONString(response)); sResponse = EntityUtils.toString(response.getEntity()); loggerWrapper.TAG("HttpClientService").info("invoke finished, response entity:{}", JSON.toJSONString(sResponse)); } catch (UnsupportedEncodingException e) { loggerWrapper.TAG("executePost").error("UnsupportedEncodingException, details:{}", Throwables.getStackTraceAsString(e)); } catch (ClientProtocolException e) { loggerWrapper.TAG("executePost").error("ClientProtocolException, details:{}", Throwables.getStackTraceAsString(e)); } catch (IOException e) { loggerWrapper.TAG("executePost").error("IOException, details:{}", Throwables.getStackTraceAsString(e)); } return sResponse; } }