需要有一个日志表,然后完成日志表的CRUD
@Target(
{
ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log
{
/** 要执行的操作类型比如:add操作 **/
public String operationType() default "";
/** 要执行的具体操作比如:添加用户 **/
public String operationName() default "";
}
其实只需要一个参数就够了。如果有需要可以吧第一个参数修改为操作等级之类的。第二个参数是操作描述。
搞个拦截器 拦截所有通过控制层的请求。
/**
* @author
* @E-mail: email
* @version 创建时间:
* @desc 切点类
*/
@Aspect
@Component
public class LogInterceptor extends BaseController
{
// 注入Service用于把日志保存数据库
@Resource // 这里我用resource注解,一般用的是@Autowired
private IUsersService usersService;
private static final Logger logger = LoggerFactory.getLogger(LogInterceptor.class);
// Controller层切点
@Pointcut("execution (* com.xxxxx.xxxxxx.back.controller.*Controller.*(..))")
public void controllerAspect()
{
}
/*@Before("controllerAspect()")
public void doBefore(JoinPoint joinPoint)
{
//System.out.println("==========执行controller前置通知===============");
if(logger.isInfoEnabled())
{
logger.info("before " + joinPoint);
}
}*/
/**
* 后置通知 用于拦截Controller层记录用户的操作
*
* @param joinPoint 切点
*/
@After("controllerAspect()")
public void after(JoinPoint joinPoint)
{
// 读取session中的用户
// User user = (User) session.getAttribute("user");
// 请求的IP
// String ip = request.getRemoteAddr();
HttpServletRequest request = null ;
try
{
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
String operationType = null;
//String operationName = null;
for (Method method : methods)
{
if (method.getName().equals(methodName))
{
Class[] clazzs = method.getParameterTypes();
if (clazzs.length == arguments.length)
{
if (method.getAnnotation(Log.class)!=null)
{
operationType = method.getAnnotation(Log.class).operationType();
}
//operationName = method.getAnnotation(Log.class).operationName();
break;
}
}
}
/*==确定request的值===*/
for (int i = 0; i < arguments.length; i++)
{
Object obj = arguments[i];
if(obj instanceof HttpServletRequest)
{
request = (HttpServletRequest) obj ;
break;
}
}
// *========控制台输出=========*//
/*System.out.println("=====controller后置通知开始=====");
System.out.println("请求方法:"
+ (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")
+ "." + operationType);
System.out.println("方法描述:" + operationName);*/
/*System.out.println("请求人:" + user.getName());
System.out.println("请求IP:" + ip);*/
// *========数据库日志=========*//
AAdminsLog log = new AAdminsLog();
log.setDescription(operationType);
log.setContent(operationType);
log.setMethod(joinPoint.getTarget().getClass().getName());
log.setLogType(AdminsLogEnum.LOGTYPE_COM.getStatus());
//log.setCreateBy(user.getName());
if(request != null)
{
String params = request.getQueryString();
if (params!=null&¶ms.length()>=250)
{
params = params.substring(0, 250);
}
log.setParams(params);
log.setIp(this.getIpAddress(request));
HttpSession session = request.getSession() ;
AAdmins adminsJSON = (AAdmins) session.getAttribute("admins");
if (adminsJSON!=null)
{
log.setAdminsId(adminsJSON.getId());
log.setName(adminsJSON.getName());
}
}
log.setCreateTime(new Date());
log.setUpdateTime(new Date());
// 保存数据库
if (operationType!=null)
{
this.usersService.saveOneAdminsLogService(log);
}
//System.out.println("=====controller后置通知结束=====");
} catch (Exception e)
{
e.printStackTrace();
// 记录本地异常日志
logger.error("==后置通知异常==");
logger.error("异常信息:{}", e.getMessage());
}
}
/**
* 异常通知 用于拦截记录异常日志
*
* @param joinPoint
* @param e
*/
@AfterThrowing(pointcut = "controllerAspect()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Throwable e)
{
/*
* HttpServletRequest request = ((ServletRequestAttributes)
* RequestContextHolder.getRequestAttributes()).getRequest(); HttpSession
* session = request.getSession(); //读取session中的用户 User user = (User)
* session.getAttribute(WebConstants.CURRENT_USER); //获取请求ip String ip =
* request.getRemoteAddr();
*/
// 获取用户请求方法的参数并序列化为JSON格式字符串
HttpServletRequest request = null ;
try
{
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
String operationType = "";
String operationName = "";
for (Method method : methods)
{
if (method.getName().equals(methodName))
{
Class[] clazzs = method.getParameterTypes();
if (clazzs.length == arguments.length)
{
operationType = method.getAnnotation(Log.class).operationType();
operationName = method.getAnnotation(Log.class).operationName();
break;
}
}
}
/*==确定request的值===*/
for (int i = 0; i < arguments.length; i++)
{
Object obj = arguments[i];
if(obj instanceof HttpServletRequest)
{
request = (HttpServletRequest) obj ;
break;
}
}
/* ========控制台输出========= */
/*System.out.println("=====异常通知开始=====");
System.out.println("异常代码:" + e.getClass().getName());
System.out.println("异常信息:" + e.getMessage());
System.out.println("异常方法:"
+ (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")
+ "." + operationType);
System.out.println("方法描述:" + operationName);*/
//System.out.println("请求人:" + user.getName());
//System.out.println("请求IP:" + ip);
//System.out.println("请求参数:" + params);
// *========数据库日志=========*//
AAdminsLog log = new AAdminsLog();
log.setDescription(operationType);
log.setMethod((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")
+ "." + operationType);
log.setLogType(AdminsLogEnum.LOGTYPE_SER.getStatus());
log.setExceptioncode(null);
log.setExceptionDetail(null);
log.setExceptioncode(e.getClass().getName());
log.setExceptionDetail(e.getMessage());
if(request != null)
{
log.setParams(request.getQueryString());
log.setIp(this.getIpAddress(request));
HttpSession session = request.getSession() ;
JSONObject adminsJSON = (JSONObject) session.getAttribute("adminsSess");
log.setAdminsId(adminsJSON.getIntValue("id"));
}
log.setCreateTime(new Date());
log.setUpdateTime(new Date());
// 保存数据库
this.usersService.saveOneAdminsLogService(log);
/*System.out.println("=====异常通知结束=====");*/
} catch (Exception ex)
{
// 记录本地异常日志
logger.error("==异常通知异常==");
logger.error("异常信息:{}", ex.getMessage());
}
/* ==========记录本地异常日志========== */
logger.error("异常方法:{}异常代码:{}异常信息:{}参数:{}",
joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(),e.getMessage());
}
}