原文链接:https:blog。51cto。comxiaowangshushu5358590一、效果 二、技术 JDK1。8 SpringBoot2。0、Aspect注解 MySql5。6三、代码干货 Log实体对象类。javapackage。。。modules。sys。log。entity;importjava。io。Serializable;importjava。util。Date;importjavax。persistence。Column;importjavax。persistence。Entity;importjavax。persistence。Id;importjavax。persistence。Table;importorg。springframework。stereotype。Component;importio。swagger。annotations。ApiModelProperty;EntityTable(namesyslog)Componentorg。hibernate。annotations。Table(comment系统ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a信息,appliesTosyslog)publicclassSysLogimplementsSerializable{privatestaticfinallongserialVersionUID42L;IdApiModelProperty(主键)Column(nameid,nullablefalse,columnDefinitionbigint(64)comment主键)privateLongid;主键IdApiModelProperty(ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a编号)Column(namelogid,columnDefinitionvarchar(255)commentahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a编号)privateStringlogId;ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a编号ApiModelProperty(请求链接)Column(nameurl,columnDefinitiontextcomment请求链接)privateStringurl;请求链接ApiModelProperty(请求方法)Column(namemethod,columnDefinitiontextcomment请求方法)privateStringmethod;请求方法ApiModelProperty(请求类名)Column(nameclassname,columnDefinitiontextcomment请求类名)privateStringclassName;请求方法ApiModelProperty(请求方法名)Column(namemethodname,columnDefinitiontextcomment请求方法名)privateStringmethodName;请求方法ApiModelProperty(请求参数)Column(nameparams,columnDefinitiontextcomment请求参数)privateStringparams;请求参数ApiModelProperty(ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a类型:(1:系统ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a2:业务ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a))Column(namelottype,columnDefinitionvarchar(255)commentahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a类型:(1:系统ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a2:业务ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a))privateStringlogType;请求方法ApiModelProperty(请求方式:(GETPOST))Column(nametype,columnDefinitionvarchar(255)comment请求方式(GETPOST))privateStringtype;请求方法ApiModelProperty(请求IP)Column(nameIP,columnDefinitiontextcomment请求IP)privateStringip;请求方法ApiModelProperty(操作的数据库表)Column(namelogtable,columnDefinitionvarchar(255)comment操作的数据库表)privateStringtable;操作的数据库表ApiModelProperty(请求异常)Column(namelogerror,columnDefinitiontextcomment请求异常)privateStringlogError;请求异常ApiModelProperty(运行时长)Column(nametime,columnDefinitionvarchar(255)comment运行时长)privatelongtime;ApiModelProperty(备注)Column(namelogcomment,columnDefinitiontextcomment备注)privateStringlogComment;备注ApiModelProperty(创建人)Column(namecreateby)privateStringcreateBy;创建人ApiModelProperty(创建时间)Column(namecreatetime)privateDatecreateTime;创建时间setter()getter();}四、基本的CRUDpackage。。。modules。sys。log。controller;importjava。util。List;importorg。springframework。beans。factory。annotation。Autowired;importorg。springframework。web。bind。annotation。CrossOrigin;importorg。springframework。web。bind。annotation。GetMapping;importorg。springframework。web。bind。annotation。RequestMapping;importorg。springframework。web。bind。annotation。ResponseBody;importorg。springframework。web。bind。annotation。RestController;import。modules。sys。log。entity。SysLog;import。modules。sys。log。service。SysLogService;importio。swagger。annotations。ApiOperation;CrossOrigin跨域RestControllerRequestMapping(SysLog)publicclassSysLogController{AutowiredpublicSysLogServicesysLogService;添加AOP注解ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a管理SysLogAspectValue(describtion获取所有ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a列表信息,logType1,typePOST,urlSysLogSelectAllSysLog,tablesyslog,paramsSysLog,methodPOST)ResponseBodyApiOperation(value获取所有ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a列表信息,notesSysLogSelectAllSysLog)GetMapping(valueSelectAllSysLog)publicListSysLogSelectAllSysLog(){returnsysLogService。SelectAllSysLogList(page)。getContent();}}package。。modules。sys。log。service;importorg。springframework。data。domain。Page;import。。t。modules。sys。log。entity。SysLog;系统ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a接口ClassName:SysLogServiceDescription:TODO(描述)authorauthordate2019120310:55:22publicinterfaceSysLogService{ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a保存Title:saveDescription:TODO(描述)paramsysLogauthorauthordate2019121009:56:28voidsave(SysLogsysLog);}package。。。modules。sys。log。service。impl;importjava。util。ArrayList;importjava。util。List;importjavax。persistence。criteria。CriteriaBuilder;importjavax。persistence。criteria。CriteriaQuery;importjavax。persistence。criteria。Predicate;importjavax。persistence。criteria。Root;importorg。springframework。beans。factory。annotation。Autowired;importorg。springframework。data。domain。Page;importorg。springframework。data。domain。PageRequest;importorg。springframework。data。domain。Pageable;importorg。springframework。data。domain。Sort;importorg。springframework。data。jpa。domain。Specification;importorg。springframework。stereotype。Service;import。。。。。modules。sys。log。entity。SysLog;import。。。。。。。。modules。sys。log。repository。SysLogRepository;import。。。。。。。。。。modules。sys。log。service。SysLogService;系统ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a实现类ClassName:SysLogServiceImplDescription:TODO(描述)authorauthordate2019120310:55:17Service(SysLogService)publicclassSysLogServiceImplimplementsSysLogService{AutowiredpublicSysLogRepositorysysLogRepository;OverridepublicPageSysLogSelectAllSysLogList(intpage){SortsortnewSort(Sort。Direction。DESC,createTime);创建时间正序排列PageablepageablePageRequest。of(page,this。size,sort);PageSysLogsysLogsysLogRepository。findAll(newSpecificationSysLog(){OverridepublicPredicatetoPredicate(RootSysLogroot,CriteriaQuerylt;?query,CriteriaBuildercriteriaBuilder){ListPredicatelistnewArrayListPredicate();拼接where条件Predicate〔〕pnewPredicate〔list。size()〕;returncriteriaBuilder。and(list。toArray(p));}},pageable);returnsysLog;}Overridepublicvoidsave(SysLogsysLog){sysLogRepository。save(sysLog);}}package。。。。。。。modules。sys。log。repository;importorg。springframework。data。jpa。domain。Specification;importorg。springframework。data。jpa。repository。JpaRepository;import。。。。。。。。modules。sys。log。entity。SysLog;系统ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a管理类ClassName:SysLogRepositoryDescription:TODO(描述)authorauthordate2019120310:55:09publicinterfaceSysLogRepositoryextendsJpaRepositorySysLog,Long{} 已上就是基本的业务功能中的CRUD的功能,下面就是重点的log的AOP切面功能,,,五、AOP切面功能动态获取log信息 1)、在每个需要用到的方法头上增加注释,附加案例【四中第一个截图】package。。。。。。。。modules。sys。log。controller;importjava。lang。annotation。Documented;importjava。lang。annotation。ElementType;importjava。lang。annotation。Retention;importjava。lang。annotation。RetentionPolicy;importjava。lang。annotation。Target;系统ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a管理表ClassName:SysLogControllerDescription:TODO(描述)authorauthordate2019120310:54:52Target(ElementType。METHOD)Retention(RetentionPolicy。RUNTIME)Documented注释文档publicinterfaceSysLogAspectValue{Stringdescribtion()default;ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a描述StringlogType()default1;ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a种类1:系统ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a2:业务ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志aStringtype()defaultGET;请求方式:(GETPOST)Stringurl()default;请求链接Stringtable()default;操作的数据库表Stringparams()default;请求参数Stringmethod()default;请求方法} 制作切面内容package。。。。。。。modules。sys。log。controller;importjava。lang。reflect。Method;importjava。util。ArrayList;importjava。util。Date;importjava。util。List;importjavax。servlet。http。HttpServletRequest;importorg。aspectj。lang。JoinPoint;importorg。aspectj。lang。ProceedingJoinPoint;importorg。aspectj。lang。annotation。AfterThrowing;importorg。aspectj。lang。annotation。Around;importorg。aspectj。lang。annotation。Aspect;importorg。aspectj。lang。annotation。Pointcut;importorg。aspectj。lang。reflect。MethodSignature;importorg。springframework。beans。factory。annotation。Autowired;importorg。springframework。stereotype。Component;importorg。springframework。web。context。request。RequestContextHolder;importorg。springframework。web。context。request。ServletRequestAttributes;importcom。google。gson。Gson;import。。。。。。common。utils。IdGenerate;import。。。。。。modules。sys。log。entity。SysLog;import。。。。。。modules。sys。log。service。SysLogService;系统ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a切面ClassName:SysLogAspectDescription:TODO(描述)authorauthordate2019120410:34:41Aspect使用Aspect注解声明一个切面ComponentpublicclassSystemLogAspect{privatefinalStringPOINTCUTannotation(。。。。。modules。sys。log。entity);privatestaticfinalorg。slf4j。Loggerlogorg。slf4j。LoggerFactory。getLogger(SystemLogAspect。class);AutowiredpublicSysLogServicesysLogService;这里我们使用注解的形式当然,我们也可以通过切点表达式直接指定需要拦截的package,需要拦截的class以及method切点表达式:execution(。。。)Pointcut(POINTCUT)publicvoidPointCut(){}环绕通知Around,当然也可以使用Before(前置通知)After(后置通知)parampointreturnthrowsThrowableAround(POINTCUT)Around(annotation(SysLogAspectValue))publicObjectaround(ProceedingJoinPointpoint)throwsThrowable{longbeginTimeSystem。currentTimeMillis();Objectresultpoint。proceed();try{正常保存ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志asaveLog(point,System。currentTimeMillis()beginTime);}catch(Exceptione){异常保存ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志aafterReturningMethod(point,e);}returnresult;}捕获异常Title:afterReturningMethodDescription:TODO(描述)paramjoinPointparameauthorauthorthrowsThrowabledate2019121001:40:37AfterThrowing(throwingexception,valueannotation(SysLogAspectValue),argNamesexception)publicvoidafterReturningMethod(JoinPointjoinPoint,Exceptione)throwsThrowable{if(e!null){SysLogsysLognewSysLog();longbeginTimeSystem。currentTimeMillis();longtimeSystem。currentTimeMillis()beginTime;MethodSignaturesignature(MethodSignature)joinPoint。getSignature();Methodmethodsignature。getMethod();接收到请求,记录请求内容ServletRequestAttributesattributes(ServletRequestAttributes)RequestContextHolder。getRequestAttributes();HttpServletRequestrequestattributes。getRequest();sysLog。setId(IdGenerate。longUUIDId());主键sysLog。setLogId(sysLog。getId()。toString());ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a编号sysLog。setTime(time);时长sysLog。setIp(request。getRemoteAddr());请求的IPsysLog。setCreateBy(sysLog。getIp());请求人sysLog。setCreateTime(newDate());创建时间SysLogAspectValuesysLogAspectValuemethod。getAnnotation(SysLogAspectValue。class);if(sysLogAspectValue!null){注解上的描述sysLog。setLogComment(sysLogAspectValue。describtion());备注sysLog。setLogType(sysLogAspectValue。logType());ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a类型sysLog。setType(sysLogAspectValue。type());请求类型sysLog。setUrl(sysLogAspectValue。url());请求链接sysLog。setTable(sysLogAspectValue。table());操作的数据表sysLog。setMethod(sysLogAspectValue。method());操作请求方法}请求的类名、方法名sysLog。setClassName(joinPoint。getTarget()。getClass()。getName());类名sysLog。setMethodName(signature。getName());方法名请求的参数Object〔〕argsjoinPoint。getArgs();ListStringlistnewArrayListString();for(Objecto:args){list。add(newGson()。toJson(o));}sysLog。setParams(Params:〔list。toString()〕:AspectjAfterThrowing);sysLog。setLogError(joinPoint。getSignature()。getName()〔message:e。getMessage()〕:AspectjAfterThrowing);System。out。println(异常保存ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a成功);sysLogService。save(sysLog);log。trace(POINTCUT,sysLog);System。out。println(异常保存ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a结束);}}正常保存ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志aparamjoinPointparamtimethrowsThrowablepublicvoidsaveLog(ProceedingJoinPointjoinPoint,longtime){SysLogsysLognewSysLog();sysLogthis。addSysLog(joinPoint,sysLog,time);请求的参数Object〔〕argsjoinPoint。getArgs();ListStringlistnewArrayListString();for(Objecto:args){list。add(newGson()。toJson(o));}sysLog。setParams(Params:〔list。toString()〕:AspectjAround);sysLog。setLogError(〔message:无〕:AspectjAround);System。out。println(正常保存ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a成功);sysLogService。save(sysLog);log。trace(POINTCUT,sysLog);System。out。println(正常保存ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a结束);}组装ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志amodelTitle:addSysLogDescription:TODO(描述)paramsysLogreturnauthorauthordate2019121002:09:04publicSysLogaddSysLog(ProceedingJoinPointjoinPoint,SysLogsysLog,longtime){MethodSignaturesignature(MethodSignature)joinPoint。getSignature();Methodmethodsignature。getMethod();接收到请求,记录请求内容ServletRequestAttributesattributes(ServletRequestAttributes)RequestContextHolder。getRequestAttributes();HttpServletRequestrequestattributes。getRequest();sysLog。setId(IdGenerate。longUUIDId());主键sysLog。setLogId(sysLog。getId()。toString());ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a编号sysLog。setTime(time);时长sysLog。setIp(request。getRemoteAddr());请求的IPsysLog。setCreateBy(sysLog。getIp());请求人sysLog。setCreateTime(newDate());创建时间SysLogAspectValuesysLogAspectValuemethod。getAnnotation(SysLogAspectValue。class);if(sysLogAspectValue!null){注解上的描述sysLog。setLogComment(sysLogAspectValue。describtion());备注sysLog。setLogType(sysLogAspectValue。logType());ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a类型sysLog。setType(sysLogAspectValue。type());请求类型sysLog。setUrl(sysLogAspectValue。url());请求链接sysLog。setTable(sysLogAspectValue。table());操作的数据表sysLog。setMethod(sysLogAspectValue。method());操作请求方法}请求的类名、方法名sysLog。setClassName(joinPoint。getTarget()。getClass()。getName());类名sysLog。setMethodName(signature。getName());方法名returnsysLog;}} 生成这个Log切面日志的用法: