add and fix

This commit is contained in:
Carol 2021-10-29 14:17:02 +08:00
parent 355d9bbd16
commit 760dcf61dc
16 changed files with 596 additions and 509 deletions

View File

@ -9,15 +9,17 @@
* [CommonUtil-sources.jar](https://github.com/carolcoral/CommonUtil/releases/download/2.0.2/CommonUtil-2.0.2-sources.jar)
## Log
> `2021年3月24日 11:24:53` fix some bugs and change mongoClient init. [Use MongoClientInit](https://github.com/carolcoral/CommonUtil/wiki/MongoClientInit).
> `2021-10-29 13:51:03` add and fix some methods.Update version to 2.1.0.
> `2021年2月9日 11:09:13` change folder and fix some bug.
> `2021-3-24 11:24:53` fix some bugs and change mongoClient init. [Use MongoClientInit](https://github.com/carolcoral/CommonUtil/wiki/MongoClientInit).
> `2020年8月20日 16:49:23` new class [MongoClientsInit](https://github.com/carolcoral/CommonUtil/blob/master/src/main/java/site/cnkj/utils/MongoClientsInit.java) for create muti mongoClient.More info to see [How to use MongoClientsInit](https://carolcoral.github.io/Article/JAVA/Java%E6%9E%84%E5%BB%BA%E5%A4%9Amongo%E6%95%B0%E6%8D%AE%E6%BA%90%E5%AE%A2%E6%88%B7%E7%AB%AF)
> `2021-2-9 11:09:13` change folder and fix some bug.
> `2020年7月21日 11:20:14` fix some expire bug from [RedisUtil](https://github.com/carolcoral/CommonUtil/blob/master/src/main/java/site/cnkj/utils/RedisUtil.java).
> `2020-8-20 16:49:23` new class [MongoClientsInit](https://github.com/carolcoral/CommonUtil/blob/master/src/main/java/site/cnkj/utils/MongoClientsInit.java) for create muti mongoClient.More info to see [How to use MongoClientsInit](https://carolcoral.github.io/Article/JAVA/Java%E6%9E%84%E5%BB%BA%E5%A4%9Amongo%E6%95%B0%E6%8D%AE%E6%BA%90%E5%AE%A2%E6%88%B7%E7%AB%AF)
> `2020年7月20日 14:17:00` New date function `String formatDateByReg(String date_format, int parseInt)` for format date by The date-format [DateUtil](https://github.com/carolcoral/CommonUtil/blob/master/src/main/java/site/cnkj/utils/DateUtil.java).For example like this:
> `2020-7-21 11:20:14` fix some expire bug from [RedisUtil](https://github.com/carolcoral/CommonUtil/blob/master/src/main/java/site/cnkj/utils/RedisUtil.java).
> `2020-7-20 14:17:00` New date function `String formatDateByReg(String date_format, int parseInt)` for format date by The date-format [DateUtil](https://github.com/carolcoral/CommonUtil/blob/master/src/main/java/site/cnkj/utils/DateUtil.java).For example like this:
```java
public static void main(String[] args) {
@ -50,7 +52,7 @@ current date_format is: YYYY-MM-dd HH:mm:ss
current format result is:2020-07-20 14:15:08
```
> `2019年12月27日 17:20:34` Demo to show how to operation Protobuf in java.[Java中使用ProtoBuf数据](https://github.com/carolcoral/CommonUtil/wiki/Java中使用ProtoBuf数据)
> `2019-12-27 17:20:34` Demo to show how to operation Protobuf in java.[Java中使用ProtoBuf数据](https://github.com/carolcoral/CommonUtil/wiki/Java中使用ProtoBuf数据)
> `2019-12-05 14:33:23` New class for remotely connect to the server and execute the script.[SSH2Util](https://github.com/carolcoral/CommonUtil/blob/master/src/main/java/site/cnkj/utils/SSH2Util.java)

View File

@ -7,7 +7,7 @@
<groupId>site.cnkj</groupId>
<artifactId>CommonUtil</artifactId>
<packaging>jar</packaging>
<version>2.0.3</version>
<version>2.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>

View File

@ -12,7 +12,7 @@ import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import site.cnkj.common.object.redis.Receiver;
import site.cnkj.common.object.Receiver;
import site.cnkj.common.utils.data.RedisUtil;
/**

View File

@ -0,0 +1,16 @@
package site.cnkj.common.object;
import lombok.Data;
import java.io.Serializable;
/**
* Created by rx on 2018/9/17.
*/
@Data
public class BaseResult implements Serializable {
private int code;
private String desc;
}

View File

@ -1,87 +0,0 @@
package site.cnkj.common.object;
import java.util.HashMap;
/*
* @author LXW
* @create 2020/4/21 11:16
* @Description 异常原因枚举值
*/
public class ReasonEnumeration {
public static HashMap<String, String> reasonEnumeration = new HashMap<>();
public static final class CODE{
public static final class Header{
public static final String IMEI = "100001";
public static final String IMSI = "100002";
public static final String IDFA = "100003";
public static final String OAID = "100004";
public static final String HWID = "100005";
public static final String UID = "100006";
}
/**
* params
*/
public static final class Params{
public static final String contentId = "200001";
public static final String marketingId = "200002";
public static final String songListId = "200003";
public static final String songId = "200004";
public static final String songName = "200005";
public static final String contentIdRange = "200006";
public static final String rateLevelRange = "200007";
public static final String isOnlineRange = "200008";
public static final String beginTime = "200009";
public static final String logId = "200010";
public static final String videoIdMvIdConcertId = "200011";
public static final String rateLevel = "200012";
public static final String vmsParamsE = "200013";
public static final String vmsParamsERange = "200014";
public static final String codeRange = "200015";
public static final String requestTimeRange = "200016";
public static final String requestTime = "200017";
public static final String resourceTypeRange = "200018";
}
/**
* RequestParams
*/
public static final class RequestParams{}
/**
* ResponseBody
*/
public static final class ResponseBody{}
}
static {
reasonEnumeration.put(CODE.Header.IMEI, "IMEI的值不符合规范数据丢弃");
reasonEnumeration.put(CODE.Header.IMSI, "IMSI的值不符合规范数据丢弃");
reasonEnumeration.put(CODE.Header.IDFA, "IDFA的值长度不符合规范数据丢弃");
reasonEnumeration.put(CODE.Header.OAID, "OAID的值不符合规范数据丢弃");
reasonEnumeration.put(CODE.Header.HWID, "HWID的值不符合规范数据丢弃");
reasonEnumeration.put(CODE.Header.UID, "UID的值等于15586008224920247234882,UID被强制转换成空值");
reasonEnumeration.put(CODE.Params.contentId, "params.contentId字段不存在或值为空数据丢弃");
reasonEnumeration.put(CODE.Params.marketingId, "params.marketingId字段不存在数据丢弃");
reasonEnumeration.put(CODE.Params.songListId, "params.songListId字段不存在设置默认值为空值");
reasonEnumeration.put(CODE.Params.songId, "params.songId字段不存在设置默认值为空值");
reasonEnumeration.put(CODE.Params.songName, "params.songName字段不存在数据丢弃");
reasonEnumeration.put(CODE.Params.contentIdRange, "params.contentId字段值不在范围内数据丢弃");
reasonEnumeration.put(CODE.Params.rateLevel, "params.rateLevel字段不存在或值为空");
reasonEnumeration.put(CODE.Params.rateLevelRange, "params.rateLevel字段不在范围内");
reasonEnumeration.put(CODE.Params.isOnlineRange, "params.isOnline字段不存在或不在范围内params.isOnline设置默认值");
reasonEnumeration.put(CODE.Params.beginTime, "params.beginTime字段不存在或值为空数据丢弃");
reasonEnumeration.put(CODE.Params.logId, "params.logId字段不存在或值为空数据丢弃");
reasonEnumeration.put(CODE.Params.videoIdMvIdConcertId, "params中不存在videoId、mvId、concertId或对应的值为空数据丢弃");
reasonEnumeration.put(CODE.Params.vmsParamsE, "params.E字段参位值数量不正确");
reasonEnumeration.put(CODE.Params.vmsParamsERange, "params.E字段参位值不在范围内");
reasonEnumeration.put(CODE.Params.codeRange, "params.code字段不存在或值为空");
reasonEnumeration.put(CODE.Params.requestTimeRange, "params.requestTime字段不符合时间戳格式");
reasonEnumeration.put(CODE.Params.requestTime, "params.requestTime字段不存在或值为空");
reasonEnumeration.put(CODE.Params.resourceTypeRange, "params.resourceType字段值不在范围内");
}
}

View File

@ -1,4 +1,4 @@
package site.cnkj.common.object.redis;
package site.cnkj.common.object;
/*
* @version 1.0 created by LXW on 2019/1/9 16:17

View File

@ -0,0 +1,27 @@
package site.cnkj.common.object;
import lombok.Data;
import lombok.EqualsAndHashCode;
import site.cnkj.common.enumeration.ResponseStatusEnum;
/*
* @version 1.0 created by LXW on 2019/7/22 11:04
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class ResponseDataResult<T> extends BaseResult {
private T data;
public ResponseDataResult(ResponseStatusEnum responseStatusEnum) {
this.setCode(responseStatusEnum.getCode());
this.setDesc(responseStatusEnum.getDesc());
}
public ResponseDataResult(T data) {
this.data = data;
}
public ResponseDataResult() {
}
}

View File

@ -1,14 +0,0 @@
package site.cnkj.common.object.servlet;
import lombok.Data;
/**
* Created by rx on 2018/9/17.
*/
@Data
public class BaseResult {
private String code;
private String desc;
}

View File

@ -1,45 +0,0 @@
package site.cnkj.common.object.servlet;
/*
* @version 1.0 created by LXW on 2019/3/12 14:17
*/
@Deprecated
public class CommonInfo {
/**
* @Desc ResponseCode for servlet request callback
* @Version delete from 0.3.5 version and replace by <url>cn.migu.log.common.object.servlet.ResponseBodyCode</url>
*/
@Deprecated
public static class ResponseCode{
public static final String SUCCESS = "000000";//成功
public static final String FAILED = "100000";//结果异常
public static final String WARNING = "200000";//警告
public static final String ERROR = "300000";//程序故障
public static final String TIMEOUT = "999999"; //登录过期
public class Desc{
public static final String SUCCESS = "SUCCESS";//成功
public static final String FAILED = "FAILED";//结果异常
public static final String WARNING = "WARNING";//警告
public static final String ERROR = "ERROR";//程序故障
public static final String NULL_URL = "请求URL不存在";
public static final String EXIST_ERROR = "该条目已存在";
public static final String NOT_EXIST_ERROR = "该条目不存在";
public static final String NOT_NUMERIC = "分隔符数量不是正整数";
public static final String OUT_RANGE_ERROR = "分隔符数量过长";
public static final String NOT_EQUAL_ERROR = "分隔符数量不一致";
public static final String NULL_PARAM = "必填字段不存在";
public static final String PARAM_ERROR = "字段值错误";
public static final String ITEM_REFERENCE = "该条目已被引用";
public static final String NOT_REFRESH_ITEM = "存在未刷新的条目";
public static final String OFFLINE_MACHINE = "机器已下线";
public static final String NOT_OFFLINE_ITEM = "该条目未下线";
public static final String RUNNING_REFRESH = "上次刷新未完成";
public static final String REFRESH_TIMEOUT = "刷新超时";
public static final String SCRIPT_ERROR = "请求脚本执行失败";
public static final String ERROR_CRON = "cron表达式错误";
}
}
}

View File

@ -1,18 +0,0 @@
package site.cnkj.common.object.servlet;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
/*
* @version 1.0 created by LXW on 2019/7/22 11:04
*/
@Data
public class DataResult extends BaseResult {
private Object data;
@Override
public String toString() {
return JSONObject.toJSONString(this);
}
}

View File

@ -1,23 +0,0 @@
package site.cnkj.common.object.servlet;
/*
* @author LXW
* @create 2021/2/8 15:04
* @Description
*/
public enum ResponseBodyCode {
SUCCESS("000000"), FAILED("100000"), WARNING("200000"), ERROR("300000");
private String code;
ResponseBodyCode(String code){
this.code = code;
}
public String getCode(){
return this.code;
}
}

View File

@ -0,0 +1,137 @@
package site.cnkj.common.utils.bean;
import org.springframework.util.ReflectionUtils;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class ReflectionUtil extends ReflectionUtils {
/**
* 类上是否包含注解
*
* @date 2021-08-10 15:30:34
* @author liuzhengyang
* @param clazz 类Class
* @param aClazz 注解Class
* @return boolean
*/
public static boolean containsAnnotation(Class<?> clazz, Class<? extends Annotation> aClazz) {
Annotation[] annotations = clazz.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation.annotationType() == aClazz) {
return true;
}
}
return false;
}
public static Type getGenericParameter(Class<?> clazz) {
while(clazz != null && !(clazz.getGenericSuperclass() instanceof ParameterizedType)) {
clazz = clazz.getSuperclass();
}
if (clazz != null) {
return ((ParameterizedType)clazz.getGenericSuperclass()).getActualTypeArguments()[0];
} else {
throw new IllegalArgumentException("Invalid argument, argument's super class must specify type parameters");
}
}
public static Class getSuperClassGenericType(final Class clazz, final int index) {
Type genType = clazz.getGenericSuperclass();
for(Class superClass = clazz; !(genType instanceof ParameterizedType); genType = superClass.getGenericSuperclass()) {
if (superClass == Object.class) {
return Object.class;
}
superClass = superClass.getSuperclass();
}
Type[] params = ((ParameterizedType)genType).getActualTypeArguments();
if (index < params.length && index >= 0) {
if (!(params[index] instanceof Class) && params[index] instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType)params[index];
return (Class)pType.getRawType();
} else {
return (Class)params[index];
}
} else {
return Object.class;
}
}
public static Class getSuperClassGenericTypeCollectionGenType(final Class clazz, final int index, final int collectionGenindex) {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
return Object.class;
} else {
Type[] params = ((ParameterizedType)genType).getActualTypeArguments();
if (index < params.length && index >= 0) {
if (!(params[index] instanceof Class) && params[index] instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType)params[index];
return (Class)pType.getActualTypeArguments()[collectionGenindex];
} else {
return (Class)params[index];
}
} else {
return Object.class;
}
}
}
public static Object newInstance(final Class clazz, final int index) {
try {
return getSuperClassGenericType(clazz, index).newInstance();
} catch (IllegalAccessException | InstantiationException var3) {
var3.printStackTrace();
}
return null;
}
public static List<Field> getAllField(Object obj) {
List<Field> fieldList = new ArrayList();
for(Class tempClass = obj.getClass(); tempClass != null; tempClass = tempClass.getSuperclass()) {
fieldList.addAll(Arrays.asList(tempClass.getDeclaredFields()));
}
return fieldList;
}
public static List<Field> getAllFieldByClazz(Class clazz) {
List<Field> fieldList = new ArrayList();
for(Class tempClass = clazz; tempClass != null; tempClass = tempClass.getSuperclass()) {
fieldList.addAll(Arrays.asList(tempClass.getDeclaredFields()));
}
return fieldList;
}
public static Field findFieldForAll(Object obj, String name) {
List<Field> fieldList = getAllField(obj);
Iterator var3 = fieldList.iterator();
Field f;
do {
if (!var3.hasNext()) {
return null;
}
f = (Field)var3.next();
} while(!f.getName().equals(name));
return f;
}
public static Object getFieldValueForAll(Object obj, String name) {
Field f = findFieldForAll(obj, name);
f.setAccessible(true);
try {
return f.get(obj);
} catch (Exception var4) {
var4.printStackTrace();
}
return null;
}
}

View File

@ -0,0 +1,167 @@
package site.cnkj.common.utils.data;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.StringJoiner;
public class GlobalId {
private static final Logger log = LoggerFactory.getLogger(GlobalId.class);
private long twepoch = 1420041600000L;
private static long workerIdBits = 5L;
private static long datacenterIdBits = 5L;
private static long maxWorkerId;
private static long maxDatacenterId;
private long sequenceBits = 12L;
private long workerIdShift;
private long datacenterIdShift;
private long timestampLeftShift;
private long sequenceMask;
private long workerId;
private long datacenterId;
private long sequence;
private long lastTimestamp;
private static GlobalId defaultGlobalId;
public GlobalId() {
this.workerIdShift = this.sequenceBits;
this.sequenceMask = ~(-1L << (int)this.sequenceBits);
this.sequence = 0L;
this.lastTimestamp = -1L;
this.workerId = 0L;
this.datacenterId = 0L;
this.build();
}
public static long getDatacenterIdByIp(String ipAddr) {
byte[] mac = (ipAddr + UUIDUtil.longUuid()).getBytes();
long id = (255L & (long)mac[mac.length - 2] | 65280L & (long)mac[mac.length - 1] << 8) >> 6;
id %= maxDatacenterId + 1L;
return id;
}
public static long getDatacenterIdByIp() {
return getDatacenterIdByIp(getIpAddress());
}
public static String getIpAddress() {
String ipAddr = "0.0.0.0";
try {
InetAddress ip = InetAddress.getLocalHost();
ipAddr = ip.getHostAddress();
} catch (Exception var2) {
log.warn("获取ip错误");
}
return ipAddr;
}
public static long getMaxWorkerId(long datacenterId) {
StringBuilder mpid = new StringBuilder();
mpid.append(datacenterId);
String mac = getMac();
mpid.append(StringUtils.isEmpty(mac) ? UUIDUtil.longUuid() : mac);
mpid.append(UUIDUtil.longUuid());
return (long)(mpid.toString().hashCode() & '\uffff') % (maxWorkerId + 1L);
}
public static String getMac() {
try {
InetAddress ip = InetAddress.getLocalHost();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
if (network == null) {
return "";
}
byte[] mac = network.getHardwareAddress();
if (null != mac) {
StringJoiner j = new StringJoiner("-");
for(int i = 0; i < mac.length; ++i) {
j.add(String.format("%02X", mac[i]));
}
return j.toString();
}
} catch (Exception var5) {
log.warn(" get Mac: " + var5.getMessage());
}
return "";
}
public GlobalId(long workerId, long datacenterId) {
this.workerIdShift = this.sequenceBits;
this.sequenceMask = ~(-1L << (int)this.sequenceBits);
this.sequence = 0L;
this.lastTimestamp = -1L;
this.build();
if (workerId <= maxWorkerId && workerId >= 0L) {
if (datacenterId <= maxDatacenterId && datacenterId >= 0L) {
this.workerId = workerId;
this.datacenterId = datacenterId;
} else {
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
} else {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
}
private void build() {
this.datacenterIdShift = this.sequenceBits + workerIdBits;
this.timestampLeftShift = this.sequenceBits + workerIdBits + datacenterIdBits;
}
public synchronized long nextId() {
long timestamp = this.timeGen();
if (timestamp < this.lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", this.lastTimestamp - timestamp));
} else {
if (this.lastTimestamp == timestamp) {
this.sequence = this.sequence + 1L & this.sequenceMask;
if (this.sequence == 0L) {
timestamp = this.tilNextMillis(this.lastTimestamp);
}
} else {
this.sequence = 0L;
}
this.lastTimestamp = timestamp;
return timestamp - this.twepoch << (int)this.timestampLeftShift | this.datacenterId << (int)this.datacenterIdShift | this.workerId << (int)this.workerIdShift | this.sequence;
}
}
protected long tilNextMillis(long lastTimestamp) {
long timestamp;
for(timestamp = this.timeGen(); timestamp <= lastTimestamp; timestamp = this.timeGen()) {
}
return timestamp;
}
protected long timeGen() {
return System.currentTimeMillis();
}
public static GlobalId initialDefault(long datacenterId, long workerId) {
defaultGlobalId = new GlobalId(workerId, datacenterId);
return defaultGlobalId;
}
public static long generateNextId() {
return defaultGlobalId.nextId();
}
static {
maxWorkerId = ~(-1L << (int)workerIdBits);
maxDatacenterId = ~(-1L << (int)datacenterIdBits);
defaultGlobalId = new GlobalId(getMaxWorkerId(getDatacenterIdByIp()), getDatacenterIdByIp());
}
}

View File

@ -0,0 +1,64 @@
package site.cnkj.common.utils.data;
import org.apache.commons.codec.binary.Base64;
public class UUIDUtil {
public UUIDUtil() {
}
public static String longUuid() {
java.util.UUID uuid = java.util.UUID.randomUUID();
return uuid.toString().replace("-", "");
}
public static String shortUuid() {
java.util.UUID uuid = java.util.UUID.randomUUID();
return compressedUUID(uuid);
}
private static String compressedUUID(java.util.UUID uuid) {
byte[] byUuid = new byte[16];
long least = uuid.getLeastSignificantBits();
long most = uuid.getMostSignificantBits();
long2bytes(most, byUuid, 0);
long2bytes(least, byUuid, 8);
String compressUUID = Base64.encodeBase64URLSafeString(byUuid);
return compressUUID;
}
private static void long2bytes(long value, byte[] bytes, int offset) {
for(int i = 7; i > -1; --i) {
bytes[offset++] = (byte)((int)(value >> 8 * i & 255L));
}
}
public static String longUuid2short(String longUuid) {
java.util.UUID uuid = java.util.UUID.fromString(longUuid);
return compressedUUID(uuid);
}
public static String shortUuid2long(String shortUuid) {
if (shortUuid.length() != 22) {
throw new IllegalArgumentException("Invalid uuid!");
} else {
byte[] byUuid = Base64.decodeBase64(shortUuid + "==");
long most = bytes2long(byUuid, 0);
long least = bytes2long(byUuid, 8);
java.util.UUID uuid = new java.util.UUID(most, least);
return uuid.toString();
}
}
private static long bytes2long(byte[] bytes, int offset) {
long value = 0L;
for(int i = 7; i > -1; --i) {
value |= (long)((bytes[offset++] & 255) << 8 * i);
}
return value;
}
}

View File

@ -5,12 +5,18 @@ import org.apache.commons.lang.StringUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
/*
* @version 1.0 created by LXW on 2018/11/8 16:11
*/
public final class DateUtil {
public class DateUtil {
public static enum FORMAT_ENUM{
BASETIME_yyyy("yyyy"),

View File

@ -1,400 +1,255 @@
package site.cnkj.common.utils.logger;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.slf4j.MDC;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import site.cnkj.common.object.ReasonEnumeration;
import site.cnkj.common.utils.bean.ReflectionUtil;
import site.cnkj.common.utils.data.GlobalId;
import site.cnkj.common.utils.date.DateUtil;
import site.cnkj.common.utils.http.HttpCommonUtil;
import site.cnkj.common.utils.io.StringUtil;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Map;
/*
* @version 1.0 created by LXW on 2019/4/1 9:13
*/
@Deprecated
@Component
public class LoggerUtil {
@Value("${spring.application.name}")
private String serviceName;//服务名
private static final Logger log = LoggerFactory.getLogger(LoggerUtil.class);
private static final Logger LOGGER = LoggerFactory.getLogger(LoggerUtil.class);
enum Level{
INFO("INFO"),
WARN("WARN"),
ERROR("ERROR"),
DEBUG("DEBUG");
public static class Level{
public static final String INFO = "INFO";
public static final String WARN = "WARN";
public static final String ERROR = "ERROR";
public static final String DEBUG = "DEBUG";
private final String value;
Level(String value){
this.value = value;
}
}
public static class Status{
public static final String SUCCESS = "000000";//成功
private static final String HOST_NAME = getHostName();
public static final String FAILED = "100000";//执行失败
public static final String FAILED_INSERTMD5 = "100001";//插入流水号失败
public static final String FAILED_VERIFYSEPARATOR = "100002";//校验分隔符数量失败
public static final String FAILED_INCLUDDIRTYDATA = "100003";//校验脏数据失败
public static final String FAILED_ANALYZESOURCE = "100004";//校验数据失败
public static final String ERROR = "200000";//错误
public static final String DEBUG = "300000";//调试开发
public static final String WARN = "400000";//警告
public static final String WARN_SOURCE = "400001";//警告,针对异常数据情况
}
public static class Type{
public static final String ERROR_MESSAGE = "error_message";
public static final String SCHEDULE = "schedule";
public static final String BUSINESS = "business";
private static String getHostName(){
InetAddress address = null;
try {
address = InetAddress.getLocalHost();
return address.getHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return null;
}
/**
* 数据处理方式枚举值
* 格式化Exception为String
* @param e Exception
* @return e.toString
*/
public static class HandleEnumeration{
public static final String discard = "0";//丢弃
public static final String replicate = "1";//复制
private static String formatException(Exception e){
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw, true));
String str = sw.toString();
return StringEscapeUtils.escapeJava(str);
}
@Data
public static class MonitorEntity {
private String hostName = HttpCommonUtil.getLocalHostName();//机器名
private String timestamp = DateUtil.translateTimeToDate(DateUtil.getCurrentTime(), DateUtil.FORMAT_ENUM.FULLTIMEBY_yMdHmsS.getValue());//时间
private String time = DateUtil.translateTimeToDate(DateUtil.getCurrentTime(), DateUtil.FORMAT_ENUM.FULLTIMEBY_yMdHmsS.getValue());//时间
private static class LoggerEntity {
private String traceId = getMDC();
private String requestId = MDC.get("requestId");
private String hostName = HOST_NAME;//机器名
private String time = DateUtil.translateDateToString(new Date(), DateUtil.FORMAT_ENUM.FULLTIMEBY_yMdHmsS.getValue());//时间
private Long timestamp = new Date().getTime();
private String className = new Throwable().getStackTrace()[4].getClassName();
private String methodName = new Throwable().getStackTrace()[4].getMethodName();
private String level;//级别
@Nullable private String status;//状态枚举值
@Nullable private String type;//类型
@Nullable private String info;//信息
@Nullable private String logName;//标识
@Nullable private String topicName;//topic名
@Nullable private String stackTrace;//异常信息如果没有则为NULL
@Nullable private String filterName;//数据特殊处理条件名称
@Nullable private String prefix;//数据模版前缀
@Nullable private String source;//原始数据
@Nullable private String message;//解析处理后的数据
@Nullable private String templateName;//模版名称
@Nullable private String serviceName;//服务名
@Nullable private String handleEnumeration;//枚举值0 剪切/1 复制
@Nullable private String reasonEnumeration;//异常原因枚举值
@Nullable private String separatorNum;//分隔符数量
@Nullable private String exceptionKeyWordName;//异常字段名字
@Nullable private String exceptionKeyWordValue;//异常字段值
@Nullable private String exceptionKeyWordTemplateArea;//异常字段在模版中的位数
private void setReasonEnumeration(String reasonEnumeration) {
this.reasonEnumeration = reasonEnumeration;
this.info = ReasonEnumeration.reasonEnumeration.get(getReasonEnumeration());
}
@Override
public String toString() {
return JSONObject.toJSONString(this);
return JSON.toJSONString(this);
}
}
private static final String TRACE_ID = "TraceID";
/**
* 处理异常数据情况的告警
* @param logName id或uri标识
* @param topic topic名字
* @param filterName 过滤条件名字
* @param prefix 模版前缀
* @param source 原始数据
* @param message 解析后数据
* @param templateName 模版名称
* @param handleEnumeration 数据处理枚举值
* @param reasonEnumeration 异常原因枚举值
* @param exceptionKeyWordName 异常字段名字 同一个字段上可能存在多个名字"|"拼接 params.videoId|params.mvId|params.concertId
* @param exceptionKeyWordValue 异常字段名字 同一个字段上可能存在多个名字"|"拼接 params.videoId|params.mvId|params.concertId
* @param exceptionKeyWordTemplateArea 异常字段在模版中的位数
*/
public static void monitor(String logName,
String topic,
String filterName,
String prefix,
String source,
String message,
String templateName,
String handleEnumeration,
String reasonEnumeration,
String separatorNum,
String exceptionKeyWordName,
String exceptionKeyWordValue,
String exceptionKeyWordTemplateArea){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.WARN);
monitorEntity.setStatus(Status.WARN_SOURCE);
monitorEntity.setType(Type.BUSINESS);
monitorEntity.setLogName(logName);
monitorEntity.setTopicName(topic);
monitorEntity.setFilterName(filterName);
monitorEntity.setPrefix(prefix);
monitorEntity.setSource(source);
monitorEntity.setMessage(message);
monitorEntity.setTemplateName(templateName);
monitorEntity.setHandleEnumeration(handleEnumeration);
monitorEntity.setReasonEnumeration(reasonEnumeration);
monitorEntity.setSeparatorNum(separatorNum);
monitorEntity.setExceptionKeyWordName(exceptionKeyWordName);
monitorEntity.setExceptionKeyWordValue(exceptionKeyWordValue);
monitorEntity.setExceptionKeyWordTemplateArea(exceptionKeyWordTemplateArea);
LOGGER.warn(monitorEntity.toString());
static String getMDC(){
if (StringUtils.isEmpty(MDC.get(TRACE_ID))){
String traceID = "TraceID: " + GlobalId.generateNextId();
MDC.put(TRACE_ID, traceID);
}
return MDC.get(TRACE_ID).split(":")[1].trim();
}
public static void message(String level, String info, String status, String type, String logName, String topicName, Exception e, String id, String uri, String filterName, String prefix, String source, String message, String templateName){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(level);
monitorEntity.setInfo(info);
monitorEntity.setStatus(status);
monitorEntity.setType(type);
monitorEntity.setLogName(logName);
monitorEntity.setTopicName(topicName);
monitorEntity.setStackTrace(StringUtil.formatException(e));
monitorEntity.setFilterName(filterName);
monitorEntity.setPrefix(prefix);
monitorEntity.setSource(source);
monitorEntity.setMessage(message);
monitorEntity.setTemplateName(templateName);
if ((Level.ERROR).equals(level)){
LOGGER.error(monitorEntity.toString());
}else if ((Level.INFO).equals(level)){
LOGGER.info(monitorEntity.toString());
}else if ((Level.WARN).equals(level)){
LOGGER.warn(monitorEntity.toString());
}else if ((Level.DEBUG).equals(level)){
LOGGER.debug(monitorEntity.toString());
static void checkFields(Map<String, Object> fields){
for (Field field : ReflectionUtil.getAllFieldByClazz(LoggerEntity.class)) {
if (field.isSynthetic()){
continue;
}
if (fields.containsKey(field.getName())){
throw new IllegalArgumentException("current field can not be use as key: " + field.getName());
}
}
}
public static void message(MonitorEntity monitorEntity){
String level = monitorEntity.getLevel();
switch(level){
case Level.DEBUG:
LOGGER.debug(monitorEntity.toString());
case Level.ERROR:
LOGGER.error(monitorEntity.toString());
case Level.WARN:
LOGGER.warn(monitorEntity.toString());
default:
LOGGER.info(monitorEntity.toString());
private static void logger(Level level, String source){
if (Level.INFO.value.equals(level.value)){
log.info(source);
}else if (Level.WARN.value.equals(level.value)){
log.warn(source);
}else if (Level.ERROR.value.equals(level.value)){
log.error(source);
}else if (Level.DEBUG.value.equals(level.value)){
log.debug(source);
}
}
public static void warn(MonitorEntity monitorEntity){
monitorEntity.setLevel(Level.WARN);
monitorEntity.setStatus(Status.WARN);
LOGGER.warn(monitorEntity.toString());
private static void message(Level level, String message){
LoggerEntity loggerEntity = new LoggerEntity();
loggerEntity.setLevel(level.value);
loggerEntity.setInfo(message);
logger(level, loggerEntity.toString());
}
public static void warn(String info, String type, String logName, String topicName){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.WARN);
monitorEntity.setInfo(info);
monitorEntity.setStatus(Status.WARN);
monitorEntity.setType(type);
monitorEntity.setLogName(logName);
monitorEntity.setTopicName(topicName);
LOGGER.warn(monitorEntity.toString());
private static void map(Level level, String message, Map<String, Object> fields){
checkFields(fields);
LoggerEntity loggerEntity = new LoggerEntity();
loggerEntity.setLevel(level.value);
loggerEntity.setInfo(message);
JSONObject jsonSource = JSON.parseObject(loggerEntity.toString());
for (Map.Entry<String, Object> entry : fields.entrySet()) {
jsonSource.put(entry.getKey(), entry.getValue());
}
logger(level, JSON.toJSONString(jsonSource));
}
public static void warn(String info, String type, String logName){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.WARN);
monitorEntity.setInfo(info);
monitorEntity.setStatus(Status.WARN);
monitorEntity.setType(type);
monitorEntity.setLogName(logName);
LOGGER.warn(monitorEntity.toString());
private static void throwable(Level level, String message, Throwable throwable){
LoggerEntity loggerEntity = new LoggerEntity();
loggerEntity.setLevel(level.value);
loggerEntity.setInfo(message);
loggerEntity.setStackTrace(throwable.getMessage());
logger(level, loggerEntity.toString());
}
public static void warn(String info, String type){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.WARN);
monitorEntity.setInfo(info);
monitorEntity.setStatus(Status.WARN);
monitorEntity.setType(type);
LOGGER.warn(monitorEntity.toString());
private static void exception(Level level, String message, Exception e){
LoggerEntity loggerEntity = new LoggerEntity();
loggerEntity.setLevel(level.value);
loggerEntity.setInfo(message);
loggerEntity.setStackTrace(formatException(e));
logger(level, loggerEntity.toString());
}
public static void warn(String info){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.WARN);
monitorEntity.setInfo(info);
monitorEntity.setStatus(Status.WARN);
monitorEntity.setType(Type.BUSINESS);
LOGGER.warn(monitorEntity.toString());
private static void mapThrowable(Level level, String message, Map<String, Object> fields, Throwable throwable){
checkFields(fields);
LoggerEntity loggerEntity = new LoggerEntity();
loggerEntity.setLevel(level.value);
loggerEntity.setInfo(message);
loggerEntity.setStackTrace(throwable.getMessage());
JSONObject jsonSource = JSON.parseObject(loggerEntity.toString());
for (Map.Entry<String, Object> entry : fields.entrySet()) {
jsonSource.put(entry.getKey(), entry.getValue());
}
logger(level, JSON.toJSONString(jsonSource));
}
public static void error(MonitorEntity monitorEntity){
monitorEntity.setLevel(Level.ERROR);
monitorEntity.setType(Type.ERROR_MESSAGE);
LOGGER.error(monitorEntity.toString());
private static void mapException(Level level, String message, Map<String, Object> fields, Exception e){
checkFields(fields);
LoggerEntity loggerEntity = new LoggerEntity();
loggerEntity.setLevel(level.value);
loggerEntity.setInfo(message);
loggerEntity.setStackTrace(formatException(e));
JSONObject jsonSource = JSON.parseObject(loggerEntity.toString());
for (Map.Entry<String, Object> entry : fields.entrySet()) {
jsonSource.put(entry.getKey(), entry.getValue());
}
logger(level, JSON.toJSONString(jsonSource));
}
public static void error(String info, String status, String logName, String topicName){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.ERROR);
monitorEntity.setInfo(info);
monitorEntity.setStatus(status);
monitorEntity.setType(Type.ERROR_MESSAGE);
monitorEntity.setLogName(logName);
monitorEntity.setTopicName(topicName);
LOGGER.error(monitorEntity.toString());
public static void info(String message){
message(Level.INFO, message);
}
public static void error(String info){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.ERROR);
monitorEntity.setInfo(info);
monitorEntity.setStatus(Status.ERROR);
monitorEntity.setType(Type.ERROR_MESSAGE);
LOGGER.error(monitorEntity.toString());
public static void info(String message, Map<String, Object> fields){
map(Level.INFO, message, fields);
}
public static void error(String info, Exception e, String status, String logName, String topicName){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.ERROR);
monitorEntity.setInfo(info);
monitorEntity.setStatus(status);
monitorEntity.setType(Type.ERROR_MESSAGE);
monitorEntity.setLogName(logName);
monitorEntity.setTopicName(topicName);
monitorEntity.setStackTrace(StringUtil.formatException(e));
LOGGER.error(monitorEntity.toString());
public static void info(String message, Throwable throwable){
throwable(Level.INFO, message, throwable);
}
public static void error(String info, Exception e, String logName, String topicName){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.ERROR);
monitorEntity.setInfo(info);
monitorEntity.setStatus(Status.ERROR);
monitorEntity.setType(Type.ERROR_MESSAGE);
monitorEntity.setLogName(logName);
monitorEntity.setTopicName(topicName);
monitorEntity.setStackTrace(StringUtil.formatException(e));
LOGGER.error(monitorEntity.toString());
public static void info(String message, Exception e){
exception(Level.INFO, message, e);
}
public static void error(String info, Exception e, String status){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.ERROR);
monitorEntity.setInfo(info);
monitorEntity.setStatus(status);
monitorEntity.setType(Type.ERROR_MESSAGE);
monitorEntity.setStackTrace(StringUtil.formatException(e));
LOGGER.error(monitorEntity.toString());
public static void info(String message, Map<String, Object> fields, Throwable throwable){
mapThrowable(Level.INFO, message, fields, throwable);
}
public static void error(String info, Exception e){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.ERROR);
monitorEntity.setInfo(info);
monitorEntity.setStatus(Status.ERROR);
monitorEntity.setType(Type.ERROR_MESSAGE);
monitorEntity.setStackTrace(StringUtil.formatException(e));
LOGGER.error(monitorEntity.toString());
public static void info(String message, Map<String, Object> fields, Exception e){
mapException(Level.INFO, message, fields, e);
}
public static void error(String info, Exception e, String source, String result, String topic, String logName){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.ERROR);
monitorEntity.setInfo(info);
monitorEntity.setStatus(Status.ERROR);
monitorEntity.setType(Type.ERROR_MESSAGE);
monitorEntity.setStackTrace(StringUtil.formatException(e));
monitorEntity.setLogName(logName);
monitorEntity.setMessage(result);
monitorEntity.setSource(source);
monitorEntity.setTopicName(topic);
LOGGER.error(monitorEntity.toString());
public static void warn(String message){
message(Level.WARN, message);
}
public static void error(String info, String status){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.ERROR);
monitorEntity.setInfo(info);
monitorEntity.setStatus(status);
monitorEntity.setType(Type.ERROR_MESSAGE);
LOGGER.error(monitorEntity.toString());
public static void warn(String message, Map<String, Object> fields){
fields.remove("data");
map(Level.WARN, message, fields);
}
public static void info(MonitorEntity monitorEntity){
monitorEntity.setLevel(Level.INFO);
monitorEntity.setStatus(Status.SUCCESS);
monitorEntity.setType(Type.BUSINESS);
LOGGER.info(monitorEntity.toString());
public static void warn(String message, Throwable throwable){
throwable(Level.WARN, message, throwable);
}
public static void info(String info, String logName, String topicName){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.INFO);
monitorEntity.setInfo(info);
monitorEntity.setStatus(Status.SUCCESS);
monitorEntity.setType(Type.BUSINESS);
monitorEntity.setLogName(logName);
monitorEntity.setTopicName(topicName);
LOGGER.info(monitorEntity.toString());
public static void warn(String message, Exception e){
exception(Level.WARN, message, e);
}
public static void info(String info, String logName){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.INFO);
monitorEntity.setInfo(info);
monitorEntity.setStatus(Status.SUCCESS);
monitorEntity.setType(Type.BUSINESS);
monitorEntity.setLogName(logName);
LOGGER.info(monitorEntity.toString());
public static void warn(String message, Map<String, Object> fields, Throwable throwable){
mapThrowable(Level.WARN, message, fields, throwable);
}
public static void info(String info){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.INFO);
monitorEntity.setInfo(info);
monitorEntity.setStatus(Status.SUCCESS);
monitorEntity.setType(Type.BUSINESS);
LOGGER.info(monitorEntity.toString());
public static void warn(String message, Map<String, Object> fields, Exception e){
mapException(Level.WARN, message, fields, e);
}
public static void debug(String info, String status, String logName, String topicName){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.DEBUG);
monitorEntity.setInfo(info);
monitorEntity.setStatus(status);
monitorEntity.setType(Type.BUSINESS);
monitorEntity.setLogName(logName);
monitorEntity.setTopicName(topicName);
LOGGER.debug(monitorEntity.toString());
public static void error(String message){
message(Level.ERROR, message);
}
public static void debug(String info, String status, String logName){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.DEBUG);
monitorEntity.setInfo(info);
monitorEntity.setStatus(status);
monitorEntity.setType(Type.BUSINESS);
monitorEntity.setLogName(logName);
LOGGER.debug(monitorEntity.toString());
public static void error(String message, Map<String, Object> fields){
map(Level.ERROR, message, fields);
}
public static void debug(String info, String status){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.DEBUG);
monitorEntity.setInfo(info);
monitorEntity.setStatus(status);
monitorEntity.setType(Type.BUSINESS);
LOGGER.debug(monitorEntity.toString());
public static void error(String message, Throwable throwable){
throwable(Level.ERROR, message, throwable);
}
public static void debug(String info){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.DEBUG);
monitorEntity.setInfo(info);
monitorEntity.setType(Type.BUSINESS);
LOGGER.debug(monitorEntity.toString());
public static void error(String message, Exception e){
exception(Level.ERROR, message, e);
}
public static void error(String message, Map<String, Object> fields, Throwable throwable){
mapThrowable(Level.ERROR, message, fields, throwable);
}
public static void error(String message, Map<String, Object> fields, Exception e){
mapException(Level.ERROR, message, fields, e);
}
}