packagecom.pantech.boot.module.log.serviceimpl;importcom.pantech.boot.common.systemlog.SystemException;importcom.pantech.boot.common.systemlog.util.ExceptionInformation;importcom.pantech.boot.common.systemlog.util.IpAddress;importcom.pantech.boot.module.log.entity.SystemExceptionLogEntity;importcom.pantech.boot.module.log.entity.SystemOperationLogEntity;importcom.pantech.boot.module.log.repository.SystemExceptionLogRepository;importcom.pantech.boot.module.log.service.SystemExceptionLogService;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;importjava.util.List;/***@author肖政宇
* @date 2019-10-29 17:06
* 说明:系统异常记录*/@Servicepublic class SystemExceptionLogServiceImpl implementsSystemExceptionLogService {private final Logger logger = LoggerFactory.getLogger(SystemExceptionLogServiceImpl.class);privateSystemExceptionLogRepository repository;privateIpAddress ipAddress;
@Autowiredpublic voidsetRepository(SystemExceptionLogRepository repository) {this.repository =repository;
}
@Autowiredpublic voidsetIpAddress(IpAddress ipAddress) {this.ipAddress =ipAddress;
}/*** 保存一条系统异常
*
*@paramsystemExceptionLog - 异常信息*/@OverridepublicSystemExceptionLogEntity save(SystemExceptionLogEntity systemExceptionLog) {returnrepository.save(systemExceptionLog);
}/*** 用于手动添加异常日志
*
*@parame - 异常类型*/@OverridepublicSystemExceptionLogEntity exceptionLog(Exception e) {/*** 1、解析异常信息*/
//获取异常栈首个元素,用以解析异常部分信息
StackTraceElement stackTraceElement = e.getStackTrace()[0];//异常类型
String exceptionType =e.toString();//异常抛出于某个类
String className =stackTraceElement.getClassName();//异常抛出于某个方法
String methodName =stackTraceElement.getMethodName();//异常抛出于第几行
int lineNumber =stackTraceElement.getLineNumber();//异常抛出地点详细信息
String throwPlace = className + "." + methodName + "[" + lineNumber + "]";//异常详细信息
String content =ExceptionInformation.getExceptionInformation(e);
String[] con= content.split("\n");if (con.length > 50) {//保存前50行
StringBuilder stringBuilder = newStringBuilder();for (int i = 0; i < 50; i++) {
stringBuilder.append(con[i]);
stringBuilder.append("\n");
}
content=stringBuilder.toString();
}//ip地址
String ip =ipAddress.getIpAddress();/*** 2、保存异常信息到数据库*/SystemExceptionLogEntity systemExceptionLog= newSystemExceptionLogEntity();
systemExceptionLog.setExceptionType(exceptionType);
systemExceptionLog.setIpAddress(ip);
systemExceptionLog.setThrowPlace(throwPlace);
systemExceptionLog.setContent(content);return this.save(systemExceptionLog);
}
}