凯发娱发k8

spring aop实现拦截接口请求打印日志 -凯发娱发k8

2023-08-17,,

在spring配置

1编写自己的注解类

2.编写注解解析类

3.配置spring aop代理 (下面我使用注解 如使用配置 配置切点即可,有两种代理默认jdk代理 设置true 为cglib代理)

//注解类

 /**
* 自定义注解 器
* @author
* 给需要监控的方法加上改注解,就可以实现该方法的日志记录
*/
@target({ elementtype.parameter, elementtype.method })
@retention(retentionpolicy.runtime)
@documented
public @interface wbmsservice{
//描述
string description() default "";
//操作类型 同步:sync 异步 async
string opratetype() default "";
//客户名称
string clientname() default "";
} 使用方法 在被调用的方法实现类上添加该注解 @wbmsservice(description = "客户欠款查询", opratetype = "sync", clientname = "")
@aspect
@component
public class interfacerecord { // logservice
private ibizlogrecordservice bizlogrecordservice; // 初始化日志类
private static final log logger = logfactory.getlog(interfacerecord.class); // service层切点
@pointcut("@annotation(com.deppon.dpap.module.common.server.aop.wbmsservice)")
public void serviceaspect() {
} @before(value = "serviceaspect()")
public void dobefore(joinpoint joinpoint) {
string now = dateutil.gettoday();
logger.info("接口拦截开始时间:" now);
} @afterreturning(value = "serviceaspect()", argnames = "retval", returning = "retval")
public void doafterreturning(joinpoint joinpoint, object retval) {
string now = dateutil.gettoday();
logger.info("接口拦截结束时间:" now);
wbmslogentity log = new wbmslogentity();
try {
// 补充数据
log = supplemententity(log, joinpoint);
// 返回参数
string responsestr = "";
if (retval != null) {
responsestr = json.tojsonstring(retval);
}
// 响应内容
log.setresponscontent(responsestr);
// 成功状态
log.setissuccess(constant.yes);
// 保存到数据库
bizlogrecordservice.savewbmslog(log);
} catch (exception e) {
logger.error("==异常通知异常==");
logger.error("异常信息:{}", e);
}
} /**
* @title: doafterthrowing
* @description: todo 异常统一处理
* @param tags
* @return return_type
* @throws
*/
@afterthrowing(pointcut = "serviceaspect()", throwing = "e")
public void doafterthrowing(joinpoint joinpoint, throwable e) {
string now = dateutil.gettoday();
logger.error("接口异常拦截时间:" now);
logger.error("接口异常信息:" e);
wbmslogentity log = new wbmslogentity();
try {
// 补充数据
log = supplemententity(log, joinpoint);
// 异常状态
log.setissuccess(constant.no);
string responsestr = "";
if (e != null) {
responsestr = json.tojsonstring(e);
}
// 响应信息
log.setresponscontent(responsestr);
// 保存到数据库
bizlogrecordservice.savewbmslog(log);
} catch (exception ee) {
logger.error("==异常通知异常==");
logger.error("异常信息:{}", ee);
}
} /**
* @title: supplemententity
* @description: todo 填充数据
* @param tags
* @return return_type
* @throws
*/
private wbmslogentity supplemententity(wbmslogentity log,
joinpoint joinpoint) {
try {
httpservletrequest request = ((servletrequestattributes) requestcontextholder
.getrequestattributes()).getrequest();
// 请求的ip
string ip = request.getremoteaddr();
// 客户端ip
log.setclientip(ip);
} catch (exception ee) {
// todo: handle exception
logger.error("获取不到httprequest:" ee);
}
// 注解
map annos = getservicemthodannotatin(joinpoint);
// 客户名称
log.setclientname(annos.get("clientname"));
// 创建时间
log.setcreatetime(new date());
// 操作功能
string requestmethod = joinpoint.gettarget().getclass().getname() "."
joinpoint.getsignature().getname() "()";
logger.info("请求方法:" requestmethod);
log.setopratemethod(requestmethod);
// 操作时间
log.setopratetime(new date());
// 操作类型
log.setopratetype(annos.get("opratetype"));
// 操作描述
log.setopratedes(annos.get("description"));
// 请求参数
stringbuffer requeststr = new stringbuffer();
jsonarray jay = new jsonarray();
// 获取请求参数
if (joinpoint.getargs() != null && joinpoint.getargs().length > 0) {
for (int i = 0; i < joinpoint.getargs().length; i ) {
if (i != joinpoint.getargs().length - 1) {
requeststr.append(json.tojsonstring(joinpoint.getargs()[i]));
requeststr.append(",");
} else {
requeststr.append(json.tojsonstring(joinpoint.getargs()[i]));
}
}
}
string arraystr = "[" requeststr "]";
jay = json.parsearray(arraystr);
// 操作单据
// 操作人
list createusercodes = new arraylist();
// 操作人数据
createusercodes.add("customercode");
createusercodes.add("createcode");
createusercodes.add("operatepersoncode");
createusercodes.add("disablepercode");
string createusercode = jsonutil.analysisjson(jay, createusercodes);
// 创建人
log.setcreateusercode(createusercode);
// 修改人
log.setmodifyusercode(createusercode);
// 操作人
log.setoprateper(createusercode);
// 请求参数
log.setrequestcontent(requeststr.tostring());
// 修改时间
log.setupdatetime(new date());
return log;
} public void setbizlogrecordservice(ibizlogrecordservice bizlogrecordservice) {
this.bizlogrecordservice = bizlogrecordservice;
} /**
* 获取注解中对方法的描述信息 用于service层注解
*
* @param joinpoint
* 切点
* @return 方法描述
* @throws exception
*/
@suppresswarnings("rawtypes")
public static map getservicemthodannotatin(
joinpoint joinpoint) {
// 结果
map result = new hashmap();
// 获取target class名称
string targetname = joinpoint.gettarget().getclass().getname();
// 获取target method名称
string methodname = joinpoint.getsignature().getname();
// 获取请求参数
object[] arguments = joinpoint.getargs();
// 注解类
try {
class targetclass = class.forname(targetname);
method[] methods = targetclass.getmethods();
// 注解方法
string description = "";
string opratetype = "";
string clientname = "";
for (method method : methods) {
if (method.getname().equals(methodname)) {
class[] clazzs = method.getparametertypes();
if (clazzs.length == arguments.length) {
description = method.getannotation(wbmsservice.class)
.description();
opratetype = method.getannotation(wbmsservice.class)
.opratetype();
clientname = method.getannotation(wbmsservice.class)
.clientname();
// 接口描述
result.put("description", description);
// 操作类型
result.put("opratetype", opratetype);
// 客户名称
result.put("clientname", clientname);
break;
}
}
}
} catch (classnotfoundexception e) {
e.printstacktrace();
}
return result;
}
}

spring aop实现拦截接口请求打印日志的相关教程结束。

网站地图