文章目录
系列目录
SpringSecurity权限管理系统实战—一、项目简介和开发环境准备
SpringSecurity权限管理系统实战—二、日志、接口文档等实现
SpringSecurity权限管理系统实战—三、主要页面及接口实现
SpringSecurity权限管理系统实战—四、整合SpringSecurity(上)
SpringSecurity权限管理系统实战—五、整合SpringSecurity(下)
SpringSecurity权限管理系统实战—六、SpringSecurity整合JWT
SpringSecurity权限管理系统实战—七、处理一些问题
SpringSecurity权限管理系统实战—八、AOP 记录用户日志、异常日志
SpringSecurity权限管理系统实战—九、数据权限的配置
前言
日志功能在二的时候其实简单实现了一下,但是有时我们需要对一些重要功能操作记录日志,或是在操作时发生异常,需要记录异常日志。但是之前每次发生异常要定位原因我们都要到服务器去查询日志才能找到,或许是搭建一个日志收集系统(但是本项目中暂不考虑)。那么我们可以专门做个功能来记录用户操作日志和异常日志,在把日志存入数据库,方便查询。
一、最终效果
二、新建my_log表
相应字段都有注释,很好理解,用户日志、异常日志都存放在这一张表中,通过type来区分,当然也可以拆分成两张表。
三、添加依赖
<!--aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- UserAgentUtils,浏览器信息工具类 -->
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>1.21</version>
</dependency>
<!--ip2region,这是根据ip查地址的工具,有兴趣自己可以了解-->
<!-- <dependency>-->
<!-- <groupId>org.lionsoul</groupId>-->
<!-- <artifactId>ip2region</artifactId>-->
<!-- <version>1.7.2</version>-->
<!-- </dependency>-->
<!--分页工具-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.13</version>
</dependency>
<!--hutool工具-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.1.4</version>
</dependency>
四、需要用到的工具类
SecurityUtils
/**
* @author codermy
* @createTime 2020/8/4
*/
public class SecurityUtils {
/**
* 获取系统用户名称
*
* @return 系统用户名称
*/
public static String getCurrentUsername() {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
throw new MyException(ResultCode.UNAUTHORIZED, "当前登录状态过期");
}
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
return userDetails.getUsername();
}
/**
* 取得当前用户登录IP, 如果当前用户未登录则返回空字符串.
* 此方法无用
*/
public static String getCurrentUserIp() {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
throw new MyException(ResultCode.UNAUTHORIZED, "当前登录状态过期");
}
Object details = authentication.getDetails();
if (!(details instanceof WebAuthenticationDetails)) {
return "";
}
WebAuthenticationDetails webDetails = (WebAuthenticationDetails) details;
return webDetails.getRemoteAddress();
}
}
LogUtils
/**
* @author codermy
* @createTime 2020/8/7
*/
public class LogUtils {
private static final char SEPARATOR = '_';
private static final String UNKNOWN = "unknown";
/**
* 获取ip地址
*/
public static String getIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0