这里用注解的形式来完成日志记录
先贴代码
@Aspect
@Component
public class LogAspect{
private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);
@Pointcut("@annotation(com.crsri.common.annotation.Log)")
public void logPointCut() {
}
@Autowired
private LogService logService;
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
//long beginTime = System.currentTimeMillis();
// 执行方法
Object result = point.proceed();
// 执行时长(毫秒)
//long time = System.currentTimeMillis() - beginTime;
//异步保存日志
saveLog(point);
return result;
}
这里定义一个方法呼应前面的方法将point传过来
void saveLog(ProceedingJoinPoint joinPoint) throws InterruptedException {
//创建对象
LogDO sysLog = new LogDO();
//获取被代理对象
BasicController basicController=(BasicController)joinPoint.getTarget();
//get方法获取operationinfo
String operationinfo = basicController.getOperationinfo();
sysLog.setOperationInfo(operationinfo);
//get方法获取operationtype
String operationtype = basicController.getOperationtype();
sysLog.setOperationType(operationtype);
//get方法获取projectID
String projectID = basicController.getProjectID();
sysLog.setProjectId(projectID);
// 将BasicController重置
basicController.setLogInfo(null, null, null);
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//Method method = signature.getMethod();
/* Log syslog = method.getAnnotation(Log.class); /
/
* if (syslog != null) { // 注解上的描述 sysLog.setOperationInfo(operationinfo); }
*/
// 请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
sysLog.setOperationFunction((className + “.” + methodName + “()”));
// 请求的参数
Object[] args = joinPoint.getArgs();
try {
String params = JSONUtils.beanToJson(args[0]).substring(0, 4999);
sysLog.setParams(params);
} catch (Exception e) {
}
/*
* String[] parameterNames = signature.getParameterNames(); for (int i = 0; i <
* parameterNames.length; i++) { String string = parameterNames[i];
* if(parameterNames[i].equals("pro")) {
* System.out.println("刘飞------------------"+args[i]); } }
*/
// 获取request
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
// 设置IP地址
sysLog.setLogIP(IPUtils.getIpAddr(request));
sysLog.setOperationAPI(HttpContextUtils.getApiUrL(request));
// 用户名
User currUser = ShiroUtil.getUser();
if (null == currUser) {
if (null != sysLog.getParams()) {
sysLog.setUserID("");
sysLog.setParams(sysLog.getParams());
}
} else {
sysLog.setUserID(ShiroUtil.getUserId());
sysLog.setUsername(ShiroUtil.getUser().getUsername());
}
// 系统当前时间
Date date = new Date();
sysLog.setOperationTime(date);
sysLog.setOperationId(UUID.randomUUID().toString());
logService.addLog(sysLog);//添加日志
}
// 请求的参数
Object[] args = joinPoint.getArgs();
try {
String params = JSONUtils.beanToJson(args[0]).substring(0, 4999);
sysLog.setParams(params);
} catch (Exception e) {
}
/*
* String[] parameterNames = signature.getParameterNames(); for (int i = 0; i <
* parameterNames.length; i++) { String string = parameterNames[i];
* if(parameterNames[i].equals(“pro”)) {
* System.out.println(“刘飞------------------”+args[i]); } }
*/
这里是将日志中参数取出来进行一个遍历
parameterNames是参数名字
args[i]是参数的值
// 获取request
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
// 设置IP地址
sysLog.setLogIP(IPUtils.getIpAddr(request));
sysLog.setOperationAPI(HttpContextUtils.getApiUrL(request));
// 用户名
User currUser = ShiroUtil.getUser();
if (null == currUser) {
if (null != sysLog.getParams()) {
sysLog.setUserID("");
sysLog.setParams(sysLog.getParams());
}
} else {
sysLog.setUserID(ShiroUtil.getUserId());
sysLog.setUsername(ShiroUtil.getUser().getUsername());
}
// 系统当前时间
Date date = new Date();
sysLog.setOperationTime(date);
sysLog.setOperationId(UUID.randomUUID().toString());
logService.addLog(sysLog);//添加日志
public class HttpContextUtils {
public static HttpServletRequest getHttpServletRequest() {
return((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
}
public static String getApiUrL(HttpServletRequest req) {
return req.getRequestURI();
}
}
这里定义一个basicController做父类供其他类继承
public class BasicController{
//登录、注销、增加、修改、删除、查询、计算、导入、导出、上传、下载、其他、锁屏
public static final String Login = “登录”;
public static final String Logout = “注销”;
public static final String Add = “增加”;
public static final String Update = “修改”;
public static final String Delete = “删除”;
public static final String Search = “查询”;
public static final String Calculate = “计算”;
public static final String Import = “导入”;
public static final String Export = “导出”;
public static final String Upload = “上传”;
public static final String Download = “下载”;
public static final String Other = “其他”;
public static final String Lock = “锁屏”;
private String operationtype;
private String operationinfo;
private String ProjectID;
public String getOperationtype() {
return operationtype;
}
public void setOperationtype(String operationtype) {
this.operationtype = operationtype;
}
public String getOperationinfo() {
return operationinfo;
}
public void setOperationinfo(String operationinfo) {
this.operationinfo = operationinfo;
}
public String getProjectID() {
return ProjectID;
}
public void setProjectID(String projectID) {
ProjectID = projectID;
}
public void setLogInfo(String operationtype,String operationinfo,String ProjectID) {
this.operationinfo = operationinfo;
this.operationtype = operationtype;
this.ProjectID=ProjectID;
}
@Override
public String toString() {
return "BasicController [operationtype=" + operationtype + ", operationinfo=" + operationinfo + ", ProjectID="
+ ProjectID + "]";
}
}
下面我们来随便用一个类下日志试试
@Controller
@RequestMapping(“user”)
public class UserController extends BasicController{
@Autowired
private UserService userService;
@Log
@RequestMapping(value="/getUser",method=RequestMethod.GET)
@ResponseBody
public ApiResponse getUser(int page,int limit ,User r){
List<User> user= userService.queryUserAndUserList(page, limit, r);
int count=userService.getCountUser(r);
setLogInfo(Search, "查询用户信息",null);
return ApiResponse.ofSuccess(user, count);
}
下面是定义的@log 注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
String value() default “”;
}