登录日志
/**
* @Date: 2023/8/20 13:24
*/
public class LoginlogThread implements Runnable {
private Loginlog loginlog;
public LoginlogThread(Loginlog loginlog) {
this.loginlog = loginlog;
}
@Override
public void run() {
LoginlogService loginlogService = Spring.getBean(LoginlogService.class);
loginlogService.save(this.loginlog);
}
}
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
* @Date: 2023/8/20 12:32
*/
@Component
@Configuration
@Slf4j
public class LoginlogInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//不记录日志
if (!(request instanceof BodyReaderHttpServletRequestWrapper)) {
return true;
}
Map<String, Object> requestParm = new HashMap<>();
BodyReaderHttpServletRequestWrapper requestWrapper = (BodyReaderHttpServletRequestWrapper) request;
//ip地址
String ipAddress = IPUtil.getIPAddress(requestWrapper);
requestParm.put("ipAddress", ipAddress);
String bodyString = requestWrapper.getBodyString();
//转map
Map<String, Object> map = JSON.parseObject(bodyString, new TypeReference<Map<String, Object>>() {
});
//获得用户名
String username = MapUtil.getMapValue(map, "username", "");
requestParm.put("username", username);
request.setAttribute("loginLog", requestParm);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
Object loginlog = request.getAttribute("loginLog");
if (null == loginlog) {
return;
}
Map<String, Object> requestParm = (Map<String, Object>) loginlog;
//获取响应结果
Object body = request.getAttribute("body");
if (null == body || !(body instanceof RespBody)) {
return;
}
RespBody<Object> result = (RespBody<Object>) body;
if (null == ex || HttpStatus.SUCCESS.getStatus() != response.getStatus()) {
Loginlog info = new Loginlog();
String username = MapUtil.getMapValue(requestParm, "username", "");
String ipAddress = MapUtil.getMapValue(requestParm, "ipAddress", "");
info.setIpAddress(ipAddress);
info.setUsername(username);
info.setLoginResult(result.getCode());
info.setHttpStatus(response.getStatus());
LoginlogThreadPool.getDataThread().submit(new LoginlogThread(info));
//释放资源
request.removeAttribute("loginLog");
}
}
}
操作日志
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
* 操作日志拦截器
*
* @Date: 2023/8/14 9:37
*/
@Component
@Configuration
@Slf4j
public class OperationLogInterceptor implements HandlerInterceptor {
@Autowired
private PersonalUserService personalUserService;
@Autowired
private LogConfig logConfig;
@Autowired
private SecurityConfig securityConfig;
//不拦截的请求
private static String[] AllowAccessURI = null;
private boolean isAllowAccessURI(String requestURI) {
//判断参数是否合法
if (StringUtil.isNullOrEmpty(requestURI)) {
return false;
}
if (StringUtil.isNullOrEmpty(securityConfig.getAllowAccessURI())) {
//log.warn("allow access uri not configured");
return false;
}
if (null == AllowAccessURI) {
AllowAccessURI = securityConfig.getAllowAccessURI().split(",");
}
//判断是否在“允许访问”的列表中
for (int i = 0; i < AllowAccessURI.length; i++) {
String allowURI = AllowAccessURI[i];
if (requestURI.contains(allowURI)) {
return true;
}
}
return false;
}
@Override
public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
//如果是不开启,则直接退出
if (logConfig.getOperationLogEnable() == EnableEnum.UNABLE.getCode()) {
return true;
}
//不记录日志
if (!(request instanceof BodyReaderHttpServletRequestWrapper)) {
return true;
}
Map<String, Object> requestParm = new HashMap<>();
BodyReaderHttpServletRequestWrapper requestWrapper = (BodyReaderHttpServletRequestWrapper) request;
//请求URI地址
String requestURI = requestWrapper.getRequestURI();
//允许通过的则不记录日志
if (isAllowAccessURI(requestURI)) {
return true;
}
requestParm.put("requestURI", requestURI);
//请求类型
String method = requestWrapper.getMethod();
requestParm.put("method", method);
//ip地址
String ipAddress = IPUtil.getIPAddress(requestWrapper);
requestParm.put("ipAddress", ipAddress);
//参数内容
String parameter = "";
Map<String, String[]> parameterMap = requestWrapper.getParameterMap();
if (null == parameterMap || parameterMap.isEmpty()) {
parameter = requestWrapper.getBodyString();
} else {
parameter = JSON.toJSONString(parameterMap);
}
requestParm.put("parameter", parameter);
//字符集
String characterEncoding = requestWrapper.getCharacterEncoding();
requestParm.put("characterEncoding", characterEncoding);
if (null == handler) {
log.error("handler is null"); //静态资源
return true;
}
//handler的处理
if (!(handler instanceof HandlerMethod)) {
log.info("static resource"); //静态资源
request.setAttribute("startTime", System.currentTimeMillis());
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
Class<?> clazz = handlerMethod.getBeanType();
//获得类上@RequestMapping注解
//类路径
String classMappingURL = "";
RequestMapping classRequestMappingAnnotation = clazz.getAnnotation(RequestMapping.class);
if (null != classRequestMappingAnnotation) {
String[] classMappingURLArray = classRequestMappingAnnotation.value();
if (null != classMappingURLArray && classMappingURLArray.length > 0) {
classMappingURL = classMappingURLArray[0];
}
}
//获得swager上的@Api注解
String apiName = "";
Api apiAnnotation = clazz.getAnnotation(Api.class);
if (null != apiAnnotation) {
String[] tags = apiAnnotation.tags();
if (null != tags && tags.length > 0) {
apiName = tags[0];
}
}
requestParm.put("apiName", apiName);
//获得swager上的@ApiOperation注解
String operationName = "";
ApiOperation apiOperationAnnotation = handlerMethod.getMethodAnnotation(ApiOperation.class);
if (null != apiOperationAnnotation) {
operationName = apiOperationAnnotation.value();
}
requestParm.put("operationName", operationName);
//获得方法上@RequestMapping注解
String methodMappingURL = "";
//获得方法上的注解
RequestMapping methodRequestMapping = handlerMethod.getMethodAnnotation(RequestMapping.class);
if (null != methodRequestMapping) {
String[] methodRequestMappingArray = methodRequestMapping.value();
if (null == methodRequestMappingArray || methodRequestMappingArray.length <= 0) {
log.error("methodRequestMappingArray is null");
return true;
}
methodMappingURL = methodRequestMappingArray[0];
} else {
if (RequestMethod.POST.name().equalsIgnoreCase(method)) {
PostMapping postMapping = handlerMethod.getMethodAnnotation(PostMapping.class);
if (null == postMapping) {
log.error("postMapping is null");
return true;
}
methodMappingURL = postMapping.value()[0];
} else if (RequestMethod.PUT.name().equalsIgnoreCase(method)) {
PutMapping putMapping = handlerMethod.getMethodAnnotation(PutMapping.class);
if (null == putMapping) {
log.error("putMapping is null");
return true;
}
methodMappingURL = putMapping.value()[0];
} else if (RequestMethod.GET.name().equalsIgnoreCase(method)) {
GetMapping getMapping = handlerMethod.getMethodAnnotation(GetMapping.class);
if (null == getMapping) {
log.error("getMapping is null");
return true;
}
methodMappingURL = getMapping.value()[0];
} else if (RequestMethod.DELETE.name().equalsIgnoreCase(method)) {
DeleteMapping deleteMapping = handlerMethod.getMethodAnnotation(DeleteMapping.class);
if (null == deleteMapping) {
log.error("deleteMapping is null");
return true;
}
methodMappingURL = deleteMapping.value()[0];
} else {
log.error("Request method type not supported");
return true;
}
}
String rule = String.format("/%s/%s/%s", logConfig.getAppName(), classMappingURL, methodMappingURL).replace("//", "/");
requestParm.put("rule", rule);
//定义一个匹配器
PathMatcher matcher = new AntPathMatcher();
boolean match = matcher.match(rule, requestURI);
if (!match) {
return true;
}
//获得登录的用户信息,如未登录,则匿名访问
Object userID = request.getAttribute("userID");
if (null == userID) {
log.error("no login");
return true;
}
PersonalUser currentLoginUser = personalUserService.getCurrentLoginUser(request);
if (null == currentLoginUser) {
return true;
}
//创建id
String id = SnowFlakeUtil.getInstance().nextStringId();
//id
request.setAttribute("id", id);
//requestParm缓存
requestParm.put("currentLoginUser", currentLoginUser);
requestParm.put("id", id);
request.setAttribute("requestParm", requestParm);
//记录起始时间
request.setAttribute("startTime", System.currentTimeMillis());
//添加日志
return true;
}
@Override
public void postHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, Object handler, Exception ex) throws Exception {
String id = (String) request.getAttribute("id");
//如果取不到id则直接返回
if (StringUtil.isNullOrEmpty(id)) {
return;
}
Long startTime = (Long) request.getAttribute("startTime");
Long endTime = System.currentTimeMillis();
Long costTime = endTime - startTime;
Object body = request.getAttribute("body");
if (null == body || !(body instanceof RespBody)) {
return;
}
RespBody<Object> result = (RespBody<Object>) body;
Map<String, Object> requestParm = (Map<String, Object>) request.getAttribute("requestParm");
Map<String, Object> map = new HashMap<>();
map.put("costTime", costTime);
map.put("httpStatus", response.getStatus());
map.put("result", result);
map.putAll(requestParm);
//记录日志并释放资源
if (null == ex || HttpStatus.SUCCESS.getStatus() != response.getStatus()) {
//更新日志,开启线程处理
OperationLogThreadPool.getDataThread().submit(new OperationLogDataThread(map));
request.removeAttribute("startTime");
request.removeAttribute("id");
request.removeAttribute("requestParm");
}
}
}
操作日志
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
* 操作日志拦截器
*
* @Date: 2023/8/14 9:37
*/
@Component
@Configuration
@Slf4j
public class OperationLogInterceptor implements HandlerInterceptor {
@Autowired
private PersonalUserService personalUserService;
@Autowired
private LogConfig logConfig;
@Autowired
private SecurityConfig securityConfig;
//不拦截的请求
private static String[] AllowAccessURI = null;
private boolean isAllowAccessURI(String requestURI) {
//判断参数是否合法
if (StringUtil.isNullOrEmpty(requestURI)) {
return false;
}
if (StringUtil.isNullOrEmpty(securityConfig.getAllowAccessURI())) {
//log.warn("allow access uri not configured");
return false;
}
if (null == AllowAccessURI) {
AllowAccessURI = securityConfig.getAllowAccessURI().split(",");
}
//判断是否在“允许访问”的列表中
for (int i = 0; i < AllowAccessURI.length; i++) {
String allowURI = AllowAccessURI[i];
if (requestURI.contains(allowURI)) {
return true;
}
}
return false;
}
@Override
public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
//如果是不开启,则直接退出
if (logConfig.getOperationLogEnable() == EnableEnum.UNABLE.getCode()) {
return true;
}
//不记录日志
if (!(request instanceof BodyReaderHttpServletRequestWrapper)) {
return true;
}
Map<String, Object> requestParm = new HashMap<>();
BodyReaderHttpServletRequestWrapper requestWrapper = (BodyReaderHttpServletRequestWrapper) request;
//请求URI地址
String requestURI = requestWrapper.getRequestURI();
//允许通过的则不记录日志
if (isAllowAccessURI(requestURI)) {
return true;
}
requestParm.put("requestURI", requestURI);
//请求类型
String method = requestWrapper.getMethod();
requestParm.put("method", method);
//ip地址
String ipAddress = IPUtil.getIPAddress(requestWrapper);
requestParm.put("ipAddress", ipAddress);
//参数内容
String parameter = "";
Map<String, String[]> parameterMap = requestWrapper.getParameterMap();
if (null == parameterMap || parameterMap.isEmpty()) {
parameter = requestWrapper.getBodyString();
} else {
parameter = JSON.toJSONString(parameterMap);
}
requestParm.put("parameter", parameter);
//字符集
String characterEncoding = requestWrapper.getCharacterEncoding();
requestParm.put("characterEncoding", characterEncoding);
if (null == handler) {
log.error("handler is null"); //静态资源
return true;
}
//handler的处理
if (!(handler instanceof HandlerMethod)) {
log.info("static resource"); //静态资源
request.setAttribute("startTime", System.currentTimeMillis());
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
Class<?> clazz = handlerMethod.getBeanType();
//获得类上@RequestMapping注解
//类路径
String classMappingURL = "";
RequestMapping classRequestMappingAnnotation = clazz.getAnnotation(RequestMapping.class);
if (null != classRequestMappingAnnotation) {
String[] classMappingURLArray = classRequestMappingAnnotation.value();
if (null != classMappingURLArray && classMappingURLArray.length > 0) {
classMappingURL = classMappingURLArray[0];
}
}
//获得swager上的@Api注解
String apiName = "";
Api apiAnnotation = clazz.getAnnotation(Api.class);
if (null != apiAnnotation) {
String[] tags = apiAnnotation.tags();
if (null != tags && tags.length > 0) {
apiName = tags[0];
}
}
requestParm.put("apiName", apiName);
//获得swager上的@ApiOperation注解
String operationName = "";
ApiOperation apiOperationAnnotation = handlerMethod.getMethodAnnotation(ApiOperation.class);
if (null != apiOperationAnnotation) {
operationName = apiOperationAnnotation.value();
}
requestParm.put("operationName", operationName);
//获得方法上@RequestMapping注解
String methodMappingURL = "";
//获得方法上的注解
RequestMapping methodRequestMapping = handlerMethod.getMethodAnnotation(RequestMapping.class);
if (null != methodRequestMapping) {
String[] methodRequestMappingArray = methodRequestMapping.value();
if (null == methodRequestMappingArray || methodRequestMappingArray.length <= 0) {
log.error("methodRequestMappingArray is null");
return true;
}
methodMappingURL = methodRequestMappingArray[0];
} else {
if (RequestMethod.POST.name().equalsIgnoreCase(method)) {
PostMapping postMapping = handlerMethod.getMethodAnnotation(PostMapping.class);
if (null == postMapping) {
log.error("postMapping is null");
return true;
}
methodMappingURL = postMapping.value()[0];
} else if (RequestMethod.PUT.name().equalsIgnoreCase(method)) {
PutMapping putMapping = handlerMethod.getMethodAnnotation(PutMapping.class);
if (null == putMapping) {
log.error("putMapping is null");
return true;
}
methodMappingURL = putMapping.value()[0];
} else if (RequestMethod.GET.name().equalsIgnoreCase(method)) {
GetMapping getMapping = handlerMethod.getMethodAnnotation(GetMapping.class);
if (null == getMapping) {
log.error("getMapping is null");
return true;
}
methodMappingURL = getMapping.value()[0];
} else if (RequestMethod.DELETE.name().equalsIgnoreCase(method)) {
DeleteMapping deleteMapping = handlerMethod.getMethodAnnotation(DeleteMapping.class);
if (null == deleteMapping) {
log.error("deleteMapping is null");
return true;
}
methodMappingURL = deleteMapping.value()[0];
} else {
log.error("Request method type not supported");
return true;
}
}
String rule = String.format("/%s/%s/%s", logConfig.getAppName(), classMappingURL, methodMappingURL).replace("//", "/");
requestParm.put("rule", rule);
//定义一个匹配器
PathMatcher matcher = new AntPathMatcher();
boolean match = matcher.match(rule, requestURI);
if (!match) {
return true;
}
//获得登录的用户信息,如未登录,则匿名访问
Object userID = request.getAttribute("userID");
if (null == userID) {
log.error("no login");
return true;
}
PersonalUser currentLoginUser = personalUserService.getCurrentLoginUser(request);
if (null == currentLoginUser) {
return true;
}
//创建id
String id = SnowFlakeUtil.getInstance().nextStringId();
//id
request.setAttribute("id", id);
//requestParm缓存
requestParm.put("currentLoginUser", currentLoginUser);
requestParm.put("id", id);
request.setAttribute("requestParm", requestParm);
//记录起始时间
request.setAttribute("startTime", System.currentTimeMillis());
//添加日志
return true;
}
@Override
public void postHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, Object handler, Exception ex) throws Exception {
String id = (String) request.getAttribute("id");
//如果取不到id则直接返回
if (StringUtil.isNullOrEmpty(id)) {
return;
}
Long startTime = (Long) request.getAttribute("startTime");
Long endTime = System.currentTimeMillis();
Long costTime = endTime - startTime;
Object body = request.getAttribute("body");
if (null == body || !(body instanceof RespBody)) {
return;
}
RespBody<Object> result = (RespBody<Object>) body;
Map<String, Object> requestParm = (Map<String, Object>) request.getAttribute("requestParm");
Map<String, Object> map = new HashMap<>();
map.put("costTime", costTime);
map.put("httpStatus", response.getStatus());
map.put("result", result);
map.putAll(requestParm);
//记录日志并释放资源
if (null == ex || HttpStatus.SUCCESS.getStatus() != response.getStatus()) {
//更新日志,开启线程处理
OperationLogThreadPool.getDataThread().submit(new OperationLogDataThread(map));
request.removeAttribute("startTime");
request.removeAttribute("id");
request.removeAttribute("requestParm");
}
}
}
package com.maxvision.systemlog.core;
import com.maxvision.common.communication.RespBody;
import com.maxvision.common.enums.EnableEnum;
import com.maxvision.common.util.*;
import com.maxvision.common.util.Error;
import com.maxvision.rbac.entity.ent.PersonalUser;
import com.maxvision.systemlog.entity.ent.Operationlog;
import com.maxvision.systemlog.entity.ent.Operationlogconfig;
import com.maxvision.systemlog.service.service.OperationLogConfigService;
import com.maxvision.systemlog.service.service.OperationlogService;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
/**
- 操作日志处理线程
*/
@Slf4j
public class OperationLogDataThread implements Runnable {
private Map<String, Object> map;
public OperationLogDataThread(Map<String, Object> map) {
this.map = map;
}
@Override
public void run() {
if (null == map) {
log.error(Error.MISSING_PARAMETER + "");
return;
}
//日志记录id
String id = MapUtil.getMapValue(map, "id", "");
//接口耗时
long costTime = MapUtil.getMapValueLong(map, "costTime", 0L);
//httpStatus
int httpStatus = MapUtil.getMapValue(map, "httpStatus", 0);
//rule
String rule = MapUtil.getMapValue(map, "rule", "");
//ipAddress
String ipAddress = MapUtil.getMapValue(map, "ipAddress", "");
//parameter
String parameter = MapUtil.getMapValue(map, "parameter", "");
//characterEncoding
String characterEncoding = MapUtil.getMapValue(map, "characterEncoding", "");
//requestURI
String requestURI = MapUtil.getMapValue(map, "requestURI", "");
//apiName
String apiName = MapUtil.getMapValue(map, "apiName", "");
//operationName
String operationName = MapUtil.getMapValue(map, "operationName", "");
//method
String method = MapUtil.getMapValue(map, "method", "");
//返回结果
int code = Error.SUCCESS;
if (map.containsKey("result")) {
Object result = map.get("result");
if (result instanceof RespBody) {
RespBody<Object> respBody = (RespBody<Object>) result;
code = respBody.getCode();
}
}
//用户
String operationUserId = "";
String operationUserName = "";
if (map.containsKey("currentLoginUser")) {
Object result = map.get("currentLoginUser");
if (result instanceof PersonalUser) {
PersonalUser respBody = (PersonalUser) result;
operationUserId = respBody.getId();
operationUserName = respBody.getUsername();
}
}
//操作日志配置接口
OperationLogConfigService operationLogConfigService = Spring.getBean(OperationLogConfigService.class);
//操作日志接口
OperationlogService operationlogService = Spring.getBean(OperationlogService.class);
synchronized (OperationLogDataThread.class) {
//将map转成对应的实体
Operationlogconfig config = new Operationlogconfig();
config.setId(MD5Util.md5Encode(rule));
//判断是否存在
Operationlogconfig dbConfig = operationLogConfigService.queryById(config.getId());
if (dbConfig == null) {
//添加
config.setMenuName(apiName);
config.setOperationName(operationName);
config.setCount(1L);
config.setEnable(EnableEnum.UNABLE.getCode());
config.setRule(rule);
//添加
operationLogConfigService.add(config);
} else {
//修改数据表中的数据
Long count = dbConfig.getCount();
if (count >= Long.MAX_VALUE) {
count = 0L;
}
dbConfig.setCount(count + 1);
if (StringUtil.isNullOrEmpty(dbConfig.getMenuName())) {
dbConfig.setMenuName(apiName);
}
if (StringUtil.isNullOrEmpty(dbConfig.getOperationName())) {
dbConfig.setOperationName(operationName);
}
operationLogConfigService.update(dbConfig);
}
//查询配置
Operationlogconfig operationlogconfig = operationLogConfigService.queryById(config.getId());
if (null == operationlogconfig) {
log.error("config is null");
return;
}
//不记日志
if (operationlogconfig.getEnable() != EnableEnum.ENABLE.getCode()) {
//log.warn("Do not record operationlog");
return;
}
Operationlog info = new Operationlog();
info.setId(id);
info.setCode(code);
info.setHttpStatus(httpStatus);
info.setParameter(parameter);
info.setCharacterEncoding(characterEncoding);
info.setOperationLogConfigId(operationlogconfig.getId());
info.setRequestURI(requestURI);
info.setCostTime(costTime);
info.setIpAddress(ipAddress);
info.setMethod(method);
info.setOperationUserId(operationUserId);
info.setOperationUserName(operationUserName);
operationlogService.add(info);
}
}
}
5895

被折叠的 条评论
为什么被折叠?



