操作日志逻辑及结构实现调整

This commit is contained in:
fanghongchao
2018-11-28 11:18:21 +08:00
parent 93b03e14f7
commit b4e2cb5f37
9 changed files with 231 additions and 114 deletions
@@ -0,0 +1,69 @@
package com.gzzn.omms.adminapi.config;
import java.net.InetAddress;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticsearchConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchConfig.class);
/**
* elk集群地址
*/
@Value("${elasticsearch.ip}")
private String hostName;
/**
* 端口
*/
@Value("${elasticsearch.port}")
private String port;
/**
* 集群名称
*/
@Value("${elasticsearch.cluster.name}")
private String clusterName;
/**
* 连接池
*/
@Value("${elasticsearch.pool}")
private String poolSize;
/**
* Bean name default 函数名字
*
* @return
*/
@Bean(name = "transportClient")
public TransportClient transportClient() {
LOGGER.info("Elasticsearch初始化开始。。。。。");
TransportClient transportClient = null;
try {
// 配置信息
Settings esSetting = Settings.builder()
.put("cluster.name", clusterName) // 集群名字
// .put("client.transport.sniff", true)// 增加嗅探机制,找到ES集群 只有在存在集群是才能开启嗅探
.put("thread_pool.search.size", Integer.parseInt(poolSize))// 增加线程池个数,暂时设为5
.build();
// 配置信息Settings自定义
transportClient = new PreBuiltTransportClient(esSetting);
TransportAddress transportAddress = new TransportAddress(InetAddress.getByName(hostName), Integer.valueOf(port));
transportClient.addTransportAddresses(transportAddress);
} catch (Exception e) {
LOGGER.error("elasticsearch TransportClient create error!!", e);
}
return transportClient;
}
}
@@ -4,6 +4,7 @@ import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@@ -25,6 +26,7 @@ import com.gzzn.omms.adminapi.domain.primary.entity.settings.Uisettings;
import com.gzzn.omms.adminapi.dto.ResponseDto;
import com.gzzn.omms.adminapi.dto.settings.UisettingsDto;
import com.gzzn.omms.adminapi.dto.settings.convert.UisettingsConvert;
import com.gzzn.omms.adminapi.enums.CommCode;
import com.gzzn.omms.adminapi.service.IUserService;
import com.gzzn.omms.adminapi.utils.CommonUtils;
import com.gzzn.omms.adminapi.utils.ElasticsearchUtil;
@@ -35,13 +37,13 @@ public class UISettingsController {
private final Logger logger = LoggerFactory.getLogger(UISettingsController.class);
/**
* 测试索引
* 操作日志索引
*/
private final String INDEX_NAME = "oplog";
/**
* 类型
* 操作日志类型
*/
private String ES_TYPE = "oplog";
private final String OPLOG_ES_TYPE = "_doc";
/**
* UI设置接口
@@ -109,13 +111,20 @@ public class UISettingsController {
Uisettings uisettings = uisettingsConvert.uisettingsDtoToUisettings(uisettingsDto);
Uisettings oldUisettings = null;
if(StringUtils.isEmpty(uisettings.getId()))
Byte optType = CommCode.LOG_OPT_TYPE_ADD;
String oldData = "";
if(!StringUtils.isEmpty(uisettings.getId())){
oldUisettings = uisettingsDao.findById(uisettings.getId());
}
if(null==oldUisettings)
{
uisettings.setId(CommonUtils.getUUID32()); //uuid自动生成
}else{
oldUisettings = uisettingsDao.findByUserid(uisettings.getId());
oldData = JsonUtil.getString(oldUisettings);
optType = CommCode.LOG_OPT_TYPE_UPDATE;
}
uisettings.setUserid(userService.getCurrentUserId());
uisettings = uisettingsDao.save(uisettings);
try {
@@ -123,16 +132,20 @@ public class UISettingsController {
ElasticsearchUtil.createIndex(INDEX_NAME);
}
UserOptLog oplog = new UserOptLog(null, "更新或者新增用户设置", userService.getCurrentUserId(),userService.getCurrentUserName(),
userService.getCurrentUserRealName(), userService.getUserRemoteAddress().getHostString(),
this.getClass().getMethod("saveUISettings", UisettingsDto.class).getAnnotation(ApiOperation.class).value());
InetSocketAddress remoteAddress = userService.getUserRemoteAddress();
UserOptLog oplog = new UserOptLog(userService.getCurrentUserId(),userService.getCurrentUserName(),
userService.getCurrentUserRealName(), null==remoteAddress?"未知":userService.getUserRemoteAddress().getHostString(),
System.currentTimeMillis());
oplog.setOpt_type(optType);
oplog.setLog_type(CommCode.LOG_TYPE_UISETTING);
oplog.setSummary("保存用户{"+userService.getCurrentUserName()+"}的UI设置");
//设置日志类容 jsonarry 历史及最新的
JSONObject log_content = new JSONObject();
log_content.put("newData", JsonUtil.getString(uisettings));
log_content.put("oldData", null==oldUisettings?"":JsonUtil.getString(oldUisettings));
log_content.put("oldData", oldData);
oplog.setLog_content(log_content.toString());
JSONObject logJson = JSONObject.parseObject(JsonUtil.getString(oplog));
String id = ElasticsearchUtil.addData(logJson, INDEX_NAME, ES_TYPE);
String id = ElasticsearchUtil.addData(logJson, INDEX_NAME, OPLOG_ES_TYPE);
logger.info("保存用户设置UI操作日志至Elatsticsearch成功:id="+id);
} catch (Exception e) {
logger.error("保存用户设置UI操作日志至Elatsticsearch异常:", e);
@@ -9,28 +9,27 @@ import lombok.ToString;
@NoArgsConstructor
public class UserOptLog {
private String id;
/**
* 标题
*/
private String title;
/**
* 应用名
*/
private String app_name = "adminapi";
private String app_name = "cdairport";
/**
* 模块名
*/
private String model_name;
private String model_name = "adminapi";
/**
* 日志详情
*/
private String log_content;
/**
* 操作日志类别 固定为oplog
* 业务类型 1:登录 2:退出 3:修改用户设置
*
*/
private String log_type = "oplog";
private Byte log_type;
/**
* 操作类别 0:新增 1:修改 2:删除
*/
private Byte opt_type;
/**
* 操作用户id
*/
@@ -52,103 +51,126 @@ public class UserOptLog {
*/
private String summary;
/**
* 操作时间(时间戳-毫秒)
*/
private Long log_datetime;
public UserOptLog() {
}
/**
*
* @param title 标题
* @param model_name 模块名
* @param user_id 操作用户id
* @param user_name 操作用户登录名
* @param real_name 操作用户真实姓名
* @param login_ip 用户登录IP
* @param summary 操作描述
* @param log_datetime 操作时间(时间戳-毫秒)
*/
public UserOptLog(String title, String model_name, String user_id,
String user_name, String real_name, String login_ip, String summary) {
public UserOptLog(String user_id, String user_name, String real_name,
String login_ip, Long log_datetime) {
super();
this.title = title;
this.model_name = model_name;
this.user_id = user_id;
this.user_name = user_name;
this.real_name = real_name;
this.login_ip = login_ip;
this.summary = summary;
this.log_datetime = log_datetime;
}
@Override
public String toString() {
return "UserOptLog [id=" + id + ", title=" + title + ", app_name="
+ app_name + ", model_name=" + model_name + ", log_content="
+ log_content + ", log_type=" + log_type + ", user_id="
+ user_id + ", user_name=" + user_name + ", real_name="
+ real_name + ", login_ip=" + login_ip + ", summary=" + summary
+ "]";
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
return "UserOptLog [app_name=" + app_name + ", model_name="
+ model_name + ", log_content=" + log_content + ", log_type="
+ log_type + ", opt_type=" + opt_type + ", user_id=" + user_id
+ ", user_name=" + user_name + ", real_name=" + real_name
+ ", login_ip=" + login_ip + ", summary=" + summary + "]";
}
public String getApp_name() {
return app_name;
}
public void setApp_name(String app_name) {
this.app_name = app_name;
}
public String getModel_name() {
return model_name;
}
public void setModel_name(String model_name) {
this.model_name = model_name;
}
public String getLog_content() {
return log_content;
}
public void setLog_content(String log_content) {
this.log_content = log_content;
}
public String getLog_type() {
public Byte getLog_type() {
return log_type;
}
public void setLog_type(String log_type) {
public void setLog_type(Byte log_type) {
this.log_type = log_type;
}
public Byte getOpt_type() {
return opt_type;
}
public void setOpt_type(Byte opt_type) {
this.opt_type = opt_type;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getReal_name() {
return real_name;
}
public void setReal_name(String real_name) {
this.real_name = real_name;
}
public String getLogin_ip() {
return login_ip;
}
public void setLogin_ip(String login_ip) {
this.login_ip = login_ip;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public Long getLog_datetime() {
return log_datetime;
}
public void setLog_datetime(Long log_datetime) {
this.log_datetime = log_datetime;
}
}
@@ -20,5 +20,5 @@ public interface UisettingsDao extends CrudRepository<Uisettings,String>{
//保存
Uisettings save(Uisettings uisettings);
Uisettings findByUserid(String userid);
Uisettings findById(String id);
}
@@ -6,6 +6,8 @@ import io.swagger.annotations.ApiModelProperty;
@ApiModel(value="UisettingsDto",description="UI设置Dto")
public class UisettingsDto {
@ApiModelProperty(value="UI的主键id:存在则进行修改 否则 进行新增",example="1")
private String id;
@ApiModelProperty(value="用户id",example="1")
private String userid;
@@ -51,5 +53,13 @@ public class UisettingsDto {
this.userid = userid;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
@@ -0,0 +1,30 @@
package com.gzzn.omms.adminapi.enums;
public class CommCode {
/**
* 操作日志类别 新建
*/
public static final Byte LOG_OPT_TYPE_ADD = 0;
/**
* 操作日志类别 修改
*/
public static final Byte LOG_OPT_TYPE_UPDATE = 1;
/**
* 操作日志类别 删除
*/
public static final Byte LOG_OPT_TYPE_DELETE = 2;
/**
* 日志类别 登录
*/
public static final Byte LOG_TYPE_LOGIN = 1;
/**
* 日志类别 登出
*/
public static final Byte LOG_TYPE_LOGOUT = 2;
/**
* 日志类别 修改用户设置
*/
public static final Byte LOG_TYPE_UISETTING = 3;
}
@@ -45,20 +45,14 @@ public class ExceptionAspect {
MDC.clear();
MDC.put("request_id", getRequestId(request));
//url
try {
logger.info("request={url={},method={},content_type={},body={},params={},remoteip={}}",
request.getRequestURL(),
request.getMethod(),
request.getContentType(),
JsonUtil.getString(joinPoint.getArgs()),
getRequestParams(wrapperRequest),
request.getRemoteAddr()
);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.info("request={url={},method={},content_type={},body={},params={},remoteip={}}",
request.getRequestURL(),
request.getMethod(),
request.getContentType(),
JsonUtil.getString(joinPoint.getArgs()),
getRequestParams(wrapperRequest),
request.getRemoteAddr()
);
}
@@ -1,7 +1,5 @@
package com.gzzn.omms.adminapi.utils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -21,17 +19,14 @@ import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
@@ -43,47 +38,16 @@ public class ElasticsearchUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchUtil.class);
/**
* elk集群地址
*/
@Value("${elasticsearch.ip}")
private String hostName;
/**
* 端口
*/
@Value("${elasticsearch.port}")
private String port;
/**
* 集群名称
*/
@Value("${elasticsearch.cluster.name}")
private String clusterName;
/**
* 连接池
*/
@Value("${elasticsearch.pool}")
private String poolSize;
@Autowired
private TransportClient transportClient;
private static TransportClient client;
/**
* @PostContruct是spring框架的注解 spring容器初始化的时候执行该方法
*/
@SuppressWarnings("resource")
@PostConstruct
public void init() {
// client = this.transportClient;
try {
Settings settings = Settings.builder()
.put("cluster.name", clusterName) //集群名字
.put("client.transport.sniff", true)//增加嗅探机制,找到ES集群
.put("thread_pool.search.size", Integer.parseInt(poolSize))//增加线程池个数,暂时设为5
.build();
client = new PreBuiltTransportClient(settings)
.addTransportAddresses(new TransportAddress(InetAddress.getByName(hostName), Integer.valueOf(port)));
} catch (UnknownHostException e) {
e.printStackTrace();
}
client = this.transportClient;
}
/**
@@ -2,27 +2,42 @@ package com.gzzn.omms.adminapi.utils;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
public class JsonUtil {
public static String getString(Object object) throws JsonProcessingException
private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
public static String getString(Object object)
{
ObjectMapper mapper = new ObjectMapper();
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
java.lang.String jsonStr = ow.writeValueAsString(object);
java.lang.String jsonStr = null;
try {
ObjectMapper mapper = new ObjectMapper();
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
jsonStr = ow.writeValueAsString(object);
} catch (JsonProcessingException e) {
logger.error("获取json串异常:", e);
e.printStackTrace();
}
return jsonStr;
}
public static <T> T getObject(String str,Class<T> valueType) throws JsonParseException, JsonMappingException, IOException
public static <T> T getObject(String str,Class<T> valueType)
{
ObjectMapper mapper = new ObjectMapper();
T obj = mapper.readValue(str, valueType);
T obj = null;
try {
ObjectMapper mapper = new ObjectMapper();
obj = mapper.readValue(str, valueType);
} catch (IOException e) {
logger.error("json转为Class异常:", e);
e.printStackTrace();
}
return obj;
}