JAva実装ログ操作記録
9240 ワード
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;
@Aspect
@Component
@Slf4j
@Order(1)
public class ThirdApiRequestLogAspect {
ObjectMapper objectMapper = new ObjectMapper();
@Resource
private CrmOperationLogMapper operationLogMapper;
public ThirdApiRequestLogAspect() {
log.info(" ...");
}
@Pointcut("execution(public * com.arvato.service.goods.api.controller.*.*(..))")
public void controllerInteceptor() {
}
@Around("controllerInteceptor()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Date start = new Date();
try {
//
CrmOperationLog sysLog = new CrmOperationLog();
SysLog syslog1 = method.getAnnotation(SysLog.class);
if (syslog1 != null) {
//
sysLog.setModule(syslog1.MODULE());
sysLog.setMethod(syslog1.REMARK());
}
//
String clazzName = joinPoint.getTarget().getClass().getName();
Class> clazz = Class.forName(clazzName);
String clazzSimpleName = clazz.getSimpleName();
String methodName = signature.getName();
sysLog.setOperationDesc(clazzSimpleName + "." + methodName);
//
String[] parameterNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
StringBuilder sb = null;
if (Objects.nonNull(parameterNames)) {
sb = new StringBuilder();
for (int i = 0; i < parameterNames.length; i++) {
Object param = joinPoint.getArgs()[i] != null ? joinPoint.getArgs()[i] : "";
if (StringUtils.isNotEmpty(param.toString()) && !"request".equals(parameterNames[i]) && !"response".equals(parameterNames[i])
&& !"modelMap".equals(parameterNames[i])) {
if (param instanceof Integer) {
sb.append(parameterNames[i] + ":" + param + "; ");
} else if (param instanceof String) {
sb.append(parameterNames[i] + ":" + param + "; ");
} else if (param instanceof Double) {
sb.append(parameterNames[i] + ":" + param + "; ");
} else if (param instanceof Float) {
sb.append(parameterNames[i] + ":" + param + "; ");
} else if (param instanceof Long) {
sb.append(parameterNames[i] + ":" + param + "; ");
} else if (param instanceof Boolean) {
sb.append(parameterNames[i] + ":" + param + "; ");
} else if (param instanceof Date) {
sb.append(parameterNames[i] + ":" + param + "; ");
} else if (param instanceof Timestamp) {
sb.append(parameterNames[i] + ":" + param + "; ");
} else {
sb.append(parameterNames[i] + ":" + getString(param) + "; ");
}
}
}
}
sb = sb == null ? new StringBuilder() : sb;
sysLog.setParams(sb.toString());
// IP
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
sysLog.setIp(IpAddressUtil.getIpAddr(request));
sysLog.setUserName(this.getDecodeUserName(request));
sysLog.setCreateTime(new Date());
log.debug("interface request startTime " + start.getTime());
Object o = joinPoint.proceed();
String response = objectMapper.writeValueAsString(o);
sysLog.setTimeMin(System.currentTimeMillis() - start.getTime());
log.debug(getString(sysLog));
//
operationLogMapper.insert(sysLog);
return o;
} catch (Exception ex) {
log.error(" "+ex.getMessage());
}
return null;
}
public static String getDecodeUserName(HttpServletRequest request) {
String userName = request.getHeader("currentUserName");
if(org.apache.commons.lang3.StringUtils.isNotEmpty(userName)) {
try {
userName = URLDecoder.decode(userName, "utf-8");
} catch (UnsupportedEncodingException var3) {
log.error(var3.getMessage(), var3);
}
}
return userName;
}
public static String getString(Object o) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
StringBuffer sb = new StringBuffer();
sb.append("entity[");
Field[] farr = o.getClass().getDeclaredFields();
for (Field field : farr) {
try {
field.setAccessible(true);
if (!ValidatorUtils.empty(field.get(o))) {
sb.append(field.getName());
sb.append("=");
if (field.get(o) instanceof Date) {
//
sb.append(sdf.format(field.get(o)));
} else {
sb.append(field.get(o));
}
sb.append("|");
}
} catch (Exception e) {
e.printStackTrace();
}
}
sb.append("]");
return sb.toString();
}
}
ユーザIPの取得
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* IP
* @author yang.liu
*/
public class IpAddressUtil {
public static String getIpAddr(HttpServletRequest request){
String ipAddress = request.getHeader("x-forwarded-for");
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
// IP
InetAddress inet=null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress= inet.getHostAddress();
}
}
// , IP IP, IP ','
if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
if(ipAddress.indexOf(",")>0){
ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
}
}
return ipAddress;
}
}
システムログ注記
import java.lang.annotation.*;
/**
*
*
* @author lipengjun
* @email [email protected]
* @date 2017 3 8 10:19:56
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
String MODULE() default " ";
String REMARK() default " ";
}
メソッドでカスタム注釈を使用して識別
@SysLog(MODULE = " ", REMARK = " ")