Spring自定义日志注解
JDK1.5中引入注解,spring框架把java注解发扬光大
一 创建自定义注解
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.lang.annotation.RetentionPolicy; @Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
String value() default "";
}
二 解析注解
使用@Aspect注解使得该类成为切面类
import java.lang.reflect.Method;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import javax.servlet.http.HttpServletRequest; import com.prostate.common.service.LogService;
import com.prostate.system.domain.UserToken;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component; import com.prostate.common.annotation.Log;
import com.prostate.common.dao.LogDao;
import com.prostate.common.domain.LogDO;
import com.prostate.common.utils.HttpContextUtils;
import com.prostate.common.utils.IPUtils;
import com.prostate.common.utils.JSONUtils;
import com.prostate.common.utils.ShiroUtils;
import com.prostate.system.domain.UserDO; @Aspect
@Component
public class LogAspect {
private static final Logger logger = LoggerFactory.getLogger(LogAspect.class); @Autowired
LogService logService; @Pointcut("@annotation(com.common.annotation.Log)")
public void logPointCut() {
} @Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
// 执行方法
Object result = point.proceed();
// 执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
//异步保存日志
saveLog(point, time);
return result;
} void saveLog(ProceedingJoinPoint joinPoint, long time) throws InterruptedException {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
LogDO sysLog = new LogDO();
Log syslog = method.getAnnotation(Log.class);
if (syslog != null) {
// 注解上的描述
sysLog.setOperation(syslog.value());
}
// 请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
sysLog.setMethod(className + "." + methodName + "()");
// 请求的参数
Object[] args = joinPoint.getArgs();
try {
String params = JSONUtils.beanToJson(args[0]).substring(0, 4999);
sysLog.setParams(params);
} catch (Exception e) { }
// 获取request
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
// 设置IP地址
sysLog.setIp(IPUtils.getIpAddr(request));
// 用户名
UserDO currUser = ShiroUtils.getUser();
if (null == currUser) {
if (null != sysLog.getParams()) {
sysLog.setUserId(-1L);
sysLog.setUsername(sysLog.getParams());
} else {
sysLog.setUserId(-1L);
sysLog.setUsername("获取用户信息为空");
}
} else {
sysLog.setUserId(ShiroUtils.getUserId());
sysLog.setUsername(ShiroUtils.getUser().getUsername());
}
sysLog.setTime((int) time);
// 系统当前时间
Date date = new Date();
sysLog.setGmtCreate(date);
// 保存系统日志
logService.save(sysLog);
}
}
通过@Pointcut指定切入点,这里指定Log注解,也就是被@Log修饰的方法,进入该切入点
① @Before 前置通知 在某连接点之前执行的通知
② @Around 环绕通知 在实现方法的前后执行的通知
③ @AfterReturning 后置通知 在某连接点正常完成执行的通知
④ @AfterThrowing 异常通知 在方法抛出异常退出执行的通知
⑤ @After 后置通知
@RequiresPermissions("base:scaleManager:edit")
@Log("编辑题目或选项")
@GetMapping("/edit/{id}")
String edit(Model model, @PathVariable("id") String id) {
ScaleDO scaleDO = scaleManagerService.get(id);
model.addAttribute("scaleDO", scaleDO);
ScaleDO scale = scaleManagerService.get(scaleDO.getParentId());
model.addAttribute("scale",scale);
return prefix+"/edit";
}
随便弄一个测试类就可测试了
Spring自定义日志注解的更多相关文章
- 自定义日志注解 + AOP实现记录操作日志
需求:系统中经常需要记录员工的操作日志和用户的活动日志,简单的做法在每个需要的方法中进行日志保存操作, 但这样对业务代码入侵性太大,下面就结合AOP和自定义日志注解实现更方便的日志记录 首先看 ...
- springboot最新版本自定义日志注解和AOP
LogAspectAnnotation @ControllerLogAspectAnnotation /** * * Define a log facet annotation * @author s ...
- Spring Boot @Enable*注解源码解析及自定义@Enable*
Spring Boot 一个重要的特点就是自动配置,约定大于配置,几乎所有组件使用其本身约定好的默认配置就可以使用,大大减轻配置的麻烦.其实现自动配置一个方式就是使用@Enable*注解,见其名知 ...
- 【Redis】redis异步消息队列+Spring自定义注解+AOP方式实现系统日志持久化
说明: SSM项目中的每一个请求都需要进行日志记录操作.一般操作做的思路是:使用springAOP思想,对指定的方法进行拦截.拼装日志信息实体,然后持久化到数据库中.可是仔细想一下会发现:每次的客户端 ...
- spring统一日志管理,切面(@Aspect),注解式日志管理
step1 开启切面编程 <!-- 开启切面编程(通过配置织入@Aspectj切面 ) --> <aop:aspectj-autoproxy/> <aop:aspectj ...
- Spring Boot 自定义日志详解
本节内容基于 Spring Boot 2.0. 你所需具备的基础 什么是 Spring Boot? Spring Boot 核心配置文件详解 Spring Boot 开启的 2 种方式 Spring ...
- 使用Spring自定义注解实现任务路由的方法
在Spring mvc的开发中,我们可以通过RequestMapping来配,当前方法用于处理哪一个URL的请求.同样我们现在有一个需求,有一个任务调度器,可以按照不同的任务类型路由到不同的任务执行器 ...
- 深入Spring:自定义注解加载和使用
前言 在工作中经常使用Spring的相关框架,免不了去看一下Spring的实现方法,了解一下Spring内部的处理逻辑.特别是开发Web应用时,我们会频繁的定义@Controller,@Service ...
- spring:自定义限定符注解@interface, 首选bean
spring:自定义限定符注解@interface, 首选bean 1.首选bean 在声明bean的时候,通过将其中一个可选的bean设置为首选(primary)bean能够避免自动装配时的歧义性. ...
随机推荐
- Leetcode 121.买股票的最佳时机
题目描述: 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格. 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润. 注意你不能在买入股票前卖出 ...
- APP自动化测试的环境配置
什么是Appium? 第三方自动化框架(工具),扩充了selenium webdriver 协议,在原有的基础上添加了移动端测试API selenium webdriver 指定了客户端到服务端的协议 ...
- 云原生生态周报 Vol. 21 | Traefik 2.0 正式发布
作者 | 浔鸣.心水.元毅.源三.衷源 业界要闻 CNCF 计划将 TOC 升至 11 人 技术监督委员会(TOC)是 CNCF 的三大核心管理机构之一,从 2020 年 1 月起,TOC 将从 9 ...
- web前端开发面试题(附答案)-3
1.用纯css创建一个三角形的原理: .demo{ width:0; height: 0; border: 5px solid transparent; border-left-color: red; ...
- Python学习笔记整理总结【Django】:Model操作(一)
Model操作(一) 一.Django ORM基本配置 ORM:关系对象映射(Object Relational Mapping,简称ORM)db Frist:到目前为止,当我们的程序涉及到数据库相关 ...
- spring 定时器知识点
一.各域说明 字段域 秒 分 时 日 月 星期(7为周六) 年(可选) 取值范围 0-59 0-59 0-23 1-31 1-12或JAN–DEC 1-7或SUN–SAT 1970–2099 可用字符 ...
- Spring Boot 监听 Activemq 中的特定 topic ,并将数据通过 RabbitMq 发布出去
1.Spring Boot 和 ActiveMQ .RabbitMQ 简介 最近因为公司的项目需要用到 Spring Boot , 所以自学了一下, 发现它与 Spring 相比,最大的优点就是减少了 ...
- 【ADO.NET基础-Login】带验证码验证的登录界面(用于简单的基础学习)
以下代码如果有不对或者不妥之处,还望大神们指点一二 或者有同学者有问题或建议,一定要提出来,共同探讨 小弟在此感谢! 前台代码: <!DOCTYPE html> <html xmln ...
- .Net Core 商城微服务项目系列(五):使用Polly处理服务错误
项目进行微服务化之后,随之而来的问题就是服务调用过程中发生错误.超时等问题的时候我们该怎么处理,比如因为网络的瞬时问题导致服务超时,这在我本人所在公司的项目里是很常见的问题,当发生请求超时问题的时候, ...
- 【干货总结】:可能是史上最全的MySQL和PGSQL对比材料
[干货总结]:可能是史上最全的MySQL和PGSQL的对比材料 运维了MySQL和PGSQL已经有一段时间了,最近接到一个数据库选型需求,于是便开始收集资料整理了一下,然后就有了下面的对比表 关键词: ...