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;
}
}

  

日志自定义Tag的更多相关文章

  1. jsp如何自定义tag的标签库?

    虽然和上一次的使用自定义的tld标签简化jsp的繁琐操作的有点不同,但是目的也是一致的.自定义tag比较简单. 1.新建tag标签 在WEB-INF目录下新建一个tags的文件夹,是自定义tag标签的 ...

  2. ASP.NET Core MVC – 自定义 Tag Helpers

    ASP.NET Core Tag Helpers系列目录,共四篇: ASP.NET Core MVC Tag Helpers 介绍 ASP.NET Core MVC – Caching Tag Hel ...

  3. 自定义tag标签-实现long类型转换成Date类型

    数据库里存储的是bigint型的时间,entity实体中存放的是long类型的标签,现在想输出到jsp页面,由于使用的是jstl标签,而要显示的是可读的时间类型,找来找去有个 fmt:formatDa ...

  4. jsp中 自定义 tag的几种方式

    在jsp文件中,可以引用tag和tld文件. 1.对于tag文件,使用tagdir引用(这个直接是引用的后缀tag文件的jsp文件) <%@ taglib prefix="ui&quo ...

  5. Jsp 自定义tag标签

    1转自:https://blog.csdn.net/yusimiao/article/details/46835617 Jsp自定义tag标签 自定义tag标签的好处 程序员可以自定一些特定功能的标记 ...

  6. 自定义tag标签的方法

    JSP1.0中可以通过继承TagSupport或者BodyTagSupport来实现自定义的tag处理方法. JSP2.0中也支持另外一种更为简单的自定tag的方法,那就是直接讲JSP代码保存成*.t ...

  7. JSP自定义tag控件标签

    JSP支持自定tag的方法,那就是直接讲JSP代码保存成*.tag或者*.tagx的标签定义文件.tag和tagx文件不仅支持经典jsp代码,各种标签模版代码,还支持xml样式的jsp指令代码. 按照 ...

  8. struts2 自定义tag标签

    在项目中可能有很多相同的jsp页面表示功能,这时可以使用自定义的tag进行定义,渐少重复的工作量便于日后维护! 下面就基于struts2进行自定义标签的定义与实现: 首先:自定义类MyTag继承str ...

  9. JSP自定义tag

    前端需要调用后端的配置,想起velocity-tools.然而jsp的话,目前只能想到tag和EL表达式了. Tag相当好写,jsp2.0提供了简化写法: 编写一个java类: public clas ...

随机推荐

  1. LeetCode——Implement Stack using Queues

    Description: Implement the following operations of a stack using queues. push(x) -- Push element x o ...

  2. 对规范中每个模块只允许一个id的理解

    优点: 每个模块只有一个ID,并且在css中不适用ID,ID从模板中传入js中,则该模块的复用灵活性会非常高.想要复用该模块时,只需要改动两个地方.一个是html中的ID,另外一个是写到全局conf. ...

  3. Python的反序列化漏洞

    最近准备研究一下反序列化漏洞,但是Java代码看不懂,所以先找一个python的看起,毕竟这种漏洞在python.php中一样存在,等研究明白了基本原理后去看java的反序列化漏洞. python反序 ...

  4. 使用springBoot进行快速开发

    springBoot项目是spring的一个子项目,使用约定由于配置的思想省去了以往在开发过程中许多的配置工作(其实使用springBoot并不是零配置,只是使用了注解完全省去了XML文件的配置),达 ...

  5. Egret3D初步笔记二 (Unity导出场景使用)

    一 Scene 根据上一节的继续.在导入unity4.7.1_Egret3D_Dll.unitypackage后. 在Unity中双击打开Assets/Egret3D/Example下的Example ...

  6. 【BZOJ4401/3004】块的计数/吊灯 乱搞

    [BZOJ4401]块的计数 Description 小Y最近从同学那里听说了一个十分牛B的高级数据结构——块状树.听说这种数据结构能在sqrt(N)的时间内维护树上的各种信息,十分的高效.当然,无聊 ...

  7. yii2.0 如何按需加载并管理CSS样式及JS脚本

    链接:http://www.yiichina.com/tutorial/399 (注:以下为Yii2.0高级应用测试) Yii2.0对于CSS/JS 管理,使用AssetBundle资源包类. 视图如 ...

  8. django-base

    1.django创建 2.django常用命令 3.django配置 一.创建django程序 1.终端:django-admin startproject sitename 2.IDE创建Djang ...

  9. DNS的MX记录和CNAME记录(转)

    MX记录就是邮件域名对邮件服务器(域名)的映射.可以映射到多个邮件服务器,发送时会选择一台发送. 拿到新域名后,还要再查找DNS,将域名转不ip 原文:http://my.oschina.net/u/ ...

  10. 评论抓取:Python爬取微信在APPStore上的评论内容及星级

    #完整程序如下: import requests import re def getHTMLText(url): try: r = requests.get(url) r.raise_for_stat ...