若依框架的日志注解
1.先创建日志注解(若依的日志是异步执行的)

InsertLog这个类里面写的是定义注解的参数
import java.lang.annotation.*;
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface InsertLog {
public String description() default "";
public String modulesName() default "";
public boolean isSaveRequestData() default true;
public boolean isSaveResponseData() default true;
}
InsertLogAspect 切点类,这个是核心代码,写注解的日志在运行时,抛出异常时怎么处理,参数的拼接可以自定义模块
package com.tecsun.common.log.aspect;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.tecsun.common.core.constant.ServiceNameConstants;
import com.tecsun.common.core.domain.interfaces.ExterNalInterfaceLog;
import com.tecsun.common.core.utils.ServletUtils;
import com.tecsun.common.core.utils.StringUtils;
import com.tecsun.common.core.utils.ip.IpUtils;
import com.tecsun.common.log.annotation.InsertLog;
import com.tecsun.common.log.enums.BusinessStatus;
import com.tecsun.common.log.service.AsyncLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
@Aspect
@Component
public class InsertLogAspect
{
private static final Logger logger = LoggerFactory.getLogger(InsertLogAspect.class);
@Autowired
private AsyncLogService asyncLogService;
@Pointcut("@annotation(com.tecsun.common.log.annotation.InsertLog)")
public void logPoint()
{
}
@AfterReturning(pointcut = "logPoint()", returning = "jsonResult")
public void doAfterReturning(JoinPoint joinPoint, Object jsonResult)
{
handleLog(joinPoint, null, jsonResult);
}
@AfterThrowing(value = "logPoint()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Exception e)
{
handleLog(joinPoint, e, null);
}
protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult)
{
try
{
InsertLog controllerLog = getAnnotationLog(joinPoint);
if (controllerLog == null)
{
return;
}
ExterNalInterfaceLog log = new ExterNalInterfaceLog();
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
log.setUrl(className + "." + methodName + "()");
log.setInterfaceType(ServletUtils.getRequest().getMethod());
String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
log.setRequestAddress(ip);
if(jsonResult != null){
String jsonOut = JSON.toJSONString(jsonResult);
log.setOutParams(jsonOut);
}
if (e != null)
{
log.setStatus(BusinessStatus.FAIL.ordinal());
log.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
}
getControllerMethodDescription(joinPoint, controllerLog, log);
String logJsonStr = JSON.toJSONString(log);
asyncLogService.saveCardCenterLog(logJsonStr);
}
catch (Exception exp)
{
logger.error("==前置通知异常==");
logger.error("异常信息:{}", exp.getMessage());
exp.printStackTrace();
}
}
public void getControllerMethodDescription(JoinPoint joinPoint, InsertLog log, ExterNalInterfaceLog exterNalInterfaceLog) throws Exception
{
if (log.isSaveRequestData())
{
setRequestValue(joinPoint, exterNalInterfaceLog,log.modulesName());
}
}
private void setRequestValue(JoinPoint joinPoint, ExterNalInterfaceLog exterNalInterfaceLog,String modulesName) throws Exception
{
String requestMethod = exterNalInterfaceLog.getInterfaceType();
if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod))
{
if (StringUtils.isBlank(modulesName) || modulesName.equals(ServiceNameConstants.CAR_SERVICE)){
argsArrayToString(joinPoint.getArgs(),exterNalInterfaceLog);
}
String param = JSON.toJSONString(exterNalInterfaceLog.getDataString());
exterNalInterfaceLog.setInParams(StringUtils.substring(param, 0, 2000));
}
}
private InsertLog getAnnotationLog(JoinPoint joinPoint) throws Exception
{
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null)
{
return method.getAnnotation(InsertLog.class);
}
return null;
}
private String argsArrayToString(Object[] paramsArray,ExterNalInterfaceLog exterNalInterfaceLog)
{
String params = "";
if (paramsArray != null && paramsArray.length > 0)
{
for (int i = 0; i < paramsArray.length; i++)
{
if (!isFilterObject(paramsArray[i]))
{
try
{
BeanUtils.copyProperties(paramsArray[i], exterNalInterfaceLog);
Object jsonObj = JSON.toJSON(paramsArray[i]);
params += jsonObj.toString() + " ";
getLogParams(exterNalInterfaceLog,params);
}
catch (Exception e)
{
}
}
}
}
return params.trim();
}
@SuppressWarnings("rawtypes")
public boolean isFilterObject(final Object o)
{
Class<?> clazz = o.getClass();
if (clazz.isArray())
{
return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
}
else if (Collection.class.isAssignableFrom(clazz))
{
Collection collection = (Collection) o;
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
return iter.next() instanceof MultipartFile;
}
}
else if (Map.class.isAssignableFrom(clazz))
{
Map map = (Map) o;
for (Iterator iter = map.entrySet().iterator(); iter.hasNext();)
{
Map.Entry entry = (Map.Entry) iter.next();
return entry.getValue() instanceof MultipartFile;
}
}
return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
|| o instanceof BindingResult;
}
private void getLogParams(ExterNalInterfaceLog log, String jsonObject) {
try {
JSONObject jsonInObject = JSONObject.parseObject(jsonObject);
if (jsonInObject == null) {
throw new JSONException("JSON解析失败");
}
if (jsonInObject.containsKey("name") && StringUtils.isNotBlank(jsonInObject.getString("name"))) {
log.setName(jsonInObject.getString("name"));
}
if (jsonInObject.containsKey("aac003") && StringUtils.isNotBlank(jsonInObject.getString("aac003"))) {
log.setName(jsonInObject.getString("aac003"));
}
if (jsonInObject.containsKey("idNum") && StringUtils.isNotBlank(jsonInObject.getString("idNum"))) {
log.setIdNum(jsonInObject.getString("idNum"));
}
if (jsonInObject.containsKey("aac002") && StringUtils.isNotBlank(jsonInObject.getString("aac002"))) {
log.setIdNum(jsonInObject.getString("aac002"));
}
if (jsonInObject.containsKey("aac147") && StringUtils.isNotBlank(jsonInObject.getString("aac147"))) {
log.setIdNum(jsonInObject.getString("aac147"));
}
if (jsonInObject.containsKey("mobileNum") && StringUtils.isNotBlank(jsonInObject.getString("mobileNum"))) {
log.setPhone(jsonInObject.getString("mobileNum"));
}
if (jsonInObject.containsKey("mobile") && StringUtils.isNotBlank(jsonInObject.getString("mobile"))) {
log.setPhone(jsonInObject.getString("mobile"));
}
if (jsonInObject.containsKey("AAE005") && StringUtils.isNotBlank(jsonInObject.getString("AAE005"))) {
log.setPhone(jsonInObject.getString("AAE005"));
}
} catch (JSONException e) {
e.getMessage();
e.printStackTrace();
logger.info("JSON解析失败!");
}
}
}
AsyncLogService 远程调用插入数据库的方法(异步)
package com.tecsun.common.log.service;
import com.tecsun.system.api.RemoteInterfaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.tecsun.system.api.RemoteLogService;
import com.tecsun.system.api.domain.SysOperLog;
import javax.annotation.Resource;
@Service
public class AsyncLogService
{
@Autowired
private RemoteLogService remoteLogService;
@Resource
RemoteInterfaceService remoteInterfaceService;
@Async
public void saveSysLog(SysOperLog sysOperLog)
{
remoteLogService.saveLog(sysOperLog);
}
@Async
public void saveCardCenterLog(String logJsonStr)
{
remoteInterfaceService.insertExternalInterfaceLog(logJsonStr);
}
}