日志自定义Tag
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的更多相关文章
- jsp如何自定义tag的标签库?
虽然和上一次的使用自定义的tld标签简化jsp的繁琐操作的有点不同,但是目的也是一致的.自定义tag比较简单. 1.新建tag标签 在WEB-INF目录下新建一个tags的文件夹,是自定义tag标签的 ...
- ASP.NET Core MVC – 自定义 Tag Helpers
ASP.NET Core Tag Helpers系列目录,共四篇: ASP.NET Core MVC Tag Helpers 介绍 ASP.NET Core MVC – Caching Tag Hel ...
- 自定义tag标签-实现long类型转换成Date类型
数据库里存储的是bigint型的时间,entity实体中存放的是long类型的标签,现在想输出到jsp页面,由于使用的是jstl标签,而要显示的是可读的时间类型,找来找去有个 fmt:formatDa ...
- jsp中 自定义 tag的几种方式
在jsp文件中,可以引用tag和tld文件. 1.对于tag文件,使用tagdir引用(这个直接是引用的后缀tag文件的jsp文件) <%@ taglib prefix="ui&quo ...
- Jsp 自定义tag标签
1转自:https://blog.csdn.net/yusimiao/article/details/46835617 Jsp自定义tag标签 自定义tag标签的好处 程序员可以自定一些特定功能的标记 ...
- 自定义tag标签的方法
JSP1.0中可以通过继承TagSupport或者BodyTagSupport来实现自定义的tag处理方法. JSP2.0中也支持另外一种更为简单的自定tag的方法,那就是直接讲JSP代码保存成*.t ...
- JSP自定义tag控件标签
JSP支持自定tag的方法,那就是直接讲JSP代码保存成*.tag或者*.tagx的标签定义文件.tag和tagx文件不仅支持经典jsp代码,各种标签模版代码,还支持xml样式的jsp指令代码. 按照 ...
- struts2 自定义tag标签
在项目中可能有很多相同的jsp页面表示功能,这时可以使用自定义的tag进行定义,渐少重复的工作量便于日后维护! 下面就基于struts2进行自定义标签的定义与实现: 首先:自定义类MyTag继承str ...
- JSP自定义tag
前端需要调用后端的配置,想起velocity-tools.然而jsp的话,目前只能想到tag和EL表达式了. Tag相当好写,jsp2.0提供了简化写法: 编写一个java类: public clas ...
随机推荐
- webpack打包jquery并引用
一,引入webpack插件 //打包第三方 const CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlug ...
- [MongoDB]安装MongoDB遇到问题
1. 首先,当然是下载 MongoDB MongoDB的官方网站是:http://www.mongodb.org/, 最新版本下载在:http://www.mongodb.org/downloads ...
- java如何重命名文件?
/** * 修改文件名 * @param oldFilePath 原文件路径 * @param newFileName 新文件名称 * @param overriding 判断标志(如果存在相同名的文 ...
- angularJS的过滤器!
angularJS过滤器: filter currency date filter json limitTo lowercase number orderBy uppercase ...... Fil ...
- Linux系统下 MongoDB安装搭建
1.下载linux的mongodb 2.在目录usr/local下创建文件夹mongodb,把安装包解压到该文件夹中 # mkdir mongodb # tar -zxvf mongodb-3.4.2 ...
- Visual Studio实用小技巧
有一个有关微软Office的笑话,说的是它的特性太多: 当你觉得自己发现了一个Office的新特性时,它已经存在很多年了. 本文将介绍一些在Visual Studio(免费下载)中很实用却被忽略的小技 ...
- VC编译选项 多线程(/MT)
VC编译选项 多线程(/MT)多线程调试(/MTd)多线程 DLL (/MD)多线程调试 DLL (/MDd)C 运行时库 库文件Single threa ...
- Java开发环境的搭建(jdk,eclipse)
一.java 开发环境的搭建 这里主要说的是在windows 环境下怎么配置环境. 1.首先安装JDK java的sdk简称JDK ,去其官方网站下载最近的JDK即可. http://www.orac ...
- instanceof 用于确定一个 PHP 变量是否属于某一类 class 的实例 , 返回true或者false
<?phpclass MyClass{} class NotMyClass{}$a = new MyClass; var_dump($a instanceof MyClass);var_dump ...
- MySQL实现根据当前ID读取上一条和下一条记录
以下为MySQL语句演示: SELECT * FROM t_news AS n ORDER BY n.`News_ID` 当前ID为4,读取上一条记录: ,; 当前ID为4,读取下一条记录: ,; 其 ...