实现了平常数据存mysql。日志数据存MongoDB的功能
2018.5.16更新 添加了按日期时间段的查询,更正了title查询,修改了返回值为时间格式
一、日志的bean类
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.mapping.Document;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
@Document(collection = "LoggerInfo")
@CompoundIndexes(
@CompoundIndex(name = "title", def = "{ title : 1}"))
public class LoggerInfo {
private static final long serialVersionUID = 4495390935587105239L;
public String title;
public Date createdate;
public String createdatestr;
public Object[] arguments;
public String targetName;
public String methodName;
public Object result;
public String ip;
public String getCreatedatestr() {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(this.createdate);
}
public void setCreatedatestr(String createdatestr) {
this.createdatestr = createdatestr;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getCreatedate() throws ParseException {
System.out.println(createdate);
return new Date();
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
public Object[] getArguments() {
return arguments;
}
public void setArguments(Object[] arguments) {
this.arguments = arguments;
}
public String getTargetName() {
return targetName;
}
public void setTargetName(String targetName) {
this.targetName = targetName;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public LoggerInfo(String title, Date createdate, Object[] arguments, Object result , String targetName, String methodName, String ip){
this.title = title;
this.createdate = createdate;
this.arguments = arguments;
this.targetName = targetName;
this.methodName = methodName;
this.result = result;
this.ip = ip;
}
}
二、service层
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
/*@Service("mongoUserService")*/
@Service
public class LoggerInfoService {
@Autowired
private LoggerInfoRepository mongoUserRepository;
public void addLoggerInfo(LoggerInfo loggerInfo){
mongoUserRepository.addLoggerInfo(loggerInfo);
}
public List getloggerInfo(String title){
return mongoUserRepository.getLoggerInfo(title);
}
public List getloggerinfobydate(String startdate,String enddate) {return mongoUserRepository.getLoggerBetweenTime(startdate,enddate);}
}
三、mapper层
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import sun.rmi.runtime.Log;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Repository
public class LoggerInfoRepository {
@Autowired
MongoTemplate mongoTemplate;
public List getLoggerInfo(String title){
Query query = new Query();
Criteria criteria = new Criteria();
criteria = Criteria.where("title").is(title);
query.addCriteria(criteria);
query.with(new Sort(Sort.Direction.DESC, "createdate"));
return mongoTemplate.find(query, LoggerInfo.class);
}
public List getLoggerBetweenTime(String startdate,String enddata){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date sdate=null,edate=null;
try {
sdate=sdf.parse(startdate);
edate=sdf.parse(enddata);
} catch (ParseException e) {
System.out.println("时间转换错误======");
e.printStackTrace();
}
Query query = new Query();
Criteria criteria = new Criteria();
if(sdate!=null && edate!=null){
criteria=Criteria.where("createdate").gte(sdate).lte(edate);
}
query.addCriteria(criteria);
return mongoTemplate.find(query,LoggerInfo.class);
}
public void addLoggerInfo(LoggerInfo loggerInfo){
mongoTemplate.insert(loggerInfo);
}
}
四、aop切面编程类
import com.lenovo.pcsd.bp.common.mongoDB.LoggerInfo;
import com.lenovo.pcsd.bp.common.mongoDB.LoggerInfoService;
import org.apache.log4j.Logger;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
@Aspect
@Component
public class LoggerInterceptor {
protected Logger log = (Logger) Logger.getLogger(this.getClass());
@Autowired
private LoggerInfoService loggerInfoService;
/**
* 环绕通知 记录服务调用次数 以及记录接口日志
*
* @param proceedingJoinPoint
* @return
* @throws Throwable
*/
@Around("execution(* com.lenovo.pcsd.bp.common.controller.*.*(..))")
public Object aroundMod(ProceedingJoinPoint proceedingJoinPoint)
throws Throwable {
Object result = null;
LoggerInfo loggerInfo;
String targetName = proceedingJoinPoint.getTarget().getClass()
.getName();
String methodName = proceedingJoinPoint.getSignature().getName();
System.out.println("方法名称:"+methodName);
Object[] args = proceedingJoinPoint.getArgs();
Class> targetClass =Class.forName(targetName);
Object[] argsrequest = proceedingJoinPoint.getArgs();
try {
// 执行目标方法
result = proceedingJoinPoint.proceed();
//记录正确的日志
if (methodName.startsWith("get")) {
System.err.println("get正确的日志不存数据库");
}else {
System.err.println("非get正确的日志存数据库");
loggerInfo = new LoggerInfo("正确日志",new Date(),args,result,targetName,methodName,"");
loggerInfoService.addLoggerInfo(loggerInfo);
}
} catch (Exception e) {
//记录错误的日志
String message = e.getMessage();
loggerInfo = new LoggerInfo("错误日志",new Date(),args,message,targetName,methodName,"");
loggerInfoService.addLoggerInfo(loggerInfo);
e.printStackTrace();
System.err.println("错误的日志");
} finally {
}
return result;
}
}
五、MongoDB配置类
import com.mongodb.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import java.util.Arrays;
@Configuration
@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@ComponentScan
@EnableMongoRepositories
public class MongoDataSourceConfig extends AbstractMongoConfiguration{
@Value("${mongo.database}")
private String dbname;
@Value("${mongo.host}")
private String dbhost;
@Value("${mongo.port}")
private String dbport;
@Value("${mongo.username}")
private String username;
@Value("${mongo.password}")
private String password;
@Override
protected String getDatabaseName() {
return this.dbname;
}
public MongoDataSourceConfig(){
if(null == dbport || "".equalsIgnoreCase(dbport.trim())){
dbport = "27017";
}
}
@Override
@Bean(name = "mongods")
public Mongo mongo() throws Exception {
ServerAddress serverAdress = new ServerAddress(dbhost, Integer.valueOf(dbport));
MongoCredential credential = MongoCredential.createCredential(username, dbname , password.toCharArray());
//Do not use new Mongo(), is deprecated.
Mongo mongo = new MongoClient(serverAdress, Arrays.asList(credential));
mongo.setWriteConcern(WriteConcern.SAFE);
return mongo;
}
}
六、yml文件
mongo.host: 10.120.112.96
mongo.port: 27017
#这是测试库
mongo.username: test
mongo.password: test
mongo.database: test
mongo.username: root
mongo.password: 123456
mongo.database: admin
七、测试类
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.List;
@RestController
public class LoggerController {
@Autowired
private LoggerInfoService loggerInfoService;
@GetMapping("LoggerInfo")
@ApiOperation(value = "LoggerInfo测试",notes = "LoggerInfo测试")
public List getLoggerInfo(@RequestParam("title")String title){
List loggerInfo = loggerInfoService.getloggerInfo(title);
System.out.println(loggerInfo);
return loggerInfo;
}
@GetMapping("getLoggerByDate")
@ApiOperation(value = "根据时间范围查询日志",notes = "根据时间范围查询日志")
public List getInfoByDate(@RequestParam("startdate") String startdate , @RequestParam("enddate") String enddate){
List loggerInfos=loggerInfoService.getloggerinfobydate(startdate,enddate);
System.out.println(loggerInfos);
return loggerInfos;
}
}
八、pom文件
org.springframework.boot
spring-boot-starter-data-mongodb
org.springframework.data
spring-data-mongodb
1.10.9.RELEASE