com.alibaba
druid-spring-boot-starter
1.1.14
org.springframework.boot
spring-boot-starter-jdbc
org.springframework.boot
spring-boot-starter-aop
mysql
mysql-connector-java
5.1.46
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
String value() default "";
}
CREATE TABLE `sys_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`operation` varchar(255) DEFAULT NULL,
`time` decimal(13,0) DEFAULT NULL,
`method` varchar(255) DEFAULT NULL,
`params` varchar(255) DEFAULT NULL,
`ip` varchar(255) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;
@Data
public class SysLog implements Serializable {
private Integer id;
private String username;
private String operation;
private Integer time;
private String method;
private String params;
private String ip;
private Date createTime;
}
public interface SysLogDao {
void saveSysLog(SysLog syslog);
}
@Service
public class SysLogDaoImp implements SysLogDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void saveSysLog(SysLog syslog) {
StringBuffer sql = new StringBuffer("insert into sys_log VALUES (NULL,?,?,?,?,?,?,?)");
String sql2=sql.toString();
jdbcTemplate.update(sql2,syslog.getUsername(),syslog.getOperation(),syslog.getTime(),syslog.getMethod(),syslog.getParams(),syslog.getIp(),syslog.getCreateTime());
}
}
@RestController
public class TestController {
@Log("执行方法一")
@GetMapping("/one")
public void methodOne(String name){}
@Log("执行方法二")
@GetMapping("/two")
public void methodTwo() throws InterruptedException {
Thread.sleep(2000);
}
@Log("执行方法三")
@GetMapping("/three")
public void methodThree(String name,String age){}
}
public class IpUtils
{
public static String getIpAddr(HttpServletRequest request)
{
if (request == null)
{
return "unknown";
}
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("X-Forwarded-For");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getRemoteAddr();
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
}
public class HttpContextUtils {
public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
}
}
@Aspect
@Component
public class LogAspect {
@Autowired
private SysLogDao sysLogDao;
@Pointcut("@annotation(com.example.springbootdemo.utils.Log)")
public void pointcut() { }
@Around("pointcut()")
public Object around(ProceedingJoinPoint point) {
Object result = null;
long beginTime = System.currentTimeMillis();
try {
// 执行方法
result = point.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
// 执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
// 保存日志
saveLog(point, time);
return result;
}
private void saveLog(ProceedingJoinPoint joinPoint, long time) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
SysLog sysLog = new SysLog();
Log logAnnotation = method.getAnnotation(Log.class);
if (logAnnotation != null) {
// 注解上的描述
sysLog.setOperation(logAnnotation.value());
}
// 请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
sysLog.setMethod(className + "." + methodName + "()");
// 请求的方法参数值
Object[] args = joinPoint.getArgs();
// 请求的方法参数名称
LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
String[] paramNames = u.getParameterNames(method);
if (args != null && paramNames != null) {
String params = "";
for (int i = 0; i < args.length; i++) {
params += " " + paramNames[i] + ": " + args[i];
}
sysLog.setParams(params);
}
// 获取request
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
// 设置IP地址
sysLog.setIp(IpUtils.getIpAddr(request));
// 模拟一个用户名
sysLog.setUsername("mrbird");
sysLog.setTime((int) time);
sysLog.setCreateTime(new Date());
// 保存系统日志
sysLogDao.saveSysLog(sysLog);
}
}
http://localhost:8080/web/one?name=KangKang
http://localhost:8080/web/two
http://localhost:8080/web/three?name=Mike&age=25