This commit is contained in:
Rinjae
2025-09-05 18:57:45 +09:00
commit aacc1a389e
1229 changed files with 167963 additions and 0 deletions
@@ -0,0 +1,42 @@
package com.eactive.eai.common.logger;
public class CustomStringBuffer {
private StringBuffer sb ;
private String DELEMITER ;
public CustomStringBuffer() {
this.sb = new StringBuffer();
this.DELEMITER = "#|@";
}
public CustomStringBuffer(String delemiter) {
this.sb = new StringBuffer();
this.DELEMITER = delemiter;
}
public CustomStringBuffer appendAndDelimeter(String data){
sb.append(data).append(DELEMITER);
return this;
}
public CustomStringBuffer appendAndDelimeter(int data){
sb.append(Integer.toString(data)).append(DELEMITER);
return this;
}
public CustomStringBuffer append(String data){
sb.append(data);
return this;
}
public CustomStringBuffer append(int data){
sb.append(Integer.toString(data));
return this;
}
public String toString(){
return sb.toString();
}
// public static void main(String[] args){
// CustomStringBuffer sb = new CustomStringBuffer();
// sb.appendAndDelimeter("ABD").append("KKK");
// System.out.println(sb.toString());
// }
}
@@ -0,0 +1,212 @@
package com.eactive.eai.common.logger;
import java.util.Properties;
import com.eactive.eai.adapter.ElinkAdapter;
import com.eactive.eai.adapter.ElinkAdapterFactory;
import com.eactive.eai.common.dao.DAOFactory;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.message.EAIMessageKeys;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.MessageUtil;
import org.apache.commons.lang.StringUtils;
/**
* 1. 기능 : EAI에서 처리되는 모든 On-Line 거래를 데이터베이스에 로깅하기 위한 운영관리 Logger Sender
* 2. 처리 개요 :
* - Processor에서 받은 거래로그 정보를 저장
* 3. 주의사항
*
* @author :
* @version : v 3.0.0
* @see :
* @since :JDK v1.5.0
*/
public class DBLogTransactionLogger implements TransactionLogger {
// 거래 로그 Count
private int logCount;
// 에러 로그 Count
private int errCount;
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
/**
* 1. 기능 : EAI 거래 로그 Count를 반환
* 2. 처리 개요 :
* - EAI 거래 로그 Count를 반환한다.
* 3. 주의사항
*
* @return int 거래 로그 Count
**/
public int logCount() {
return logCount;
}
/**
* 1. 기능 : EAI 에러 로그 Count를 반환
* 2. 처리 개요 :
* - EAI 거래 에러 Count를 반환한다.
* 3. 주의사항
*
* @return int 에러 로그 Count
**/
public int errCount() {
return errCount;
}
/**
* 1. 기능 : 거래 로그 및 에러 로그 초기화
* 2. 처리 개요 :
* - 거래 및 에러 로그를 초기화 한다.
* 3. 주의사항
*
**/
public void resetCount() {
logCount = 0;
errCount = 0;
}
private byte[] callAdapter(String adapterGroupName, Properties prop, Object message)
throws java.lang.Exception {
byte[] resBytes;
try {
ElinkAdapterFactory factory = ElinkAdapterFactory.newInstance();
ElinkAdapter adapter = null;
adapter = factory.getElinkAdapter(com.eactive.eai.adapter.Keys.TYPE_NET2);
if(prop==null) {
prop = new Properties();
}
if(prop.getProperty("ADAPTER_GROUP_NAME") == null) {
prop.setProperty("ADAPTER_GROUP_NAME", adapterGroupName);
}
resBytes = (byte[])adapter.callService(adapterGroupName, prop, message, prop);
} catch(Exception e) {
logger.error("callSocketAdapter error", e);
//throw new Exception(ExceptionUtil.getErrorCode(e, SOCK_CONTROL_ERROR));
throw e;
}
return resBytes;
}
private byte[] getItsmSMSMesage(EAIMessage eaimessage) {
byte[] itsmSMSMessage = null;
StringBuilder sb = new StringBuilder();
try {
// make message from EAIMessage
sb.append(eaimessage.getEAISvcCd());
itsmSMSMessage = sb.toString().getBytes();
}
catch(Exception e) {
itsmSMSMessage = sb.toString().getBytes();
}
return itsmSMSMessage;
}
/**
* 1. 기능 : 로깅 정보를 로그 Queue로 전달
* 2. 처리 개요 :
* - 로깅 정보를 로그 Queue로 전달
* - 실시간 거래 정보 통계를 위해 EAIServiceMonitor로 전달
* 3. 주의사항
*
* @param message EAIMessage
* @param prop logging 관련 Properties
* @exception EAILogException
**/
public void log(EAIMessage message, Properties prop) throws EAILogException {
++logCount;
int svcLogLvl = message.getSvcLogLvl();
String svcTsmtUsgTp = message.getSvcTsmtUsgTp();
int logPssSno = message.getLogPssSno();
boolean isLogging = false;
String guidLogPrefix = "DBLogTransactionLogger] GUID["
+ message.getMapper().getGuid(message.getStandardMessage())
+ "] UUID[" + message.getSvcOgNo() + "] ";
try {
// Direct DB Logging
String logType = "DB";
String setLogType = PropManager.getInstance().getProperty("LOG_TYPE");
if(setLogType != null) {
logType = setLogType;
}
if("DB".equals(logType)) {
insertLog(message, prop);
}
else {
EAIFileLogger.getInstance().setLog(message, prop);
}
//---------------------------------------------------->
// ITSM ERROR Log 전송
// 템플릿만 남겨두고, 나머지는 사이트에 맞게 수정 필요함.
//---------------------------------------------------->
boolean itsmEnabled = false;
if((itsmEnabled) && !MessageUtil.checkRspErrCd(message.getRspErrCd())) {
if(logger.isDebug()) {
logger.debug(guidLogPrefix + " ITSM Error Message Notify! ");
}
if(( EAIMessageKeys.SYNC_SVC.equals(svcTsmtUsgTp) && logPssSno == 400 ) ||
( EAIMessageKeys.ASYNC_SVC.equals(svcTsmtUsgTp) && (logPssSno == 200 || logPssSno == 400))) {
String itsmErrorAdapterName = "";
itsmErrorAdapterName = PropManager.getInstance().getProperty("ITSM_CONFIG","ADAPTER_GROUP_NAME_ERROR"); /* Properties 추가 및 어뎁터 등록 */
if (logger.isDebug()) {
logger.debug(guidLogPrefix + " ITSM ERROR Send Message Adapter Name[" + itsmErrorAdapterName + "]");
}
if(itsmErrorAdapterName != null && itsmErrorAdapterName.length() > 0) {
byte[] itsmSMSMessage = getItsmSMSMesage(message); /* ITSM 전송 메시지 포맷 결정 */
Properties itsmProp = new Properties();
callAdapter(itsmErrorAdapterName, itsmProp, itsmSMSMessage);
}
}
}
} catch(Exception e) {
if (logger.isError()) logger.error(guidLogPrefix + " ITSM ERROR Send ERROR " + e.getMessage(),e);
errCount++;
//throw new EAILogException(ExceptionUtil.getErrorCode(e, "RECEAICLG005"));
}
}
public static void insertLog(EAIMessage eaiMessage, Properties prop) throws EAILogException {
String guidLogPrefix = "DBLogTransactionLogger] GUID["+ eaiMessage.getMapper().getGuid(eaiMessage.getStandardMessage())
+"] UUID["+eaiMessage.getSvcOgNo()+"] ";
try {
if (EAIDBLogControl.isEnable()){
try {
EAILogDAO dao = ApplicationContextProvider.getContext().getBean(EAILogDAO.class);
dao.addEAISvcLog(eaiMessage, prop);
} catch(Exception e) {
if (logger.isError()) logger.error(guidLogPrefix +" insertLog DB ERROR. - " + e.getMessage(),e);
// DB Connection Error일 경우에만 설정하도록 수정
String message = e.getMessage();
// 오류 메시지 추가 - Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
// 오류 메시지 추가 - Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
if( "ConnectionError".equals(message) || StringUtils.contains(message, "JDBCConnectionException")
|| StringUtils.contains(message, "Unable to acquire JDBC Connection") ) {
EAIDBLogControl.setEnable(false);
}
//file log
EAIFileLogger.getInstance().setLog(eaiMessage, prop);
throw e;
}
}
else{
//file log
EAIFileLogger.getInstance().setLog(eaiMessage, prop);
}
} catch(Exception e) {
if (logger.isError()) logger.error(guidLogPrefix + " insertLog ERROR. - " + e.getMessage(), e);
throw new EAILogException("insertLog ERROR."+ e.getMessage());
}
}
}
@@ -0,0 +1,62 @@
package com.eactive.eai.common.logger;
import com.eactive.eai.common.dao.DAOFactory;
import com.eactive.eai.common.logger.async.HttpAdapterExtraLogH2Factory;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.common.util.Logger;
/**
* 1. 기능 : DB 장애 상태 관리
* 2. 처리 개요 :
* 3. 주의사항
*/
public class EAIDBLogControl {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
private static boolean isEnable = true;
private EAIDBLogControl() {
}
public static synchronized boolean isEnable() {
return isEnable;
}
public static synchronized void setEnable(boolean enable) {
if (isEnable == enable) return ;
isEnable = enable;
if (!enable){
//thread 기동
Runnable runnable = new Runnable() {
public void run() {
while(true) {
try {
//db check
EAILogDAO dao = ApplicationContextProvider.getContext().getBean(EAILogDAO.class);
boolean result = dao.getCheck();
if (result){
setEnable(result);
// 25.04.29 안해도 정상적으로 Header 정보 저장됨 확인
// 있으면 오히려 NoClassDefFoundError Exception 발생
// HttpAdapterExtraLogH2Factory.getInstance().closeSessionFactory();
break;
}
} catch(Throwable t) {
logger.warn("setEnable", t);
}
try {
Thread.sleep(1000L);
} catch(InterruptedException e) {
logger.warn("sleep", e);
}
}
}
};
Thread t = new Thread(runnable);
t.setName("DBChecker-Launcher");
t.start();
}
}
}
@@ -0,0 +1,900 @@
package com.eactive.eai.common.logger;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import com.eactive.eai.adapter.AdapterGroupVO;
import com.eactive.eai.adapter.AdapterManager;
import com.eactive.eai.agent.encryption.EncryptionManager;
import com.eactive.eai.common.dao.DAOException;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.message.EAIMessageKeys;
import com.eactive.eai.common.message.MessageType;
import com.eactive.eai.common.message.ServiceMessage;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.LogKeys;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.MessageUtil;
import com.eactive.eai.common.util.NullControl;
import com.eactive.eai.common.util.StringUtil;
import com.eactive.eai.transformer.layout.Item;
import com.eactive.eai.transformer.layout.Layout;
import com.eactive.eai.transformer.transform.Transform;
import com.eactive.eai.transformer.transform.TransformManager;
import com.eactive.eai.transformer.util.IConv;
import com.eactive.eai.util.HexaConverter;
import com.ext.eai.common.stdmessage.STDMessageKeys;
/**
* 1. 기능 : DAO 객체를 생성하기 위한 Factory 클래스
* 2. 처리 개요 : DAO 객체를 생성하는 Factory 메서드를 정의한다.
* * -
* 3. 주의사항
*
* @author :
* @version : v 1.0.0
* @see : 관련 기능을 참조
* @since :
* :
*/
public class EAIFileLogger
{
private static EAIFileLogger instance ;
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
static Logger tranLogger = Logger.getLogger(Logger.LOGGER_TRAN);
private static final String DELIMITER = "#|@";
private static final String EOL = "EOL$$;";
private EAIFileLogger() {
}
/**
* 1. 기능 : EAI File Logger 객체를 생성 반환하는 메서드
* 2. 처리 개요 : EAI File Logger 객체를 생성 반환한다.
* -
* 3. 주의사항
*
* @return DAOFactory
**/
public static EAIFileLogger getInstance() {
if (instance == null){
instance = new EAIFileLogger();
}
return instance;
}
/**
* 1. 기능 : 메시지의 Type이 EBCDIC인지 판단
* 2. 처리 개요 :
* - 로그시퀀스에 맞는 Adapter의 메시지 type을 비교
* - EBC인지 판별
* 3. 주의사항
*
* @param srcIfType String
* @param tgtIfType String
* @param logPssSno int
* @param srcAdapterMsgType String
* @param tgtAdapterMsgType String
* @return boolean
**/
public boolean isEBC(String srcIfType, String tgtIfType, int logPssSno,
String srcAdapterMsgType, String tgtAdapterMsgType) {
boolean isEBCDIC = false;
// SS. SA Type
if(logPssSno == 100) {
if( "EBC".equals(srcAdapterMsgType) ) {
isEBCDIC = true;
}
}
else if(logPssSno == 200) {
if( "EBC".equals(tgtAdapterMsgType) ) {
isEBCDIC = true;
}
}
else if(logPssSno == 300) {
if (EAIMessageKeys.ASYNC_SVC.equals(srcIfType) &&
EAIMessageKeys.ASYNC_SVC.equals(tgtIfType)) {
if( "EBC".equals(srcAdapterMsgType) ) {
isEBCDIC = true;
}
}
else {
if( "EBC".equals(tgtAdapterMsgType) ) {
isEBCDIC = true;
}
}
}
// 400
else if(logPssSno == 400) {
if (EAIMessageKeys.ASYNC_SVC.equals(srcIfType) &&
EAIMessageKeys.ASYNC_SVC.equals(tgtIfType)) {
if( "EBC".equals(tgtAdapterMsgType) ) {
isEBCDIC = true;
}
}
else {
if( "EBC".equals(srcAdapterMsgType) ) {
isEBCDIC = true;
}
}
}
// 900
else {
if (EAIMessageKeys.ASYNC_SVC.equals(srcIfType) &&
EAIMessageKeys.ASYNC_SVC.equals(tgtIfType)) {
if( "EBC".equals(tgtAdapterMsgType) ) {
isEBCDIC = true;
}
}
else {
if( "EBC".equals(srcAdapterMsgType) ) {
isEBCDIC = true;
}
}
}
return isEBCDIC;
}
public boolean isUTF8(String srcIfType, String tgtIfType, int logPssSno,
String srcAdapterMsgEncode, String tgtAdapterMsgEncode) {
boolean isUTF = false;
if (logger.isInfo()) {
logger.info(String.format("EAIFileLogger] isUTF8 %s %s %s %s %s", srcIfType, tgtIfType, logPssSno, srcAdapterMsgEncode, tgtAdapterMsgEncode));
}
String adapterMsgEncode = "";
// SS. SA Type
if(logPssSno == 100) {
adapterMsgEncode = srcAdapterMsgEncode;
}
else if(logPssSno == 200) {
adapterMsgEncode = tgtAdapterMsgEncode;
}
else if(logPssSno == 300) {
if (EAIMessageKeys.ASYNC_SVC.equals(srcIfType) &&
EAIMessageKeys.ASYNC_SVC.equals(tgtIfType)) {
adapterMsgEncode = srcAdapterMsgEncode;
}
else {
adapterMsgEncode = tgtAdapterMsgEncode;
}
}
// 400
else if(logPssSno == 400) {
if (EAIMessageKeys.ASYNC_SVC.equals(srcIfType) &&
EAIMessageKeys.ASYNC_SVC.equals(tgtIfType)) {
adapterMsgEncode = tgtAdapterMsgEncode;
}
else {
adapterMsgEncode = srcAdapterMsgEncode;
}
}
// 900
else {
if (EAIMessageKeys.ASYNC_SVC.equals(srcIfType) &&
EAIMessageKeys.ASYNC_SVC.equals(tgtIfType)) {
adapterMsgEncode = tgtAdapterMsgEncode;
}
else {
adapterMsgEncode = srcAdapterMsgEncode;
}
}
isUTF = StringUtils.equalsIgnoreCase(adapterMsgEncode, "UTF-8");
return isUTF;
}
protected String removeXMLHeaderAll(String xmlMsg) {
if(xmlMsg == null) {
return "";
}
else {
xmlMsg = xmlMsg.trim();
}
int sPos = xmlMsg.indexOf("<Individual>");
int ePos = xmlMsg.indexOf("</Individual>");
// 중간에 있는 경우 - CDATA 의 내용
if(sPos > -1 && ePos > -1) {
xmlMsg = xmlMsg.substring(sPos+12, ePos);
}
return xmlMsg;
}
// private String removeXMLRootItem(String xmlString, String rootItemName) {
// String prefix = "<" + rootItemName + ">";
// String suffix = "</" + rootItemName + ">";
//
// int s_idx = xmlString.indexOf(prefix);
// int e_idx = xmlString.indexOf(suffix);
// if (s_idx == -1 || e_idx == -1) {
// return xmlString;
// } else {
// return xmlString.substring(s_idx + prefix.length(), e_idx);
// }
// }
// private String addJsonRootItem(String jsonString, String rootItemName) {
// JSONObject value = (JSONObject)JSONValue.parse(jsonString);
// JSONObject root = new JSONObject();
// root.put(rootItemName, value);
// return root.toJSONString();
// }
// private String removeJsonRootItem(String jsonString, String rootItemName) {
// JSONObject value = (JSONObject)JSONValue.parse(jsonString);
// JSONObject sub = (JSONObject) value.get(rootItemName);
// return sub.toJSONString();
// }
/**
* 1. 기능 : EAI 서비스 로그 셋팅
* 2. 처리 개요 :
* - tran.log(EAI서비스로그) 로그값 셋팅
* 3. 주의사항
*
* @param message EAIMessage
* @exception DAOException
**/
public void setLog(EAIMessage message, Properties prop) throws Exception{
// 업무데이터 size 체크하여 업무데이터1,2에 insert하고
// addBwkDataSub(message) 호출 여부 결정
String apndBwkDataYn = "N"; //추가업무데이터 여부
int dayOfWeek = DatetimeUtil.getDayOfWeekNum(message.getMsgRcvTm());
// 개별메시지
// Object bizMsg = message.getBizMsg()[0];
// Object bizMsg = message.getExtMsg().getBizData()[0];
Object bizMsg = message.getStandardMessage().getBizData();
ServiceMessage svcMsg = message.getCurrentSvcMsg();
String bizMsgStr = "";
//transformer 적용
String svcTsmtUsgTp = message.getSvcTsmtUsgTp(); // 기동 Syunc/Async
String psvItfTp = svcMsg.getPsvItfTp(); // 수동 Syunc/Async
int logPssSno = message.getLogPssSno();
String rspErrCd = message.getRspErrCd();
// Duplication Error 방지를 위해
// 원 로그처리일련번호를 저장 : 2009.07.13
int orglogPssSno = logPssSno;
// int svcLogLvl = message.getSvcLogLvl();
boolean loggingBizData = true;
// if(svcLogLvl > 3) {
// loggingBizData = false;
// }
if (logger.isWarn()) logger.warn("EAIFileLogger] loggingBizData - " + loggingBizData);
// 복합거래인 경우 2X1,3X1 -> 200, 2X2,3X2 -> 300 처럼 처리한다.
if( (logPssSno > 200 && logPssSno < 300)
|| (logPssSno > 300 && logPssSno < 400) ) {
if( (logPssSno % 2) == 1) {
logPssSno = 200;
}
else {
logPssSno = 300;
}
}
// 업무테이터 처리
// 1. Get Source, Target Adapter Group Name
String srcAdapterGroupName = message.getSngSysItfTp();
String tgtAdapterGroupName = message.getCurrentSvcMsg().getPsvSysItfTp();
// 2. Get Source, Target Adapter GroupVO
AdapterManager adapterManager = AdapterManager.getInstance();
AdapterGroupVO srcAdapterGrpVO = adapterManager.getAdapterGroupVO(srcAdapterGroupName);
AdapterGroupVO tgtAdapterGrpVO = adapterManager.getAdapterGroupVO(tgtAdapterGroupName);
// 3. Get Source, Target Adapter Message Type
/*
String srcAdapterMsgType = srcAdapterGrpVO.getMessageType();
String tgtAdapterMsgType = tgtAdapterGrpVO != null ? tgtAdapterGrpVO.getMessageType() : "N/A";
*/
String srcAdapterMsgType = null;
String tgtAdapterMsgType = null;
//String srcAdptrMsgPtrnCd = null;
String tgtAdptrMsgPtrnCd = null;
String srcAdapterMsgEncode = null;
String tgtAdapterMsgEncode = null;
// String s = System.getProperty("os.name");
// if (s.indexOf("Window") < 0){
// srcAdptrMsgPtrnCd = srcAdapterGrpVO.getAdptrMsgPtrnCd();
if (srcAdapterGrpVO == null){
srcAdapterMsgType = MessageType.ASC;
srcAdapterMsgEncode = Charset.defaultCharset().name();
if (logger.isWarn()){
logger.warn("EAIFileLogger] Source Adapter null. eai service code="+message.getEAISvcCd());
}
}
else {
srcAdapterMsgType = srcAdapterGrpVO.getMessageType();
srcAdapterMsgEncode = StringUtils.defaultIfBlank(srcAdapterGrpVO.getMessageEncode(), Charset.defaultCharset().name());
}
if (tgtAdapterGrpVO == null){
tgtAdapterMsgType = MessageType.ASC;
tgtAdapterMsgEncode = Charset.defaultCharset().name();
if (logger.isWarn()){
logger.warn("EAIFileLogger] Target Adapter null. eai service code="+message.getEAISvcCd());
}
}
else{
tgtAdapterMsgType = tgtAdapterGrpVO.getMessageType();
tgtAdptrMsgPtrnCd = tgtAdapterGrpVO.getAdptrMsgPtrnCd();
tgtAdapterMsgEncode = StringUtils.defaultIfBlank(tgtAdapterGrpVO.getMessageEncode(), Charset.defaultCharset().name());
}
// }else{
// srcAdapterMsgType = MessageType.ASC;
// tgtAdapterMsgType = MessageType.ASC;
// }
String bwkData = "";
String addBwkData = "";
String refMsgID = "";
if(loggingBizData) {
//---------------------------------------------------
// LogMasking 을 위해 변환이 등록된 경우에만
// 변환을 통해 처리하도록 수정 : 20080827 DHLEE
//---------------------------------------------------
boolean isMasked = false;
boolean isMasking = false;
// 변환이 등록된 경우
if ("1".equals(svcMsg.getCnvEn())) {
TransformManager manager = TransformManager.getManager();
Transform info = null;
Layout l = null;
// AA - 요청변환에서
if (EAIMessageKeys.ASYNC_SVC.equals(svcTsmtUsgTp) && EAIMessageKeys.ASYNC_SVC.equals(psvItfTp)) {
info = manager.getTransform(svcMsg.getCnvMsgID()); //요청변환메시지ID명
}
// AA이 아닌 경우
// - 100, 200 요청변환에서
// - 300, 400 응답변환에서
else {
if (logPssSno == 100 || logPssSno == 200) {
info = manager.getTransform(svcMsg.getCnvMsgID()); //요청변환메시지ID명
} else {
if (rspErrCd.equals(EAIMessageKeys.BWK_ERRMSG_CODE)) { //업무에러(RIBEAI999999)
info = manager.getTransform(svcMsg.getErrRspCnvMsgID()); //오류응답변환메시지ID명
if(info == null) {
info = manager.getTransform(svcMsg.getBsRspCnvMsgID()); //기본응답변환메시지ID명
}
} else if(MessageUtil.checkRspErrCd(rspErrCd)) {
info = manager.getTransform(svcMsg.getBsRspCnvMsgID()); //기본응답변환메시지ID명
}
}
}
// 등록된 변환이 있는 경우
if (info != null) {
if (logger.isInfo()) logger.info("EAIFileLogger] Masking Log Message - " + message.getEAISvcCd());
// 변환은 등록되어 있으나 레이아웃정보가 삭제된 경우
// 정삭적인 Case 가 아님.
try {
if (logPssSno == 100 || logPssSno == 300 || logPssSno == 900)
l = info.getSourceLayout(0);
else
l = info.getTargetLayout();
}
catch(Exception e) {
if (logger.isInfo()) logger.info("getTargetLayout error" + e.getMessage());
}
// Layout 에 Mask 필드가 없는 경우 SKIP 하도록 한다.
if(l != null) {
try {
Item root = l.getRootItem();
isMasking = root.existMask();
}
catch(Exception e) {
if (logger.isWarn()) logger.info("EAIFileLogger] Check Masking field Error - " + e.getMessage());
isMasking = false;
}
if (logger.isInfo()) logger.info("EAIFileLogger] Message has Masking field [" + l.getName() + "][ " + isMasking+"]");
}
if(isMasking) {
try {
bizMsgStr = LogMessageUtil.makeMaskData(message, bizMsg, l, logPssSno,tgtAdptrMsgPtrnCd
, svcTsmtUsgTp, psvItfTp );
isMasked = true;
} catch(Exception e) {
if (logger.isInfo()) logger.info("EAIFileLogger] LogMasking Error - " + e.getMessage());
isMasked = false;
}
}
else {
if (logger.isInfo()) {
logger.info("EAIFileLogger] Masking is unnecessary - Skip Masking ");
}
isMasked = false;
}
}
else {
if (logger.isInfo()) {
logger.info("EAIFileLogger] Transform Not Found - Masking Unable");
}
isMasked = false;
}
// Masking check END
}
// boolean isUtf8 = isUTF8(svcTsmtUsgTp, psvItfTp, logPssSno, srcAdapterMsgType, tgtAdapterMsgType);
boolean isUtf8 = isUTF8(svcTsmtUsgTp, psvItfTp, logPssSno, srcAdapterMsgEncode, tgtAdapterMsgEncode);
// 요청 변환이 등록되지 않은 경우 또는 Masking 처리를 실패한 경우
if(!isMasked) {
if (bizMsg == null) {
if (logger.isInfo()) logger.info("EAIFileLogger] Message is NULL");
bizMsgStr = "";
} else if (bizMsg instanceof String) {
if (logger.isInfo()) logger.info("EAIFileLogger] Message is String Type");
bizMsgStr = (String)bizMsg;
} else if (bizMsg instanceof byte[]) {
if(isEBC(svcTsmtUsgTp, psvItfTp, logPssSno, srcAdapterMsgType, tgtAdapterMsgType)) {
if (logger.isInfo()) logger.info("EAIFileLogger] Message is EBCDIC bytes Type");
try {
bizMsgStr = IConv.ebcdicToASCIIWithSOSIEX( (byte[])bizMsg );
} catch(Exception ex) {
if (logger.isInfo()) logger.info("EAIFileLogger] 타입변환오류 - " + ex.getMessage());
bizMsgStr = new String((byte[])bizMsg);
}
}
else if(isUtf8) {
if (logger.isInfo()) logger.info("EAIFileLogger] Message is ASCII-UTF8 bytes Type");
bizMsgStr = new String((byte[])bizMsg, StandardCharsets.UTF_8);
}
else {
if (logger.isInfo()) logger.info("EAIFileLogger] Message is ASCII bytes Type");
bizMsgStr = new String((byte[])bizMsg);
// bizMsgStr = new String((byte[])bizMsg,JSONMessage.encode);
}
} else {
if (logger.isInfo()) logger.info("EAIFileLogger] Message is Object or UNKNOWN Type");
try {
StringBuilder sbuff = new StringBuilder();
bizMsgStr = sbuff.append(PropertyUtils.describe(bizMsg)).toString();
} catch (Exception e) {
if (logger.isWarn()) logger.warn("EAIFileLogger] Object Message Parsing Error - " + e.getMessage());
}
}
}
//-------------------------------------------------------------------------
// EAI 업무 개별부(32,000bytes)
/**
* 업무데이터에 대한정의
* 1. biz 데이터
* 2. 표준전문 JSON 데이터
* 3. 전장표
*/
StringBuilder sb = new StringBuilder();
String biz ="";
// String header = ExtMessageConverter.getSTDLog(message.getExtMsg());
String header = message.getStandardMessage().toFixedString(false);
//20220405
// String header = "";
// if (logPssSno ==100 || logPssSno ==300){
// header = ExtMessageConverter.getOriginalSTDLog(message.getExtMsg());
// }else{
// header = ExtMessageConverter.getSettingSTDLog(message.getExtMsg());
// }
String mdclData ="";
if (bizMsgStr == null) {
bizMsgStr = "";
}
//전장표 데이터부 JSON Array로 저장
//암호화
Charset hexaCharset = Charset.forName("euc-kr");
if("Y".equalsIgnoreCase(EncryptionManager.getInstance().getEncryptYN()) ){
try{
biz = HexaConverter.bytesToHexa(bizMsgStr.getBytes(hexaCharset));
}catch(Exception e){
logger.error("EAIFileLogger] bizMsgStr encryption Error - " + e.getMessage());
}
try{
header = HexaConverter.bytesToHexa(header.getBytes(hexaCharset));
}catch(Exception e){
logger.error("EAIFileLogger] header encryption Error - " + e.getMessage());
}
try{
mdclData = HexaConverter.bytesToHexa(mdclData.getBytes(hexaCharset));
}catch(Exception e){
logger.error("EAIFileLogger] mdclData encryption Error - " + e.getMessage());
}
}else {
biz = bizMsgStr;
}
//임시코드 시작
String logType = PropManager.getInstance().getProperty("BIZ_LOG_TYPE");
if (!StringUtils.isBlank(logType)){
if ("ALL".equals(logType)){
sb.append(header).append("|").append(biz).append("|").append(mdclData);
}else if ("HEADER".equals(logType)){
sb.append(header).append("|").append("|");
}else if ("BODY".equals(logType)){
sb.append("|").append(biz).append("|");
}else if ("NONE".equals(logType)){
sb.append("|").append("|");
}
}else{
sb.append(header).append("|").append(biz).append("|").append(mdclData);
}
//임시코드 종료
// File은 전체전문을 남기도록 한다.
String tmpStr = sb.toString();
bwkData = tmpStr.length() > 4000 ? StringUtils.substring(tmpStr, 0, 4000) : tmpStr;
addBwkData = tmpStr.length() > 4000 ? StringUtils.substring(tmpStr, 4000) : "";
// 업무데이터 사이즈가 4000byte 이상이면 추가업무데이터 테이블에 insert
if (!"".equals(addBwkData))
apndBwkDataYn = "Y";
String[] refMsgIDs = svcMsg.getRefMsgIDs();
// 입력메시지IDS 배열은 delimiter로 구분하여 200byte 만 insert
StringBuilder sbMsgIds = new StringBuilder();
if (refMsgIDs != null && refMsgIDs.length > 0) {
for (int i = 0; i < refMsgIDs.length - 1; i++) {
sbMsgIds.append(refMsgIDs[i]).append(", ");
}
sbMsgIds.append(refMsgIDs[refMsgIDs.length - 1]);
refMsgID = sbMsgIds.toString();
if (refMsgID.getBytes().length > 200) {
refMsgID = StringUtil.chunkString(refMsgID, 200);
}
}
} // 업무데이터 로깅을 할 경우에만 END loggingBizData
// ExtMessage extMessage = message.getExtMsg();
// 메시지수신시각으로 테이블명 설정
// int dayOfWeek = DatetimeUtil.getDayOfWeekNum(message.getMsgRcvTm());
try {
// 1/1000초로 변경
//String msgPssTm = DatetimeUtil.getTimeCenti(message.getMsgPssTm());
String msgPssTm = DatetimeUtil.getCurrentTime(message.getMsgPssTm());
CustomStringBuffer sb = new CustomStringBuffer(DELIMITER);
String serverName = EAIServerManager.getInstance().getLocalServerName();
String serverGroupName = EAIServerManager.getInstance().getServerType();
// EAI 업무 공통부(100 bytes)
sb.appendAndDelimeter( NullControl.addSpace(message.getBwkCls())); //EAI업무구분코드
sb.appendAndDelimeter( DatetimeUtil.getCurrentTime(message.getMsgRcvTm())); //메시지수신시각
sb.appendAndDelimeter( NullControl.addSpace(message.getSvcOgNo())); //EAI서비스일련번호
// 2009.07.13 공동망 통신망관련 수정 - 로그 저장시 원 로그처리일련번호를 저장
// sb.appendAndDelimeter(4, String.valueOf(logPssSno)); //로그처리일련번호
sb.appendAndDelimeter( String.valueOf(orglogPssSno)); //로그처리일련번호
// sb.appendAndDelimeter(5, NullControl.addSpace(message.getEAISvrInstNm())); //EAI서버인스탄스명
sb.appendAndDelimeter( NullControl.addSpace(serverName)); //EAI서버인스탄스명
sb.appendAndDelimeter( NullControl.addSpace(message.getEAISvcCd())); //EAI서비스명
sb.appendAndDelimeter( NullControl.addSpace(message.getSvcTmEn())); //서비스시각유무
sb.appendAndDelimeter( NullControl.addSpace(message.getSvcTsmtUsgTp())); //서비스동기사용구분코드
sb.appendAndDelimeter( NullControl.addSpace(message.getSvcPssTp())); //서비스처리구분명
sb.appendAndDelimeter( NullControl.addSpace(message.getFlwCntlRtnNm())); //흐름통제라우팅명
//index 10
sb.appendAndDelimeter( NullControl.addSpace(message.getUnifTp())); //통합구분명
sb.appendAndDelimeter( NullControl.addSpace(message.getSngSvcCls())); //기동서비스구분명
sb.appendAndDelimeter( String.valueOf(message.getSvcPssSeq())); //서비스처리번호
sb.appendAndDelimeter( NullControl.addSpace(message.getSvcWlColLogYn())); //서비스전컬럼로그여부
sb.appendAndDelimeter( NullControl.addSpace(message.getStdMsgUsgCls())); //표준메시지사용여부
sb.appendAndDelimeter( NullControl.addSpace(message.getSngSysItfTp())); //기동시스템어댑터업무그룹명
sb.appendAndDelimeter( NullControl.addSpace(message.getLydMsgID())); //현재메시지ID명
sb.appendAndDelimeter( NullControl.addSpace(message.getRspErrCd())); //응답에러코드명
sb.appendAndDelimeter( msgPssTm); //메시지처리시각
sb.appendAndDelimeter( String.valueOf(message.getSvrLogLvl())); //서버로그레벨번호
//index 20
sb.appendAndDelimeter( String.valueOf(message.getSvcLogLvl())); //서비스로그레벨번호
sb.appendAndDelimeter( NullControl.addSpace(message.getErrEAISvcName())); //오류EAI서비스명
sb.appendAndDelimeter( NullControl.addSpace(message.getDmndErrChngIDName())); //요청오류변환ID명
sb.appendAndDelimeter( NullControl.addSpace(message.getDmndErrFldName())); //요청에러필드명
sb.appendAndDelimeter( NullControl.addSpace(message.getRspnsErrChngIDName())); //응답오류변환ID명
sb.appendAndDelimeter( NullControl.addSpace(message.getRspnsErrFldName())); //응답에러필드명
sb.appendAndDelimeter( NullControl.addSpace(svcMsg.getPsvItfTp())); //수동인터페이스구분명
sb.appendAndDelimeter( NullControl.addSpace(svcMsg.getPsvBwkSysNm())); //수동업무시스템명
sb.appendAndDelimeter( NullControl.addSpace(svcMsg.getPsvSysID())); //수동시스템ID명
sb.appendAndDelimeter( NullControl.addSpace(svcMsg.getPsvSysSvcCd())); //수동시스템서비스구분명
//index 30
sb.appendAndDelimeter( NullControl.addSpace(svcMsg.getPsvSysItfTp())); //수동시스템어댑터업무그룹명
sb.appendAndDelimeter( NullControl.addSpace(svcMsg.getFlOvrCls())); //장애극복여부
sb.appendAndDelimeter( NullControl.addSpace(svcMsg.getCnvEn())); //변환여부
sb.appendAndDelimeter( NullControl.addSpace(svcMsg.getCnvMsgID())); //변환메시지ID명
sb.appendAndDelimeter( NullControl.addSpace(refMsgID)); //입력메시지ID명
sb.appendAndDelimeter( NullControl.addSpace(svcMsg.getBsRspMsgCprVl())); //기본응답메시지비교내용
sb.appendAndDelimeter( NullControl.addSpace(svcMsg.getBsRspCnvEn())); //기본응답변환여부
sb.appendAndDelimeter( NullControl.addSpace(svcMsg.getBsRspCnvMsgID())); //기본응답변환메시지ID명
sb.appendAndDelimeter( NullControl.addSpace(svcMsg.getErrRspMsgCprVl())); //오류응답메시지비교내용
sb.appendAndDelimeter( NullControl.addSpace(svcMsg.getErrRspCnvEn())); //오류응답변환여부
//index 40
sb.appendAndDelimeter( NullControl.addSpace(svcMsg.getErrRspCnvMsgID())); //오류응답변환메시지ID명
sb.appendAndDelimeter( String.valueOf(svcMsg.getNxtSvcPssSeq())); //다음서비스처리번호
sb.appendAndDelimeter( NullControl.addSpace(svcMsg.getOutbRtnNm())); //아웃바운드라우팅명
sb.appendAndDelimeter(svcMsg.getTmoVl()); //타임아웃값
sb.appendAndDelimeter( NullControl.addSpace(svcMsg.getCpnsSvcPssCd())); //보상서비스처리명
sb.appendAndDelimeter( NullControl.addSpace(apndBwkDataYn)); //추가업무데이터여부
sb.appendAndDelimeter( NullControl.addSpace(svcMsg.getKeyMgtMsgVl())); //키관리메시지내용
// SS,SA - Send - 100
// AA - Send - 100
// AA - Recv - 100, 300
// AS - 100
// String telgmDmndDstcd = kbheader.getTelgmDmndDstcd();
// String telgmDmndDstcd = message.getExtMsg().getSendRecv();
String telgmDmndDstcd = message.getMapper().getSendRecvDivision(message.getStandardMessage()); // S|R
if (prop != null &&
((EAIMessageKeys.SYNC_SVC.equals(svcTsmtUsgTp)
&& logPssSno == 100)
|| (EAIMessageKeys.ASYNC_SVC.equals(svcTsmtUsgTp)
&& EAIMessageKeys.ASYNC_SVC.equals(psvItfTp)
&& STDMessageKeys.SEND_RECV_CD_RECV.equals(telgmDmndDstcd)
&& (logPssSno == 100 || logPssSno == 300))
|| (EAIMessageKeys.ASYNC_SVC.equals(svcTsmtUsgTp)
&& EAIMessageKeys.ASYNC_SVC.equals(psvItfTp)
&& STDMessageKeys.SEND_RECV_CD_SEND.equals(telgmDmndDstcd)
&& logPssSno == 100)
|| (EAIMessageKeys.ASYNC_SVC.equals(svcTsmtUsgTp)
&& EAIMessageKeys.SYNC_SVC.equals(psvItfTp)
&& logPssSno == 100))) {
sb.appendAndDelimeter( NullControl.addSpace(prop.getProperty(Keys.LOG_ALT_KEY1))); //추적보조키1내용
sb.appendAndDelimeter( NullControl.addSpace(prop.getProperty(Keys.LOG_ALT_KEY2))); //추적보조키2내용
sb.appendAndDelimeter( NullControl.addSpace(prop.getProperty(Keys.LOG_ALT_KEY3))); //추적보조키3내용
sb.appendAndDelimeter( NullControl.addSpace(prop.getProperty(Keys.LOG_ALT_KEY4))); //추적보조키4내용
} else {
sb.appendAndDelimeter( " "); //추적보조키1내용
sb.appendAndDelimeter( " "); //추적보조키2내용
sb.appendAndDelimeter( " "); //추적보조키3내용
sb.appendAndDelimeter( " "); //추적보조키4내용
}
//index 51
sb.appendAndDelimeter( NullControl.addSpace(message.getGroupCoCd())); //EAI서비스코드의 그룹회사코드
// sb.appendAndDelimeter( kbheader.getGuIdNo().substring(0,33)); // PGUID
// sb.appendAndDelimeter( extMessage.getGuid()); // PGUID
sb.appendAndDelimeter( message.getMapper().getGuid(message.getStandardMessage())); // PGUID
sb.appendAndDelimeter( message.getTranType()); // 거래처리구분
sb.appendAndDelimeter( NullControl.addSpace(message.getRspnsChngMsgType())); // 응답변환유형
// log level 'E' or 'F'
if ("E".equals(message.getRspErrCd().substring(1, 2)) || "F".equals(message.getRspErrCd().substring(1, 2))) {
sb.appendAndDelimeter( NullControl.addSpace(message.getRspErrCd())); //EAI에러코드
sb.appendAndDelimeter( StringUtil.chunkString(message.getRspErrMsg(),1000)); //EAI에러내용
}
else {
sb.appendAndDelimeter( " "); //EAI에러코드
sb.appendAndDelimeter( " "); //EAI에러내용
}
//juns 서버명 변경에 따른 인스턴스 룰 추출변경
//ex)EAIDSG_i11 => EAIDS01_i01
//sb.appendAndDelimeter( serverName.substring(3, 6)); //서버그룹명
sb.appendAndDelimeter( serverGroupName); //서버그룹명
sb.appendAndDelimeter( NullControl.addSpace(message.getCompanyCode()) ); //업체코드, add 20190625
sb.appendAndDelimeter( message.getSplizLength()); //전문크기, add 20190625
//index 60
sb.appendAndDelimeter( NullControl.addSpace(message.getAdptrInstiCode())); // add 20190404 // adapterNickName
sb.appendAndDelimeter( NullControl.addSpace(message.getTxId()));// add 20210331 //TODO 거래ID
sb.appendAndDelimeter( NullControl.addSpace(message.getRefKey()));// add 20210331 //TODO 참조ID
sb.appendAndDelimeter( NullControl.addSpace(message.getExtBizCd()));// add 20210402 //TODO 대외업무구분코드
// EAI 업무 개별부(32,000bytes)
// 전체업무데이터를 HEXA String 으로 변경해서 저장한다. (newline 등의 문제로)
// Read시에는 HexaConverter.hexaToBytes 를 사용
// String hexaData = HexaConverter.bytesToHexa(bizMsgStr.getBytes());
// sb.appendAndDelimeter(hexaData);
// 에러메시지에도 newline이 있을 수 있으므로 다른 방안으로 처리 (2019.06.25)
// - EOL 라인을 추가한다.
if(bwkData == null || bwkData.equals(""))
bwkData = " ";
sb.appendAndDelimeter(bwkData);
String standardLayoutName = System.getProperty("STANDARD_LAYOUT_NAME");
sb.appendAndDelimeter( NullControl.addSpace(standardLayoutName));
sb.appendAndDelimeter( NullControl.addSpace(message.getClientId()));
// DATA에 NewLine이 있을 경우가 있으므로
// 데이터 라인 마지막에 추가하여 Loading 시에 EOL로 시작하는 라인이 올때까지 읽도록 처리해야 함.
// 데이터룰 HEXA로 저장하므로 필요없음
sb.append("\n"+EOL);
// tranLogger.info(sb.toString());
// 2025.04.10 tran.log 생성 로그 레벨 변경 info -> error
tranLogger.error(sb.toString());
// String sLogDirectory = PropManager.getInstance().getProperty(LogKeys.LOGGER_INFO, LogKeys.LOG_DIRECOTRY_PREFIX);
// String localServer = EAIServerManager.getInstance().getLocalServerName();
// String type = "TSEAILG1" + dayOfWeek;
// String serialNo = message.getSvcOgNo();
// String logSeq = String.valueOf(message.getSvcPssSeq());
// String logPath = sLogDirectory + localServer + File.separator + type + File.separator + serialNo+ File.separator;
//
// FileWrite(logPath, logSeq, sb.toString());
if ("Y".equals(apndBwkDataYn)) {
addBwkDataSub(message, addBwkData, dayOfWeek); // 업무데이터서브
}
} catch(Exception e) {
// logger.error("File Logging[MASTER] Failed - " + message.getEAISvcCd() + "|" + orglogPssSno
// + "|" + message.getSvcOgNo() + "|" + kbheader.getGuIdNo());
logger.error("File Logging[MASTER] Failed - " + message.getEAISvcCd() + "|" + orglogPssSno
+ "|" + message.getSvcOgNo() + "|" + message.getMapper().getGuid(message.getStandardMessage()));
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAICLG001"));
}
}
/**
* 1. 기능 : 업무데이터 서브 로그 셋팅
* 2. 처리 개요 :info[3]
* - TSEAILG03(EAI로그업무데이터서브정보) 로그값 셋팅
* - 매 4000byte 마다 row 증가
* 3. 주의사항
*
* @param message EAIMessage
* @param subBizMsgStr 추가 업무 데이터
* @exception DAOException
**/
public void addBwkDataSub(EAIMessage message, String subBizMsgStr, int dayOfWeek) {
try {
String sLogDirectory = PropManager.getInstance().getProperty(LogKeys.LOGGER_INFO, LogKeys.LOG_DIRECOTRY_PREFIX);
String localServer = EAIServerManager.getInstance().getLocalServerName();
String type = "TSEAILG2" + dayOfWeek;
String serialNo = message.getSvcOgNo();
String logSeq = String.valueOf(message.getLogPssSno());
String logPath = sLogDirectory + localServer + File.separator + type + File.separator + serialNo + File.separator;
FileWrite(logPath, logSeq, subBizMsgStr);
}catch(Exception e) {
logger.error("Log Sub Data write error.",e);
}
}
/**
* 1. 기능 : 모니터링을 위한 별도의 에러로그테이블에 에러정보를 저정
* 2. 처리 개요 :
* - TSEAILG03(EAI로그업무데이터서브정보) 로그값 셋팅
* 3. 주의사항
*
* @param message EAIMessage
* @exception DAOException
**/
public void addErrorLog(EAIMessage message, int dayOfWeek) {
try {
CustomStringBuffer sb = new CustomStringBuffer();
String serverName = EAIServerManager.getInstance().getLocalServerName();
sb.appendAndDelimeter(message.getBwkCls()); //EAI업무구분코드
sb.appendAndDelimeter(DatetimeUtil.getCurrentTime(message.getMsgRcvTm())); //메시지수신시각
sb.appendAndDelimeter(message.getSvcOgNo()); //EAI거래일련번호
sb.appendAndDelimeter(String.valueOf(message.getLogPssSno())); //로그처리일련번호
sb.appendAndDelimeter(message.getEAISvcCd()); //EAI서비스명
sb.appendAndDelimeter(message.getRspErrCd()); //응답에러코드명
sb.appendAndDelimeter(message.getSngSysItfTp()); //기동시스템어댑터업무그룹명
sb.appendAndDelimeter(message.getCurrentSvcMsg().getPsvSysItfTp()); //수동시스템어댑터업무그룹명
if ("E".equals(message.getRspErrCd().substring(1, 2)) || "F".equals(message.getRspErrCd().substring(1, 2))) {
sb.appendAndDelimeter(NullControl.addSpace(message.getRspErrCd())); //EAI에러코드
sb.appendAndDelimeter(StringUtil.chunkString(message.getRspErrMsg(),500)); //EAI에러내용
}
else {
sb.appendAndDelimeter(" "); //EAI에러코드
sb.appendAndDelimeter(" "); //EAI에러내용
}
sb.appendAndDelimeter(NullControl.addSpace(serverName)); //EAI서버인스턴스명
sb.appendAndDelimeter(NullControl.addSpace(EAIServerManager.getInstance().getEAIServer(serverName).getHostName())); //로깅시스템ID
sb.appendAndDelimeter(DatetimeUtil.getCurrentTime(message.getMsgPssTm())); // 메시지처리일시
// TODO DB 필드매핑 2010.12.21
sb.appendAndDelimeter(message.getGroupCoCd()); // EAI그룹회사코드
String sLogDirectory = PropManager.getInstance().getProperty(LogKeys.LOGGER_INFO, LogKeys.LOG_DIRECOTRY_PREFIX);
String localServer = EAIServerManager.getInstance().getLocalServerName();
String type = "TSEAILG3" + dayOfWeek;
String serialNo = message.getSvcOgNo();
String logSeq = String.valueOf(message.getLogPssSno());
String logPath = sLogDirectory + localServer + File.separator + type + File.separator + serialNo + File.separator;
FileWrite(logPath, logSeq, sb.toString());
} catch(Exception e) {
logger.error("Error Log Data write error.",e);
}
}
public void FileWrite(String path, String fileName, String data)throws Exception{
File directory = new File(path);
directory.setWritable(true,false);
directory.setReadable(true,false);
directory.setExecutable(true,true);
if (!directory.exists()){
if (!directory.mkdirs()){
throw new Exception("디렉토리 생성 오류입니다."+path);
}
}
File file = new File(path+fileName);
FileOutputStream os = null;
BufferedOutputStream bos = null;
try {
os = new FileOutputStream(file);
bos = new BufferedOutputStream(os);
bos.write(data.getBytes());
bos.flush();
file.setWritable(true,false);
file.setReadable(true,false);
file.setExecutable(true,true);
if (logger.isDebugEnabled()){
logger.debug(data);
}
}
catch(Exception ex) {
logger.error("file error", ex);
throw ex;
}
finally {
try { if(bos != null) bos.close(); } catch(Exception e) {}
try { if(os != null) os.close(); } catch(Exception e) {}
}
}
}
@@ -0,0 +1,843 @@
package com.eactive.eai.common.logger;
import java.nio.charset.Charset;
import java.util.Properties;
import com.eactive.eai.authserver.service.OAuth2Manager;
import com.eactive.eai.authserver.vo.ClientVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.eactive.eai.adapter.AdapterGroupVO;
import com.eactive.eai.adapter.AdapterManager;
import com.eactive.eai.agent.encryption.EncryptionManager;
import com.eactive.eai.common.dao.DAOException;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.logger.EAILogLogger;
import com.eactive.eai.common.logger.StatAdapterLogLogger;
import com.eactive.eai.common.logger.StatLogLogger;
import com.eactive.eai.common.logger.StatTranLogLogger;
import com.eactive.eai.common.logger.SubMessageLogLogger;
import com.eactive.eai.common.logger.mapper.StatAdapterLogMapper;
import com.eactive.eai.common.logger.mapper.StatLogMapper;
import com.eactive.eai.common.logger.mapper.StatTranLogMapper;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.message.EAIMessageKeys;
import com.eactive.eai.common.message.MessageType;
import com.eactive.eai.common.message.ServiceMessage;
import com.eactive.eai.common.monitor.StatMonitorLogVO;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.server.EAIServerVO;
import com.eactive.eai.common.server.loader.EAIServerLoader;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.MessageUtil;
import com.eactive.eai.common.util.StringUtil;
import com.eactive.eai.data.RollingTable;
import com.eactive.eai.data.entity.onl.logger.EAIErrorLog;
import com.eactive.eai.data.entity.onl.logger.EAIErrorLogId;
import com.eactive.eai.data.entity.onl.logger.EAILog;
import com.eactive.eai.data.entity.onl.logger.EAILogId;
import com.eactive.eai.data.entity.onl.logger.StatAdapterLog;
import com.eactive.eai.data.entity.onl.logger.StatLog;
import com.eactive.eai.data.entity.onl.logger.StatTranLog;
import com.eactive.eai.data.entity.onl.logger.SubMessageLog;
import com.eactive.eai.data.entity.onl.logger.SubMessageLogId;
import com.eactive.eai.message.EncodingVar;
import com.eactive.eai.message.StandardMessage;
import com.eactive.eai.message.manager.StandardMessageManager;
import com.eactive.eai.transformer.layout.Item;
import com.eactive.eai.transformer.layout.Layout;
import com.eactive.eai.transformer.transform.Transform;
import com.eactive.eai.transformer.transform.TransformManager;
import com.eactive.eai.util.HexaConverter;
import com.ext.eai.common.stdmessage.STDMessageKeys;
@Service
@Transactional
public class EAILogDAO {
//extends BaseDAO {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
@Autowired
private ApplicationContext applicationContext;
@Autowired
private EAILogLogger eaiLogEntityService;
@Autowired
private SubMessageLogLogger subMessageLogLogger;
@Autowired
private StatLogLogger statLogLogger;
@Autowired
private StatTranLogLogger statTranLogLogger;
@Autowired
private StatAdapterLogLogger statAdapterLogLogger;
@Autowired
private StatLogMapper statLogMapper;
@Autowired
private StatTranLogMapper statTranLogMapper;
@Autowired
private StatAdapterLogMapper statAdapterLogMapper;
@Autowired
private EAIServerLoader eaiServerEntityService;
public EAILogDAO() {
// empty
}
/**
* 1. 기능 : 메시지의 Type이 EBCDIC인지 판단 2. 처리 개요 : - 로그시퀀스에 맞는 Adapter의 메시지 type을 비교 -
* EBC인지 판별 3. 주의사항
*
* @param srcIfType String
* @param tgtIfType String
* @param logPssSno int
* @param srcAdapterMsgType String
* @param tgtAdapterMsgType String
* @return boolean
**/
public boolean isEBC(String srcIfType, String tgtIfType, int logPssSno, String srcAdapterMsgType,
String tgtAdapterMsgType) {
boolean isEBCDIC = false;
// SS. SA Type
if (logPssSno == 100) {
if (MessageType.EBC.equals(srcAdapterMsgType)) {
isEBCDIC = true;
}
} else if (logPssSno == 200) {
if (MessageType.EBC.equals(tgtAdapterMsgType)) {
isEBCDIC = true;
}
} else if (logPssSno == 300) {
if (EAIMessageKeys.ASYNC_SVC.equals(srcIfType) && EAIMessageKeys.ASYNC_SVC.equals(tgtIfType)) {
if (MessageType.EBC.equals(srcAdapterMsgType)) {
isEBCDIC = true;
}
} else {
if (MessageType.EBC.equals(tgtAdapterMsgType)) {
isEBCDIC = true;
}
}
}
// 400
else if (logPssSno == 400) {
if (EAIMessageKeys.ASYNC_SVC.equals(srcIfType) && EAIMessageKeys.ASYNC_SVC.equals(tgtIfType)) {
if (MessageType.EBC.equals(tgtAdapterMsgType)) {
isEBCDIC = true;
}
} else {
if (MessageType.EBC.equals(srcAdapterMsgType)) {
isEBCDIC = true;
}
}
}
// 900
else {
if (EAIMessageKeys.ASYNC_SVC.equals(srcIfType) && EAIMessageKeys.ASYNC_SVC.equals(tgtIfType)) {
if (MessageType.EBC.equals(tgtAdapterMsgType)) {
isEBCDIC = true;
}
} else {
if (MessageType.EBC.equals(srcAdapterMsgType)) {
isEBCDIC = true;
}
}
}
return isEBCDIC;
}
public boolean isUTF8(String srcIfType, String tgtIfType, int logPssSno, String srcAdapterMsgEncode,
String tgtAdapterMsgEncode) {
boolean isUTF = false;
if (logger.isInfo()) {
logger.info(String.format("EAILogDAO] isUTF8 %s %s %s %s %s", srcIfType, tgtIfType, logPssSno,
srcAdapterMsgEncode, tgtAdapterMsgEncode));
}
String adapterMsgEncode = "";
// SS. SA Type
if (logPssSno == 100) {
adapterMsgEncode = srcAdapterMsgEncode;
} else if (logPssSno == 200) {
adapterMsgEncode = tgtAdapterMsgEncode;
} else if (logPssSno == 300) {
if (EAIMessageKeys.ASYNC_SVC.equals(srcIfType) && EAIMessageKeys.ASYNC_SVC.equals(tgtIfType)) {
adapterMsgEncode = srcAdapterMsgEncode;
} else {
adapterMsgEncode = tgtAdapterMsgEncode;
}
}
// 400
else if (logPssSno == 400) {
if (EAIMessageKeys.ASYNC_SVC.equals(srcIfType) && EAIMessageKeys.ASYNC_SVC.equals(tgtIfType)) {
adapterMsgEncode = tgtAdapterMsgEncode;
} else {
adapterMsgEncode = srcAdapterMsgEncode;
}
}
// 900
else {
if (EAIMessageKeys.ASYNC_SVC.equals(srcIfType) && EAIMessageKeys.ASYNC_SVC.equals(tgtIfType)) {
adapterMsgEncode = tgtAdapterMsgEncode;
} else {
adapterMsgEncode = srcAdapterMsgEncode;
}
}
isUTF = StringUtils.equalsIgnoreCase(adapterMsgEncode, "UTF-8");
return isUTF;
}
/**
* 1. 기능 : EAI 서비스 로그 셋팅 2. 처리 개요 : - TSEAILG01(EAI서비스로그) 로그값 셋팅 -
* TSEAILG03(EAI로그업무데이터서브정보) insert 여부 결정 3. 주의사항
*
* @param message EAIMessage
* @exception DAOException
**/
public void addEAISvcLog(EAIMessage message, Properties prop) throws Exception {
String apndBwkDataYn = "N"; // 추가업무데이터 여부
// 개별메시지
String bizMsg = message.getStandardMessage().getBizData();
ServiceMessage svcMsg = message.getCurrentSvcMsg();
String bizMsgStr = "";
// transformer 적용
String svcTsmtUsgTp = message.getSvcTsmtUsgTp(); // 기동 Syunc/Async
String psvItfTp = svcMsg.getPsvItfTp(); // 수동 Syunc/Async
int logPssSno = message.getLogPssSno();
String rspErrCd = message.getRspErrCd();
// Duplication Error 방지를 위해
// 원 로그처리일련번호를 저장 : 2009.07.13
int orglogPssSno = logPssSno;
int svcLogLvl = message.getSvcLogLvl();
boolean loggingBizData = true;
// 특정거래에 대해 업무데이터를 저외함.
if (svcLogLvl > 3) {
loggingBizData = false;
}
if (logger.isWarn())
logger.warn("EAILogDAO] loggingBizData - " + loggingBizData);
// 복합거래인 경우 2X1,3X1 -> 200, 2X2,3X2 -> 300 처럼 처리한다.
if ((logPssSno > 200 && logPssSno < 300) || (logPssSno > 300 && logPssSno < 400)) {
if ((logPssSno % 2) == 1) {
logPssSno = 200;
} else {
logPssSno = 300;
}
}
// 업무테이터 처리
// 1. Get Source, Target Adapter Group Name
String srcAdapterGroupName = message.getSngSysItfTp();
String tgtAdapterGroupName = message.getCurrentSvcMsg().getPsvSysItfTp();
// 2. Get Source, Target Adapter GroupVO
AdapterManager adapterManager = AdapterManager.getInstance();
AdapterGroupVO srcAdapterGrpVO = adapterManager.getAdapterGroupVO(srcAdapterGroupName);
AdapterGroupVO tgtAdapterGrpVO = adapterManager.getAdapterGroupVO(tgtAdapterGroupName);
// 3. Get Source, Target Adapter Message Type
String srcAdapterMsgType = null;
String srcAdptrMsgPtrnCd = null;
String tgtAdapterMsgType = null;
String tgtAdptrMsgPtrnCd = null;
String srcAdapterMsgEncode = null;
String tgtAdapterMsgEncode = null;
if (srcAdapterGrpVO == null) {
srcAdapterMsgType = MessageType.ASC;
srcAdapterMsgEncode = Charset.defaultCharset().name();
if (logger.isWarn()) {
logger.warn("EAILogDAO] Source Adapter null. eai service code=" + message.getEAISvcCd());
}
} else {
srcAdapterMsgType = srcAdapterGrpVO.getMessageType();
srcAdptrMsgPtrnCd = srcAdapterGrpVO.getAdptrMsgPtrnCd();
srcAdapterMsgEncode = StringUtils.defaultIfBlank(srcAdapterGrpVO.getMessageEncode(),
Charset.defaultCharset().name());
}
if (tgtAdapterGrpVO == null) {
tgtAdapterMsgType = MessageType.ASC;
tgtAdapterMsgEncode = Charset.defaultCharset().name();
if (logger.isWarn()) {
logger.warn("EAILogDAO] Target Adapter null. eai service code=" + message.getEAISvcCd());
}
} else {
tgtAdapterMsgType = tgtAdapterGrpVO.getMessageType();
tgtAdptrMsgPtrnCd = tgtAdapterGrpVO.getAdptrMsgPtrnCd();
tgtAdapterMsgEncode = StringUtils.defaultIfBlank(tgtAdapterGrpVO.getMessageEncode(),
Charset.defaultCharset().name());
}
// SUBSTANDARD Logging
StandardMessage subMessage = message.getSubMessage();
boolean isSubLogging = false;
if(subMessage != null) {
isSubLogging = checkSubLogging(svcTsmtUsgTp, psvItfTp, srcAdptrMsgPtrnCd, tgtAdptrMsgPtrnCd, logPssSno);
if (logger.isDebug()) {
logger.debug( String.format("EAILogDAO] SUBSTANDARD-LOGGING checkSubLogging %s-%s %s-%s %d => %s",
svcTsmtUsgTp, psvItfTp, srcAdptrMsgPtrnCd, tgtAdptrMsgPtrnCd, logPssSno, isSubLogging) );
}
}
if(isSubLogging) {
String headerData = subMessage.toFixedString(false, EncodingVar.flatEncoding);
if (logger.isDebug()) {
logger.debug( String.format("EAILogDAO] SUBSTANDARD-LOGGING UUID: %s, LOGSEQ: %s, HEADER: %s",
message.getSvcOgNo(), logPssSno, headerData) );
}
try {
String layoutName = StandardMessageManager.getInstance().getVersionLayoutName();
SubMessageLog subMessageLog = (SubMessageLog) applicationContext.getBean(RollingTable.class, SubMessageLog.class,
message.getMsgRcvTm());
SubMessageLogId subLogId = new SubMessageLogId();
subMessageLog.setId(subLogId);
subLogId.setEaisvcserno(message.getSvcOgNo());
subLogId.setLogprcssserno(String.valueOf(orglogPssSno));
subMessageLog.setLayoutname(layoutName);
subMessageLog.setHeaderdata(headerData);
subMessageLogLogger.save(subMessageLog);
}
catch(Exception ex) {
logger.error( String.format("EAILogDAO] SUBSTANDARD-LOGGING ERROR UUID: %s, LOGSEQ: %s, HEADER: %s",
message.getSvcOgNo(), logPssSno, headerData), ex);
}
}
String bwkData = "";
String addBwkData = "";
String refMsgID = "";
if (loggingBizData) {
// ---------------------------------------------------
// LogMasking 을 위해 변환이 등록된 경우에만
// 변환을 통해 처리하도록 수정
// ---------------------------------------------------
boolean isMasked = false;
boolean isMasking = false;
// 변환이 등록된 경우
if ("1".equals(svcMsg.getCnvEn())) {
TransformManager manager = TransformManager.getManager();
Transform info = null;
Layout l = null;
// AA - 요청변환에서
if (EAIMessageKeys.ASYNC_SVC.equals(svcTsmtUsgTp) && EAIMessageKeys.ASYNC_SVC.equals(psvItfTp)) {
info = manager.getTransform(svcMsg.getCnvMsgID()); // 요청변환메시지ID명
}
// AA이 아닌 경우
// - 100, 200 요청변환에서
// - 300, 400 응답변환에서
else {
if (logPssSno == 100 || logPssSno == 200) {
info = manager.getTransform(svcMsg.getCnvMsgID()); // 요청변환메시지ID명
} else {
if (rspErrCd.equals(EAIMessageKeys.BWK_ERRMSG_CODE)) { // 업무에러(RIBEAI999999)
info = manager.getTransform(svcMsg.getErrRspCnvMsgID()); // 오류응답변환메시지ID명
if (info == null) {
info = manager.getTransform(svcMsg.getBsRspCnvMsgID()); // 기본응답변환메시지ID명
}
} else if (MessageUtil.checkRspErrCd(rspErrCd)) {
info = manager.getTransform(svcMsg.getBsRspCnvMsgID()); // 기본응답변환메시지ID명
}
}
}
// 등록된 변환이 있는 경우
if (info != null) {
if (logger.isInfo())
logger.info("EAILogDAO] Masking Log Message - " + message.getEAISvcCd());
// 변환은 등록되어 있으나 레이아웃정보가 삭제된 경우
// 정삭적인 Case 가 아님.
try {
if (logPssSno == 100 || logPssSno == 300 || logPssSno == 900)
l = info.getSourceLayout(0);
else
l = info.getTargetLayout();
} catch (Exception e) {
if (logger.isInfo())
logger.info("EAILogDAO] Layout not set");
}
// Layout 에 Mask 필드가 없는 경우 SKIP 하도록 한다.
if (l != null) {
try {
Item root = l.getRootItem();
isMasking = root.existMask();
} catch (Exception e) {
if (logger.isWarn())
logger.info("EAILogDAO] Check Masking field Error - " + e.getMessage());
isMasking = false;
}
if (logger.isInfo())
logger.info(
"EAILogDAO] Message has Masking field [" + l.getName() + "][ " + isMasking + "]");
}
if (isMasking) {
try {
bizMsgStr = LogMessageUtil.makeMaskData(message, bizMsg, l, logPssSno, tgtAdptrMsgPtrnCd,
svcTsmtUsgTp, psvItfTp);
isMasked = true;
} catch (Exception e) {
if (logger.isWarn())
logger.warn("EAILogDAO] LogMasking Error - " + e.getMessage(), e);
isMasked = false;
}
} else {
if (logger.isInfo())
logger.info("EAILogDAO] Masking is unnecessary - Skip Masking ");
isMasked = false;
}
} else {
if (logger.isInfo())
logger.info("EAILogDAO] Transform Not Found - Masking Unable");
isMasked = false;
}
// Masking check END
}
// boolean isUtf8 = isUTF8(svcTsmtUsgTp, psvItfTp, logPssSno, srcAdapterMsgEncode, tgtAdapterMsgEncode);
// 요청 변환이 등록되지 않은 경우 또는 Masking 처리를 실패한 경우
if (!isMasked) {
if (bizMsg == null) {
if (logger.isInfo())
logger.info("EAILogDAO] Message is NULL");
bizMsgStr = "";
} else {
if (logger.isInfo())
logger.info("EAILogDAO] Message is String Type");
bizMsgStr = bizMsg;
}
}
// EAI 업무 개별부(32,000bytes)
/**
* 업무데이터에 대한정의 1. biz 데이터 2. 표준전문 JSON 데이터 3. 전장표
*/
StringBuilder sb = new StringBuilder();
String biz = "";
String header = message.getStandardMessage().toFixedString(false, EncodingVar.flatEncoding);
String mdclData = "";
if (bizMsgStr == null) {
bizMsgStr = "";
}
// 암호화
Charset hexaCharset = Charset.forName("euc-kr");
if ("Y".equalsIgnoreCase(EncryptionManager.getInstance().getEncryptYN())) {
try {
biz = HexaConverter.bytesToHexa(bizMsgStr.getBytes(hexaCharset));
} catch (Exception e) {
logger.error("EAIFileLogger] bizMsgStr encryption Error - " + e.getMessage());
}
try {
header = HexaConverter.bytesToHexa(header.getBytes(hexaCharset));
} catch (Exception e) {
logger.error("EAIFileLogger] header encryption Error - " + e.getMessage());
}
try {
mdclData = HexaConverter.bytesToHexa(mdclData.getBytes(hexaCharset));
} catch (Exception e) {
logger.error("EAIFileLogger] mdclData encryption Error - " + e.getMessage());
}
} else {
biz = bizMsgStr;
}
// 임시코드 시작
String logType = PropManager.getInstance().getProperty("BIZ_LOG_TYPE");
if (!StringUtils.isBlank(logType)) {
if ("ALL".equals(logType)) {
sb.append(header).append("|").append(biz).append("|").append(mdclData);
} else if ("HEADER".equals(logType)) {
sb.append(header).append("|").append("|");
} else if ("BODY".equals(logType)) {
sb.append("|").append(biz).append("|");
} else if ("NONE".equals(logType)) {
sb.append("|").append("|");
}
} else {
sb.append(header).append("|").append(biz).append("|").append(mdclData);
}
// 임시코드 종료
bwkData = sb.toString();
String[] refMsgIDs = svcMsg.getRefMsgIDs();
// 입력메시지IDS 배열은 delimiter로 구분하여 200byte 만 insert
StringBuilder sbMsgIds = new StringBuilder();
if (refMsgIDs != null && refMsgIDs.length > 0) {
for (int i = 0; i < refMsgIDs.length - 1; i++) {
sbMsgIds.append(refMsgIDs[i]).append(", ");
}
sbMsgIds.append(refMsgIDs[refMsgIDs.length - 1]);
refMsgID = sbMsgIds.toString();
if (refMsgID.getBytes().length > 200) {
refMsgID = StringUtil.chunkString(refMsgID, 200);
}
}
} // 업무데이터 로깅을 할 경우에만 END loggingBizData
EAILog eaiLog = (EAILog) applicationContext.getBean(RollingTable.class, EAILog.class, message.getMsgRcvTm());
try {
// 1/1000초로 변경
String msgPssTm = DatetimeUtil.getCurrentTime(message.getMsgPssTm());
String serverName = EAIServerManager.getInstance().getLocalServerName();
String serverGroupName = EAIServerManager.getInstance().getServerType();
// EAI 업무 공통부(100 bytes)
EAILogId eaiLogId = new EAILogId();
eaiLog.setId(eaiLogId);
// EAI업무구분코드
eaiLogId.setEaibzwkdstcd(message.getBwkCls());
// 메시지수신시각
eaiLogId.setMsgdpstyms(DatetimeUtil.getCurrentTime(message.getMsgRcvTm()));
// EAI서비스일련번호
eaiLogId.setEaisvcserno(message.getSvcOgNo());
// 로그처리일련번호
eaiLogId.setLogprcssserno(String.valueOf(orglogPssSno));
// EAI서버인스탄스명
eaiLog.setEaisevrinstncname(serverName);
// EAI서비스명
eaiLog.setEaisvcname(message.getEAISvcCd());
// 서비스시각유무
eaiLog.setSvchmseonot(message.getSvcTmEn());
// 서비스동기사용구분코드
eaiLog.setSvcmotivusedstcd(message.getSvcTsmtUsgTp());
// 서비스처리구분명
eaiLog.setSvcprcssdsticname(message.getSvcPssTp());
// 흐름통제라우팅명
eaiLog.setFlowctrlroutname(message.getFlwCntlRtnNm());
// 통합구분명
eaiLog.setIntgradsticname(message.getUnifTp());
// 기동서비스구분명
eaiLog.setGstatsvcdsticname(message.getSngSvcCls());
// 서비스처리번호
eaiLog.setSvcprcssno(String.valueOf(message.getSvcPssSeq()));
// 서비스전컬럼로그여부
eaiLog.setSvcbfclmnlogyn(message.getSvcWlColLogYn());
// 표준메시지사용여부
eaiLog.setStndmsguseyn(message.getStdMsgUsgCls());
// 기동시스템어댑터업무그룹명
eaiLog.setGstatsysadptrbzwkgroupname(message.getSngSysItfTp());
// 현재메시지ID명
eaiLog.setPrsntmsgidname(message.getLydMsgID());
// 응답에러코드명
eaiLog.setRspnserrcdname(message.getRspErrCd());
// 메시지처리시각
eaiLog.setMsgprcssyms(msgPssTm);
// 서버로그레벨번호
eaiLog.setSevrloglvelno(String.valueOf(message.getSvrLogLvl()));
// 서비스로그레벨번호
eaiLog.setSvcloglvelno(String.valueOf(message.getSvcLogLvl()));
// 오류EAI서비스명
eaiLog.setErreaisvcname(message.getErrEAISvcName());
// 요청오류변환ID명
eaiLog.setDmnderrchngidname(message.getDmndErrChngIDName());
// 요청에러필드명
eaiLog.setDmnderrfldname(message.getDmndErrFldName());
// 응답오류변환ID명
eaiLog.setRspnserrchngidname(message.getRspnsErrChngIDName());
// 응답에러필드명
eaiLog.setRspnserrfldname(message.getRspnsErrFldName());
// 수동인터페이스구분명
eaiLog.setPsvintfacdsticname(svcMsg.getPsvItfTp());
// 수동업무시스템명
eaiLog.setPsvbzwksysname(svcMsg.getPsvBwkSysNm());
// 수동시스템ID명
eaiLog.setPsvsysidname(svcMsg.getPsvSysID());
// 수동시스템서비스구분명
eaiLog.setPsvsyssvcdsticname(svcMsg.getPsvSysSvcCd());
// 수동시스템어댑터업무그룹명
eaiLog.setPsvsysadptrbzwkgroupname(svcMsg.getPsvSysItfTp());
// 장애극복여부
eaiLog.setFlovryn(svcMsg.getFlOvrCls());
// 변환여부
eaiLog.setChngyn(svcMsg.getCnvEn());
// 변환메시지ID명
eaiLog.setChngmsgidname(svcMsg.getCnvMsgID());
// 입력메시지ID명
eaiLog.setInptmsgidname(refMsgID);
// 기본응답메시지비교내용
eaiLog.setBascrspnsmsgcmprctnt(svcMsg.getBsRspMsgCprVl());
// 기본응답변환여부
eaiLog.setBascrspnschngyn(svcMsg.getBsRspCnvEn());
// 기본응답변환메시지ID명
eaiLog.setBascrspnschngmsgidname(svcMsg.getBsRspCnvMsgID());
// 오류응답메시지비교내용
eaiLog.setErrrspnsmsgcmprctnt(svcMsg.getErrRspMsgCprVl());
// 오류응답변환여부
eaiLog.setErrrspnschngyn(svcMsg.getErrRspCnvEn());
// 오류응답변환메시지ID명
eaiLog.setErrrspnschngmsgidname(svcMsg.getErrRspCnvMsgID());
// 다음서비스처리번호
eaiLog.setNextsvcprcssno(String.valueOf(svcMsg.getNxtSvcPssSeq()));
// 아웃바운드라우팅명
eaiLog.setOutbndroutname(svcMsg.getOutbRtnNm());
// 타임아웃값
eaiLog.setToutval(svcMsg.getTmoVl());
// 보상서비스처리명
eaiLog.setCmpensvcprcssname(svcMsg.getCpnsSvcPssCd());
// 추가업무데이터여부
eaiLog.setSupplbzwkdatayn(apndBwkDataYn);
// 키관리메시지내용
eaiLog.setKeymgtmsgctnt(svcMsg.getKeyMgtMsgVl());
// SS,SA - Send - 100
// AA - Send - 100
// AA - Recv - 100, 300
// AS - 100
String telgmDmndDstcd = message.getMapper().getSendRecvDivision(message.getStandardMessage());
if (prop != null && ((EAIMessageKeys.SYNC_SVC.equals(svcTsmtUsgTp) && logPssSno == 100)
|| (EAIMessageKeys.ASYNC_SVC.equals(svcTsmtUsgTp) && EAIMessageKeys.ASYNC_SVC.equals(psvItfTp)
&& STDMessageKeys.SEND_RECV_CD_RECV.equals(telgmDmndDstcd)
&& (logPssSno == 100 || logPssSno == 300))
|| (EAIMessageKeys.ASYNC_SVC.equals(svcTsmtUsgTp) && EAIMessageKeys.ASYNC_SVC.equals(psvItfTp)
&& STDMessageKeys.SEND_RECV_CD_SEND.equals(telgmDmndDstcd) && logPssSno == 100)
|| (EAIMessageKeys.ASYNC_SVC.equals(svcTsmtUsgTp) && EAIMessageKeys.SYNC_SVC.equals(psvItfTp)
&& logPssSno == 100))) {
eaiLog.setTrackasiskey1ctnt(prop.getProperty(com.eactive.eai.common.logger.Keys.LOG_ALT_KEY1)); // 추적보조키1내용
eaiLog.setTrackasiskey2ctnt(prop.getProperty(com.eactive.eai.common.logger.Keys.LOG_ALT_KEY2)); // 추적보조키2내용
eaiLog.setTrackasiskey3ctnt(prop.getProperty(com.eactive.eai.common.logger.Keys.LOG_ALT_KEY3)); // 추적보조키3내용
eaiLog.setTrackasiskey4ctnt(prop.getProperty(com.eactive.eai.common.logger.Keys.LOG_ALT_KEY4)); // 추적보조키4내용
}
// EAI서비스코드의 그룹회사코드
eaiLog.setEaigroupcodstcd(message.getGroupCoCd());
// PGUID
eaiLog.setPguid(message.getMapper().getOrgGuid(message.getStandardMessage()));
// 송수신구분
eaiLog.setTrantype(message.getTranType());
//
eaiLog.setRspnschngmsgtype(message.getRspnsChngMsgType());
// log level 'E' or 'F'
if ("E".equals(message.getRspErrCd().substring(1, 2))
|| "F".equals(message.getRspErrCd().substring(1, 2))) {
// EAI에러코드
eaiLog.setEaierrcd(message.getRspErrCd());
// EAI에러내용
eaiLog.setEaierrctnt(StringUtil.chunkString(message.getRspErrMsg(), 1000));
}
// 서버그룹명
eaiLog.setSevrgroupname(serverGroupName);
// 업체코드
eaiLog.setCompanycode(message.getCompanyCode());
// 전문크기, add 20190404
eaiLog.setSplizlength(message.getSplizLength());
// index 60
// add 20190404 // adapterNickName
eaiLog.setAdptrinsticode(message.getAdptrInstiCode());
// 거래ID
eaiLog.setTxid(message.getTxId());
// 참조ID
eaiLog.setRefkey(message.getRefKey());
// 대외업무구분코드
eaiLog.setExtbizcd(message.getExtBizCd());
// EAI 업무 개별부(32,000bytes)
if (bwkData == null || bwkData.equals(""))
bwkData = " ";
eaiLog.setBzwkdatactnt(bwkData);
String standardLayoutName = System.getProperty("STANDARD_LAYOUT_NAME");
// 표준전문레이아웃 명
eaiLog.setStdlayoutname(standardLayoutName);
// clientId 로그에 추가
String clientId = message.getClientId();
eaiLog.setClientid(clientId);
// client IP 로그에 추가
String clientIp = message.getClientIp();
eaiLog.setClientip(clientIp);
/**
* CLIENT ID 있을 경우 APP, 기관정보 로그에 추가
* TODO: ClientVO의 경우 spring security oauth의 ClientDetails를 상속받고 있어 OAUTH가 아닌 인증의 경우에 대한 처리 추가 필요
*/
if(StringUtils.isNotBlank(clientId)) {
ClientVO clientVO = OAuth2Manager.getInstance().getClientVO(clientId);
if (clientVO != null) {
eaiLog.setClientname(clientVO.getClientName());
eaiLog.setOrgid(clientVO.getOrgId());
eaiLog.setOrgname(clientVO.getOrgName());
}
}
eaiLogEntityService.save(eaiLog);
} catch (Exception e) {
logger.error(
"DB Logging[MASTER] Failed - " + message.getEAISvcCd() + "|" + orglogPssSno + "|"
+ message.getSvcOgNo() + "|" + message.getMapper().getGuid(message.getStandardMessage()),
e);
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAICLG001"));
}
// 에러로그를 별도의 테이블에 저장하도록 한다.
if (!MessageUtil.checkRspErrCd(message.getRspErrCd())) {
try {
// 거래통제, 유량제어에 의한 에러는 저장하지 않도록 한다.
if (!(EAIMessageKeys.EAI_BLOCKED_CODE.equals(message.getRspErrCd())
|| EAIMessageKeys.EAI_INFLOW_BLOCKED_CODE.equals(message.getRspErrCd()))) {
addErrorLog(message); // 에러로그
}
} catch (Exception ex) {
logger.warn("에러로그테이블 저장 SKIP 에러발생 - " + ex.getMessage());
}
}
}
public void addErrorLog(EAIMessage message) throws DAOException {
try {
String serverName = EAIServerManager.getInstance().getLocalServerName();
EAIErrorLog eaiErrorLog = (EAIErrorLog) applicationContext.getBean(RollingTable.class, EAIErrorLog.class,
message.getMsgRcvTm());
// EAI업무구분코드
EAIErrorLogId eaiErrorLogId = new EAIErrorLogId();
eaiErrorLog.setId(eaiErrorLogId);
eaiErrorLogId.setEaibzwkdstcd(message.getBwkCls());
// 메시지수신시각
eaiErrorLogId.setMsgdpstyms(DatetimeUtil.getCurrentTime(message.getMsgRcvTm()));
// EAI거래일련번호
eaiErrorLogId.setEaisvcserno(message.getSvcOgNo());
// 로그처리일련번호
eaiErrorLogId.setLogprcssserno(String.valueOf(message.getLogPssSno()));
// EAI서비스명
eaiErrorLog.setEaisvcname(message.getEAISvcCd());
// 응답에러코드명
eaiErrorLog.setRspnserrcdname(message.getRspErrCd());
// 기동시스템어댑터업무그룹명
eaiErrorLog.setGstatsysadptrbzwkgroupname(message.getSngSysItfTp());
// 수동시스템어댑터업무그룹명
eaiErrorLog.setPsvsysadptrbzwkgroupname(message.getCurrentSvcMsg().getPsvSysItfTp());
if ("E".equals(message.getRspErrCd().substring(1, 2))
|| "F".equals(message.getRspErrCd().substring(1, 2))) {
// EAI에러코드
eaiErrorLog.setEaierrcd(message.getRspErrCd());
// EAI에러내용
eaiErrorLog.setEaierrctnt(StringUtil.chunkString(message.getRspErrMsg(), 500));
}
// EAI서버인스턴스명
eaiErrorLog.setEaisevrinstncname(serverName);
// 로깅시스템ID
EAIServerVO eaiServerVO = EAIServerManager.getInstance().getEAIServer(serverName);
if(eaiServerVO != null) {
eaiErrorLog.setLgingsysid(eaiServerVO.getHostName());
}
// 메시지처리일시
eaiErrorLog.setMsgprcssyms(DatetimeUtil.getCurrentTime(message.getMsgPssTm()));
// EAI그룹회사코드
eaiErrorLog.setEaigroupcodstcd(message.getGroupCoCd());
} catch (Exception e) {
logger.error("DB Logging[ERROR_LOG] Failed - " + message.getEAISvcCd() + "|" + message.getLogPssSno() + "|"
+ message.getSvcOgNo(), e);
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAICLG003"));
}
}
public void addStaticLog(StatMonitorLogVO vo) throws DAOException {
try {
StatLog statLog = statLogMapper.toEntity(vo);
statLogLogger.save(statLog);
} catch (Exception e) {
logger.error("DB Logging[STATIC_LOG] Failed - " + vo.toString(), e);
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAICLG003"));
}
}
public void addStaticTranCdLog(StatMonitorLogVO vo) throws DAOException {
try {
StatTranLog statTranLog = statTranLogMapper.toEntity(vo);
statTranLogLogger.save(statTranLog);
} catch (Exception e) {
logger.error("DB Logging[STATIC_TRANCD_LOG] Failed - " + vo.toString(), e);
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAICLG003"));
}
}
public void addStaticAdapterLog(StatMonitorLogVO vo) throws DAOException {
try {
StatAdapterLog statAdapterLog = statAdapterLogMapper.toEntity(vo);
statAdapterLogLogger.save(statAdapterLog);
} catch (Exception e) {
logger.error("DB Logging[STATIC_ADAPTER_LOG] Failed - " + vo.toString(), e);
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAICLG003"));
}
}
public boolean getCheck() throws DAOException {
return eaiServerEntityService.checkConnection();
}
private boolean checkSubLogging(String svcTsmtUsgTp, String psvItfTp, String srcAdptrMsgPtrnCd, String tgtAdptrMsgPtrnCd, int logPssSno) {
boolean isAsyncSvc = EAIMessageKeys.ASYNC_SVC.equals(svcTsmtUsgTp) && EAIMessageKeys.ASYNC_SVC.equals(psvItfTp);
boolean isSrcStandard = com.eactive.eai.adapter.Keys.IF_SUBSTANDARD.equals(srcAdptrMsgPtrnCd);
// // SOURCE : AA : 100, 300, ELSE: 100, 400
if(isSrcStandard && ( (isAsyncSvc && (logPssSno == 100 || logPssSno == 300)) ||
(!isAsyncSvc && (logPssSno == 100 || logPssSno == 400)) ) ) {
return true;
}
boolean isTgtStandard = com.eactive.eai.adapter.Keys.IF_SUBSTANDARD.equals(tgtAdptrMsgPtrnCd);
// // TARGET : AA : 200, 400, ELSE : 200, 300
if (isTgtStandard && ( (isAsyncSvc && (logPssSno == 200 || logPssSno == 400)) ||
(!isAsyncSvc && (logPssSno == 200 || logPssSno == 300)) ) ) {
return true;
}
return false;
}
}
@@ -0,0 +1,38 @@
package com.eactive.eai.common.logger;
/**
* 1. 기능 : EAI 로그 처리 시 예외처리를 위한 Exception
* 2. 처리 개요 :
* - EAILogger 예외처리
* 3. 주의사항
*
* @author : 전영석( amjang@evalleyvs.com)
* @version : v 1.0.0
* @see : TestCall
* @since :JDK v1.4.2
*/
public class EAILogException extends Exception
{
/**
* 1. 기능 : Default 생성자 함수
* 2. 처리 개요 :
* - Default 생성자 함수
* 3. 주의사항
*
**/
public EAILogException() {
super("EAILogException is occured.");
}
/**
* 1. 기능 : Exception 발생 원인을 저장하는 생성자 함수
* 2. 처리 개요 :
* - Exception 발생 원인을 저장하는 생성자 함수
* 3. 주의사항
*
*@param msg Exception 발생 원인
**/
public EAILogException(String msg) {
super(msg);
}
}
@@ -0,0 +1,132 @@
package com.eactive.eai.common.logger;
import com.eactive.eai.common.dao.Keys;
/**
* 1. 기능 : EAI에서 처리되는 모든 On-Line 거래를 데이터베이스에 로깅하기 위한 운영관리 Logger Query Object
* 2. 처리 개요 :
* - TSEAILG01(EAI서비스로그), TSEAILG02(로그ALTKEY정보), TSEAILG03(EAI로그업무데이터서브정보), TSEAILG04(EAI서비스오류정보) insert Query
* 3. 주의사항
*
* @author : 전영석(amjang@evalleyvs.com)
* @version : v 1.0.0
* @see : IMSAdapterListener, IMSRecord
* @since :JDK v1.4.2
*/
public interface EAILogQuery
{
/**
* 1. 기능 : EAI 서비스 로그 셋팅
* 2. 처리 개요 :
* - TSEAILG01(EAI서비스로그) 로그값 셋팅
* 3. 주의사항
**/
public static final String ADD_EAI_SVC_LOG
= " INSERT INTO " + Keys.TABLE_OWNER + "#{LOG_MASTER_TABLE} ( \n"
//EAI업무공통부
+ " EAIBZWKDSTCD, MSGDPSTYMS, EAISVCSERNO, LOGPRCSSSERNO, EAISEVRINSTNCNAME, \n"
+ " EAISVCNAME, SVCHMSEONOT, SVCMOTIVUSEDSTCD, SVCPRCSSDSTICNAME, FLOWCTRLROUTNAME, \n"
+ " INTGRADSTICNAME, GSTATSVCDSTICNAME, SVCPRCSSNO, SVCBFCLMNLOGYN, STNDMSGUSEYN, \n"
+ " GSTATSYSADPTRBZWKGROUPNAME, PRSNTMSGIDNAME, RSPNSERRCDNAME, MSGPRCSSYMS, SEVRLOGLVELNO, \n"
+ " SVCLOGLVELNO, ERREAISVCNAME, DMNDERRCHNGIDNAME, DMNDERRFLDNAME, RSPNSERRCHNGIDNAME, \n"
+ " RSPNSERRFLDNAME, PSVINTFACDSTICNAME, PSVBZWKSYSNAME, PSVSYSIDNAME, PSVSYSSVCDSTICNAME, \n"
+ " PSVSYSADPTRBZWKGROUPNAME, FLOVRYN, CHNGYN, CHNGMSGIDNAME, INPTMSGIDNAME, \n"
+ " BASCRSPNSMSGCMPRCTNT, BASCRSPNSCHNGYN, BASCRSPNSCHNGMSGIDNAME, ERRRSPNSMSGCMPRCTNT, ERRRSPNSCHNGYN, \n"
+ " ERRRSPNSCHNGMSGIDNAME, NEXTSVCPRCSSNO, OUTBNDROUTNAME, TOUTVAL, CMPENSVCPRCSSNAME, \n"
+ " SUPPLBZWKDATAYN, KEYMGTMSGCTNT, TRACKASISKEY1CTNT, TRACKASISKEY2CTNT, TRACKASISKEY3CTNT, \n"
+ " TRACKASISKEY4CTNT, EAIGROUPCODSTCD, PGUID, TRANTYPE, RSPNSCHNGMSGTYPE, \n"
+ " EAIERRCD, EAIERRCTNT, SEVRGROUPNAME, COMPANYCODE, SPLIZLENGTH, ADPTRINSTICODE, \n"
+ " TXID, REFKEY, EXTBIZCD, \n"
+ " BZWKDATACTNT, STDLAYOUTNAME, CLIENTID \n"
+ " ) VALUES ( \n"
//EAI업무공통부
+ " ?, ?, ?, ?, ?, \n" //index to 5
+ " ?, ?, ?, ?, ?, \n" //index to 10
+ " ?, ?, ?, ?, ?, \n" //index to 15
+ " ?, ?, ?, ?, ?, \n" //index to 20
+ " ?, ?, ?, ?, ?, \n" //index to 25
+ " ?, ?, ?, ?, ?, \n" //index to 30
+ " ?, ?, ?, ?, ?, \n" //index to 35
+ " ?, ?, ?, ?, ?, \n" //index to 40
+ " ?, ?, ?, ?, ?, \n" //index to 45
+ " ?, ?, ?, ?, ?, \n" //index to 50
+ " ?, ?, ?, ?, ?, \n" //index to 55
+ " ?, ?, ?, ?, ?, \n" //index to 60
+ " ?, ?, ?, ?,\n" //index to 61
+ " ?, ?, ? \n" // 62~66
+ ") ";
/**
* 1. 기능 : 업무데이터 서브 로그 셋팅
* 2. 처리 개요 :
* - TSEAILG03(EAI로그업무데이터서브정보) 로그값 셋팅
* 3. 주의사항
**/
public static final String ADD_BWK_DATA_SUB
= " INSERT INTO " + Keys.TABLE_OWNER + "#{LOG_SLAVE_TABLE} ( \n"
+ " EAIBZWKDSTCD, MSGDPSTYMS, EAISVCSERNO, BZWKDATASERNO, LOGPRCSSSERNO \n"
+ " , BZWKDATACTNT \n"
+ " ) VALUES ( \n"
+ " ?, ?, ?, ?, ? \n"
+ " , ? \n"
+ " ) ";
public static final String ERROR_LOG
= " INSERT INTO " + Keys.TABLE_OWNER + "#{LOG_SLAVE_TABLE} ( \n"
+ " EAIBZWKDSTCD, MSGDPSTYMS, EAISVCSERNO, LOGPRCSSSERNO, EAISVCNAME \n"
+ " , RSPNSERRCDNAME, GSTATSYSADPTRBZWKGROUPNAME, PSVSYSADPTRBZWKGROUPNAME, EAIERRCD, EAIERRCTNT \n"
+ " , EAISEVRINSTNCNAME, LGINGSYSID, MSGPRCSSYMS, EAIGROUPCODSTCD \n"
+ " ) VALUES ( \n"
+ " ?, ?, ?, ?, ? \n"
+ " , ?, ?, ?, ?, ? \n"
+ " , ?, ?, ?, ? \n"
+ " ) ";
public static final String STATIC_LOG
= " INSERT INTO " + Keys.TABLE_OWNER + "TSEAISR01 ( \n"
+ " BASEYMD, BASEHH, BASEHHMM, EAIBZWKDSTCD, EAISVCNAME \n"
+ " , EAISEVRINSTNCNAME, EAIPRCSSTTMVAL, EAIPSVPRCSSTTMVAL, EAITOTALPRCSSTTMVAL, WHOLPRCSSNOITM \n"
+ " , ERRZNOITM, TOUTNOITM, NOMALNOITM \n"
+ " ) VALUES ( \n"
+ " ?, ?, ?, ?, ? \n"
+ " , ?, ?, ?, ?, ? \n"
+ " , ?, ?, ? \n"
+ " ) ";
public static final String STATIC_TRANCD_LOG
= " INSERT INTO " + Keys.TABLE_OWNER + "TSEAISR02 ( \n"
+ " BASEYMD, BASEHH, BASEHHMM, EAIBZWKDSTCD, EAISVCNAME \n"
+ " , INTFACSENDTRANCD, EAISEVRINSTNCNAME ,EAIPRCSSTTMVAL, EAIPSVPRCSSTTMVAL, EAITOTALPRCSSTTMVAL \n"
+ " , WHOLPRCSSNOITM, ERRZNOITM, TOUTNOITM, NOMALNOITM \n"
+ " ) VALUES ( \n"
+ " ?, ?, ?, ?, ? \n"
+ " , ?, ?, ?, ?, ? \n"
+ " , ?, ?, ?, ? \n"
+ " ) ";
public static final String STATIC_SCREEN_LOG
= " INSERT INTO " + Keys.TABLE_OWNER + "TSEAISR03 ( \n"
+ " BASEYMD, BASEHH, BASEHHMM, EAIBZWKDSTCD, EAISVCNAME \n"
+ " , SCRENNO, EAISEVRINSTNCNAME, EAIPRCSSTTMVAL, EAIPSVPRCSSTTMVAL, EAITOTALPRCSSTTMVAL \n"
+ " , WHOLPRCSSNOITM, ERRZNOITM, TOUTNOITM, NOMALNOITM \n"
+ " ) VALUES ( \n"
+ " ?, ?, ?, ?, ? \n"
+ " , ?, ?, ?, ?, ? \n"
+ " , ?, ?, ?, ? \n"
+ " ) ";
public static final String STATIC_ADAPTER_LOG
= " INSERT INTO " + Keys.TABLE_OWNER + "TSEAISR04 ( \n"
+ " BASEYMD, BASEHH, BASEHHMM, EAIBZWKDSTCD, EAISVCNAME \n"
+ " , ADPTRBZWKGROUPNAME, EAISEVRINSTNCNAME, EAIPRCSSTTMVAL, EAIPSVPRCSSTTMVAL, EAITOTALPRCSSTTMVAL \n"
+ " , WHOLPRCSSNOITM, ERRZNOITM, TOUTNOITM, NOMALNOITM \n"
+ " ) VALUES ( \n"
+ " ?, ?, ?, ?, ? \n"
+ " , ?, ?, ?, ?, ? \n"
+ " , ?, ?, ?, ? \n"
+ " ) ";
public static final String CHECK_DB = "select 1";
}
@@ -0,0 +1,127 @@
package com.eactive.eai.common.logger;
import java.util.Properties;
import org.apache.commons.lang3.SerializationUtils;
import com.eactive.eai.common.logger.async.AsyncLoggingPoolManager;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.message.EAIMessageKeys;
import com.eactive.eai.common.monitor.EAIServiceMonitor;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.MessageUtil;
import com.eactive.eai.env.ElinkConfig;
/**
* 1. 기능 : EAI에서 처리되는 모든 On-Line 거래를 데이터베이스에 로깅하기 위한 운영관리 Logger Sender
* 2. 처리 개요 : - RequestProcessor에서 받은 로깅 정보를 로그 Queue로 전달
* 3. 주의사항
*/
public class EAILogSender {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
static TransactionLogger txLogger;
static {
try {
txLogger = (TransactionLogger) Class.forName("com.eactive.eai.common.logger.DBLogTransactionLogger").newInstance();
} catch(Exception e) {
logger.error(e.getMessage(), e);
}
}
private EAILogSender() {
}
public static int logCount() {
return txLogger.logCount();
}
public static int errCount() {
return txLogger.errCount();
}
public static void resetCount() {
txLogger.resetCount();
}
public static void send(EAIMessage message, Properties prop) throws Exception {
if(message == null) {
if(logger.isWarn()) {
logger.warn("EAIMessage is null, skip async logging.");
}
}
else {
String guidLogPrefix = "EAILogSender] GUID[" + message.getMapper().getGuid(message.getStandardMessage())
+ "] UUID[" + message.getSvcOgNo() + "] ";
boolean isLogging = false;
int svcLogLvl = message.getSvcLogLvl();
int logPssSno = message.getLogPssSno();
String svcTsmtUsgTp = message.getSvcTsmtUsgTp();
if(svcLogLvl >= 3) {
isLogging = true;
}
else if(svcLogLvl == 2) {
if( EAIMessageKeys.SYNC_SVC.equals(svcTsmtUsgTp) &&
(logPssSno == 100 || logPssSno == 400) ) {
isLogging = true;
}
if( EAIMessageKeys.ASYNC_SVC.equals(svcTsmtUsgTp) &&
(logPssSno == 200 || logPssSno == 400) ) {
isLogging = true;
}
}
else if(svcLogLvl == 1) {
isLogging = ! MessageUtil.checkRspErrCd(message.getRspErrCd());
}
else {
isLogging = false;
}
if(logger.isDebug()) {
logger.debug(guidLogPrefix + " svcLogLvl="+ svcLogLvl + ",isLogging="+ isLogging+ ", logPssSno="+ logPssSno);
}
long logTime = System.currentTimeMillis();
message.setMsgPssTm(logTime);
if(isLogging) {
if(ElinkConfig.isUseAsyncLogging()) {
try {
EAIMessage cloned = null;
// cloned = (EAIMessage) ObjectUtil.deepCopy(message);
// cloned = (EAIMessage) SerializationUtils.clone(message);
// performance issue, use clone -> shallow copy bug -> fix
cloned = (EAIMessage) message.clone();
Properties clonedProp = null;
if(prop != null) clonedProp = (Properties) prop.clone();
AsyncLoggingPoolManager.getInstance().publish(cloned, clonedProp);
} catch (Exception e) {
logger.warn("AsyncLogging error", e);
logDirect(message, prop);
// throw e;
}
}
else {
logDirect(message, prop);
}
}
// 실시간 모니터링 로그
EAIServiceMonitor servicemonitor = EAIServiceMonitor.getInstance();
if(EAIMessageKeys.EAI_BLOCKED_CODE.equals(message.getRspErrCd())) {
if(logger.isWarn()) {
logger.warn(guidLogPrefix + " 거래통제 실시간 모니터링 SKIP - " + message.getEAISvcCd()
+ ", "+message.getMapper().getGuid(message.getStandardMessage()) );
}
}else if (EAIMessageKeys.EAI_INFLOW_BLOCKED_CODE.equals(message.getRspErrCd())) {
if(logger.isWarn()) {
logger.warn(guidLogPrefix + " 유량제어 실시간 모니터링 SKIP - " + message.getEAISvcCd()
+ ", "+ message.getMapper().getGuid(message.getStandardMessage()) );
}
}else {
servicemonitor.receiveLogMessage(message);
}
}
}
public static void logDirect(EAIMessage message, Properties prop) throws EAILogException {
txLogger.log(message, prop);
}
}
@@ -0,0 +1,12 @@
package com.eactive.eai.common.logger;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class HttpAdapterExtraHeaderVo {
private String name;
private String value;
}
@@ -0,0 +1,32 @@
package com.eactive.eai.common.logger;
import com.eactive.eai.common.logger.async.HttpAdapterExtraLogH2Factory;
import com.eactive.eai.data.entity.onl.logger.HttpAdapterExtraLog;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Service;
@Service
public class HttpAdapterExtraLogFileLogger {
public void writeFileLog(HttpAdapterExtraLog httpAdapterExtraLog){
try (Session session = HttpAdapterExtraLogH2Factory.getInstance().openSession()) {
Transaction transaction = null;
try {
// 트랜잭션 시작
transaction = session.beginTransaction();
session.persist(httpAdapterExtraLog);
// 트랜잭션 커밋
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
throw e;
}
}
}
}
@@ -0,0 +1,17 @@
package com.eactive.eai.common.logger;
import lombok.Data;
import java.util.List;
@Data
public class HttpAdapterExtraLogVo {
private String guid;
private int serviceProcessNumber;
private String adapterGroupName;
private String adapterName;
private String url;
private String httpMethod;
private int httpStatus;
List<HttpAdapterExtraHeaderVo> headerList;
}
@@ -0,0 +1,41 @@
package com.eactive.eai.common.logger;
import com.eactive.eai.common.logger.mapper.HttpAdapterExtraLogMapper;
import com.eactive.eai.data.entity.onl.logger.HttpAdapterExtraLog;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class HttpLoggingService {
@Autowired
private HttpAdapterExtraLogMapper mapper;
@Autowired
private HttpAdapterExtraLogLogger dbLogger;
@Autowired
private HttpAdapterExtraLogFileLogger fileLogger;
public void insertHttpAdapterExtraLog(HttpAdapterExtraLogVo httpAdapterExtraLogVo) throws Throwable{
HttpAdapterExtraLog httpAdapterExtraLog = mapper.toEntity(httpAdapterExtraLogVo);
if (EAIDBLogControl.isEnable()) {
try {
dbLogger.save(httpAdapterExtraLog);
} catch(Exception e){
String message = e.getMessage();
// 오류 메시지 추가 - Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
// 오류 메시지 추가 - Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
if( "ConnectionError".equals(message) || StringUtils.contains(message, "JDBCConnectionException")
|| StringUtils.contains(message, "Unable to acquire JDBC Connection") ) {
EAIDBLogControl.setEnable(false);
}
fileLogger.writeFileLog(httpAdapterExtraLog);
}
} else {
fileLogger.writeFileLog(httpAdapterExtraLog);
}
}
}
@@ -0,0 +1,121 @@
package com.eactive.eai.common.logger;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.jms.JmsServiceLocator;
import com.eactive.eai.common.lifecycle.Lifecycle;
import com.eactive.eai.common.lifecycle.LifecycleException;
import com.eactive.eai.common.lifecycle.LifecycleListener;
import com.eactive.eai.common.lifecycle.LifecycleSupport;
/**
* 1. 기능 : LogListener를 관리하는 Manager 클래스
* 2. 처리 개요 : ServiceLocator로부터 queue를 get하여 Receiver를 생성 관리한한다.
* 3. 주의사항
*
* @author :
* @version : v 1.0.0
* @see : 관련 기능을 참조
* @since : :
*/
public class LogListener implements MessageListener, Lifecycle {
private String name;
private LifecycleSupport lifecycle = new LifecycleSupport(this);
private boolean started;
private QueueConnection qcon;
private QueueSession qsession;
private QueueReceiver qreceiver;
private Queue queue;
public LogListener(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void onMessage(Message msg) {
// write code here!
}
public void start() throws LifecycleException {
if (started)
throw new LifecycleException("RECEAICLG101");
lifecycle.fireLifecycleEvent(STARTING_EVENT, null);
try {
JmsServiceLocator locator = JmsServiceLocator.getInstance();
QueueConnectionFactory qconFactory = locator.getQueueConnectionFactory(Keys.LOG_CONNECTION_FACTORY);
if (qconFactory == null) {
throw new Exception("QueueConnectionFactory not found - " + Keys.LOG_CONNECTION_FACTORY);
}
qcon = qconFactory.createQueueConnection();
qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
queue = locator.getQueue(Keys.LOG_QUEUE);
qreceiver = qsession.createReceiver(queue);
qreceiver.setMessageListener(this);
qcon.start();
} catch (Exception e) {
throw new LifecycleException(ExceptionUtil.getErrorCode(e, "RECEAICLG102"));
}
started = true;
lifecycle.fireLifecycleEvent(STARTED_EVENT, null);
}
public void stop() throws LifecycleException {
if (!started)
throw new LifecycleException("RECEAICLG103");
lifecycle.fireLifecycleEvent(STOPING_EVENT, null);
try {
if (qreceiver != null)
qreceiver.close();
} catch (Exception e) {
// nothing to do
}
try {
if (qreceiver != null)
qsession.close();
} catch (Exception e) {
// nothing to do
}
try {
if (qreceiver != null)
qcon.close();
} catch (Exception e) {
// nothing to do
}
started = false;
lifecycle.fireLifecycleEvent(STOPPED_EVENT, null);
}
public void addLifecycleListener(LifecycleListener listener) {
lifecycle.addLifecycleListener(listener);
}
public LifecycleListener[] findLifecycleListeners() {
return lifecycle.findLifecycleListeners();
}
public void removeLifecycleListener(LifecycleListener listener) {
lifecycle.removeLifecycleListener(listener);
}
public boolean isStarted() {
return this.started;
}
}
@@ -0,0 +1,178 @@
package com.eactive.eai.common.logger;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.lifecycle.Lifecycle;
import com.eactive.eai.common.lifecycle.LifecycleException;
import com.eactive.eai.common.lifecycle.LifecycleListener;
import com.eactive.eai.common.lifecycle.LifecycleSupport;
/**
* 1. 기능 : LogListener를 생성 관리하는 Manager 클래스
* 2. 처리 개요 : LogListener를 생성 관리한다.
* 3. 주의사항
*
* @author :
* @version : v 1.0.0
* @see : 관련 기능을 참조
* @since :
* :
*/
public class LogListenerManager implements Lifecycle
{
/**
* Default Logger
*/
// private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
/**
* LogListener생성 count. LogListener생성시 증가시킴
*/
private int count;
// private ArrayList listeners;
/**
* LifeccyleSupport object
*/
private LifecycleSupport lifecycle = new LifecycleSupport(this);
/**
* 기동 여부
*/
private boolean started;
/**
* LogListener생성시 동기화를 위한 lock
*/
private Object lock = new Object();
/**
* 1. 기능 : Lifecycle의 start 메서드로 LogListenerManager를 초기화하는 메서드
* 2. 처리 개요 : Lifecycle의 start
* 3. 주의사항
*
* @exception LifecycleException 이미 시작되었을 경우 발생(RECEAICLG111)
*
**/
public void start() throws LifecycleException {
if (started)
throw new LifecycleException("RECEAICLG111");
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STARTING_EVENT, null);
// this.listeners = new ArrayList();
this.count = 0;
started = true;
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STARTED_EVENT, null);
}
/**
* 1. 기능 : Lifecycle의 stop 메서드로 LogListenerManager를 종료하는 메서드
* 2. 처리 개요 : Lifecycle의 stop 메서드로 LogListenerManager를 종료
* 3. 주의사항
*
* @exception LifecycleException 이미 종료된 경우 발생(RECEAICLG112)
**/
public void stop() throws LifecycleException {
// Validate and update our current component state
if (!started)
throw new LifecycleException("RECEAICLG112");
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STOPING_EVENT, null);
started = false;
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STOPPED_EVENT, null);
}
/**
* 1. 기능 : LifecycleListener를 등록하는 메서드
* 2. 처리 개요 : LifecycleListener를 등록한다.
* 3. 주의사항
*
* @param listener LifecycleEvent를 수신한 LifecycleListener
**/
public void addLifecycleListener(LifecycleListener listener)
{
lifecycle.addLifecycleListener(listener);
}
/**
* 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드
* 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다.
* 3. 주의사항
*
* @return 등록된 LifecycleListener 리스트
**/
public LifecycleListener[] findLifecycleListeners()
{
return lifecycle.findLifecycleListeners();
}
/**
* 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드
* 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다.
* 3. 주의사항
*
* @param listener 삭제할 LifecycleListener
**/
public void removeLifecycleListener(LifecycleListener listener)
{
lifecycle.removeLifecycleListener(listener);
}
/**
* 1. 기능 : LogListenerManager의 초기화 여부를 반환하는 getter 메서드
* 2. 처리 개요 : LogListenerManager의 초기화 여부를 반환한다.
* 3. 주의사항
*
* @return 초기화 여부
**/
public boolean isStarted() {
return this.started;
}
/**
* 1. 기능 : LogListener를 생성하고 초기화하는 메서드
* 2. 처리 개요 : LogListener를 생성하고 생성한 LogListener를 start하여 초기화 시킨다.
* 3. 주의사항
*
**/
public void addLogListener() {
LogListener listener = createLogListener();
if(listener instanceof Lifecycle) {
try {
listener.start();
} catch(Exception e) {
String code = "RECEAICLG113";
//if (logger.isError()) logger.error(ExceptionUtil.make(code, CodeMessageHandler.getMessage(code)));
throw new RuntimeException(ExceptionUtil.getErrorCode(e, code));
}
}
}
/**
* 1. 기능 : LogListener를 생성하는 메서드
* 2. 처리 개요 : LogListener를 생성시 생성 카운트를 증가시킨다
* -
* 3. 주의사항
* @return LogListener 생성된 LogListener
**/
private LogListener createLogListener() {
String name = null;
synchronized(lock) {
name = "LogListener["+(++count)+"]";
}
LogListener listener = new LogListener(name);
return listener;
}
}
@@ -0,0 +1,96 @@
package com.eactive.eai.common.logger;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.MessageUtil;
import com.eactive.eai.transformer.layout.Layout;
import com.eactive.eai.transformer.message.BytesMessage;
import com.eactive.eai.transformer.message.JSONMessage;
import com.eactive.eai.transformer.message.Message;
import com.eactive.eai.transformer.message.MessageFactory;
import com.eactive.eai.transformer.message.XMLMessage;
public class LogMessageUtil {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
public static String makeMaskData(EAIMessage message, Object bizMsg, Layout l, int logPssSno, String tgtAdptrMsgPtrnCd
, String svcTsmtUsgTp, String psvItfTp) throws Exception {
String bizMsgStr="";
Message msg = MessageFactory.getFactory().getMessage(l.getName());
if("XML".equals(l.getLayoutType().getName())) {
if (logger.isInfo()) logger.info("EAILogDAO] XML Message Masking - "+ message.getEAISvcCd()+" - "+ logPssSno);
String xmlString = "";
if(bizMsg instanceof byte[]) {
xmlString = new String((byte[])bizMsg);
} else {
xmlString = (String)bizMsg;
}
String rootItemName = ((XMLMessage)msg).getLayout().getRootItem().getName();
xmlString = MessageUtil.removeXMLHeader(xmlString);
xmlString = "<"+rootItemName+">"+xmlString+"</"+rootItemName+">";
msg.setData(xmlString);
bizMsgStr = MessageUtil.removeXMLRootItem(msg.toLogString(), rootItemName);
}
else if("JSON".equals(l.getLayoutType().getName())) {
if (logger.isInfo()) logger.info("EAILogDAO] JSON Message Masking - "+ message.getEAISvcCd()+" - "+ logPssSno);
String jsonString = "";
jsonString = (String)bizMsg;
// String rootItemName = ((JSONMessage)msg).getLayout().getRootItem().getName();
// jsonString = MessageUtil.addJsonRootItem(jsonString, rootItemName);
// msg.setData(jsonString);
// bizMsgStr = MessageUtil.removeJsonRootItem(msg.toLogString(), rootItemName);;
// JSON Tuning
msg.setData(jsonString);
bizMsgStr = msg.toLogString();
}
// else if("UJSON".equals(l.getLayoutType().getName())) {
// if (logger.isInfo()) logger.info("EAILogDAO] UJSON Message Masking - "+ message.getEAISvcCd()+" - "+ logPssSno);
//
// String jsonString = "";
//
// if(bizMsg instanceof byte[]) {
// jsonString = new String((byte[])bizMsg, UJSONMessage.encode);
// } else {
// jsonString = (String)bizMsg;
// }
//
// String rootItemName = ((UJSONMessage)msg).getLayout().getRootItem().getName();
// jsonString = MessageUtil.addJsonRootItem(jsonString, rootItemName);
// msg.setData(jsonString);
// bizMsgStr = MessageUtil.removeJsonRootItem(msg.toLogString(), rootItemName);;
// }
else if("EBCDIC".equals(l.getLayoutType().getName())) {
if (logger.isInfo()) logger.info("EAILogDAO] EBCDIC Message Masking - "+ message.getEAISvcCd()+" - "+ logPssSno);
byte[] orgBytes = (byte[])bizMsg;
byte[] msgBytes = null;
byte[] header = null;
msg.setData(bizMsg);
bizMsgStr = ((BytesMessage)msg).toLogString(true);
}
else if( "BYTES".equals(l.getLayoutType().getName()) ) {
if (logger.isInfo()) logger.info("EAILogDAO] BYTES Message Masking - "+ logPssSno);
byte[] orgBytes = (byte[])bizMsg;
byte[] msgBytes = null;
byte[] header = null;
if (logger.isInfo()) logger.info("EAILogDAO] BYTES Standard Header Type = " + tgtAdptrMsgPtrnCd);
if (logger.isInfo()) logger.info("EAILogDAO] "+l.getLayoutType().getName()+" Message Masking - "+ message.getEAISvcCd()+" - "+ logPssSno);
msg.setData(bizMsg);
bizMsgStr = msg.toLogString();
}
else {
msg.setData(bizMsg);
bizMsgStr = msg.toLogString();
}
return bizMsgStr;
}
}
@@ -0,0 +1,12 @@
package com.eactive.eai.common.logger;
import com.eactive.eai.common.message.EAIMessage;
import java.util.Properties;
public interface TransactionLogger {
public void log(EAIMessage message,Properties prop) throws EAILogException;
public int logCount();
public int errCount();
public void resetCount();
}
@@ -0,0 +1,210 @@
package com.eactive.eai.common.logger.async;
import com.eactive.eai.common.lifecycle.Lifecycle;
import com.eactive.eai.common.lifecycle.LifecycleException;
import com.eactive.eai.common.lifecycle.LifecycleListener;
import com.eactive.eai.common.lifecycle.LifecycleSupport;
import com.eactive.eai.common.logger.HttpAdapterExtraLogVo;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.env.ElinkConfig;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import java.time.Duration;
import java.util.Properties;
/**
* HTTP 로그도 ASYNC 모드를 대응하기 위해 추가
* 추후 고도화 필요
*/
public class AsyncHttpLoggingPoolManager implements Lifecycle {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
private static AsyncHttpLoggingPoolManager instance;
private static boolean stopped = true;
private int maxPoolSize = 10;
private int initPoolSize = 8;
private boolean initOnStartup = true;
private ObjectPool<HttpLoggingPoolObject> pool = null;
/**
* 기동 여부
*/
private boolean started;
/**
* LifeccyleSupport object
*/
private LifecycleSupport lifecycle = new LifecycleSupport(this);
public static synchronized AsyncHttpLoggingPoolManager getInstance() {
if (instance == null) {
instance = new AsyncHttpLoggingPoolManager();
}
return instance;
}
public int getMaxPoolSize() {
return maxPoolSize;
}
public void setMaxPoolSize(int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}
public int getInitPoolSize() {
return initPoolSize;
}
public void setInitPoolSize(int initPoolSize) {
this.initPoolSize = initPoolSize;
}
public boolean isInitOnStartup() {
return initOnStartup;
}
public void setInitOnStartup(boolean initOnStartup) {
this.initOnStartup = initOnStartup;
}
public void publish(HttpAdapterExtraLogVo httpAdapterExtraLogVo) throws Exception {
HttpLoggingPoolObject queue = null;
try {
queue = borrowObject();
queue.putMessage(httpAdapterExtraLogVo);
} catch (Exception ex) {
logger.error("publish failed.", ex);
throw ex;
} finally {
if (queue != null) returnObject(queue);
}
}
public void init() {
if (pool != null) shutdown();
maxPoolSize = ElinkConfig.getAsyncPoolMaxSize();
initPoolSize = ElinkConfig.getAsyncPoolInitSize();
initOnStartup = ElinkConfig.isAsyncInitOnstartup();
if (logger.isWarn()) {
logger.warn("<< init start - maxPoolSize = {}, initPoolSize = {}, initOnStartup = {}", maxPoolSize, initPoolSize, initOnStartup);
}
@SuppressWarnings("rawtypes")
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
HttpLoggingPoolObjectFactory factory = new HttpLoggingPoolObjectFactory();
config.setMaxTotal(maxPoolSize);
//config.setMinIdle(maxPoolSize); // default: 0
//config.setMaxIdle(maxPoolSize); // default: 8
config.setMaxWait(Duration.ofSeconds(5));
// add proper config options
// config.setLifo(true);
pool = new GenericObjectPool<HttpLoggingPoolObject>(factory, config);
if (initOnStartup) {
HttpLoggingPoolObject[] pools = new HttpLoggingPoolObject[initPoolSize];
for (int i = 0; i < initPoolSize; i++) {
try {
logger.warn(">> borrowObject LoggingPoolObject-" + i);
pools[i] = pool.borrowObject();
} catch (Exception e) {
// nothing to do
}
}
for (int i = 0; i < initPoolSize; i++) {
try {
logger.warn("<< returnObject LoggingPoolObject-" + i);
pool.returnObject(pools[i]);
} catch (Exception e) {
// nothing to do
}
}
}
stopped = false;
logger.warn("<< init end");
}
public HttpLoggingPoolObject borrowObject() throws Exception {
if (stopped) throw new PoolShutdownException();
return pool.borrowObject();
}
public void returnObject(HttpLoggingPoolObject object) throws Exception {
if (stopped) throw new PoolShutdownException();
pool.returnObject(object);
}
public void shutdown() {
if (logger.isWarn()) {
logger.warn("<< shutdown start");
}
int retry = 0;
try {
if (pool != null) {
while (true) {
pool.close();
logger.warn("close pool.getNumActive() = " + pool.getNumActive());
if (pool.getNumActive() == 0 || retry > 10) break;
logger.warn("close - sleep 100ms");
Thread.sleep(100);
retry++;
}
}
} catch (Exception e) {
logger.error("shutdown failed.", e);
} finally {
stopped = true;
pool = null;
}
logger.warn(">> shutdown end");
}
@Override
public void addLifecycleListener(LifecycleListener listener) {
lifecycle.addLifecycleListener(listener);
}
@Override
public LifecycleListener[] findLifecycleListeners() {
return lifecycle.findLifecycleListeners();
}
@Override
public void removeLifecycleListener(LifecycleListener listener) {
lifecycle.removeLifecycleListener(listener);
}
@Override
public void start() throws LifecycleException {
if (started)
throw new LifecycleException("RECEAICRT201");
lifecycle.fireLifecycleEvent(STARTING_EVENT, this);
// init pool & disruptor component
init();
started = true;
lifecycle.fireLifecycleEvent(STARTED_EVENT, this);
}
@Override
public void stop() throws LifecycleException {
if (!started)
throw new LifecycleException("RECEAICRT203");
lifecycle.fireLifecycleEvent(STOPING_EVENT, this);
shutdown();
started = false;
lifecycle.fireLifecycleEvent(STOPPED_EVENT, this);
}
@Override
public boolean isStarted() {
return this.started;
}
}
@@ -0,0 +1,209 @@
package com.eactive.eai.common.logger.async;
import java.time.Duration;
import java.util.Properties;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import com.eactive.eai.common.lifecycle.Lifecycle;
import com.eactive.eai.common.lifecycle.LifecycleException;
import com.eactive.eai.common.lifecycle.LifecycleListener;
import com.eactive.eai.common.lifecycle.LifecycleSupport;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.env.ElinkConfig;
public class AsyncLoggingPoolManager implements Lifecycle {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
private static AsyncLoggingPoolManager instance;
private static boolean stopped = true;
private int maxPoolSize = 10;
private int initPoolSize = 8;
private boolean initOnStartup = true;
private ObjectPool<LoggingPoolObject> pool = null;
/**
* 기동 여부
*/
private boolean started;
/**
* LifeccyleSupport object
*/
private LifecycleSupport lifecycle = new LifecycleSupport(this);
public static synchronized AsyncLoggingPoolManager getInstance() {
if(instance == null) {
instance = new AsyncLoggingPoolManager();
}
return instance;
}
public int getMaxPoolSize() {
return maxPoolSize;
}
public void setMaxPoolSize(int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}
public int getInitPoolSize() {
return initPoolSize;
}
public void setInitPoolSize(int initPoolSize) {
this.initPoolSize = initPoolSize;
}
public boolean isInitOnStartup() {
return initOnStartup;
}
public void setInitOnStartup(boolean initOnStartup) {
this.initOnStartup = initOnStartup;
}
public void publish(EAIMessage message, Properties prop) throws Exception {
LoggingPoolObject queue = null;
try {
queue = borrowObject();
queue.putMessage(message, prop);
}
catch(Exception ex) {
logger.error("publish failed.", ex);
throw ex;
}
finally {
if(queue != null) returnObject(queue);
}
}
public void init() {
if(pool != null) shutdown();
maxPoolSize = ElinkConfig.getAsyncPoolMaxSize();
initPoolSize = ElinkConfig.getAsyncPoolInitSize();
initOnStartup = ElinkConfig.isAsyncInitOnstartup();
if(logger.isWarn()) {
logger.warn("<< init start - maxPoolSize = {}, initPoolSize = {}, initOnStartup = {}", maxPoolSize, initPoolSize, initOnStartup);
}
@SuppressWarnings("rawtypes")
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
LoggingPoolObjectFactory factory = new LoggingPoolObjectFactory();
config.setMaxTotal(maxPoolSize);
//config.setMinIdle(maxPoolSize); // default: 0
//config.setMaxIdle(maxPoolSize); // default: 8
config.setMaxWait(Duration.ofSeconds(5));
// add proper config options
// config.setLifo(true);
pool = new GenericObjectPool<LoggingPoolObject>(factory, config);
if(initOnStartup) {
LoggingPoolObject[] pools = new LoggingPoolObject[initPoolSize];
for(int i=0; i<initPoolSize; i++) {
try {
logger.warn(">> borrowObject LoggingPoolObject-"+ i);
pools[i] = pool.borrowObject();
} catch (Exception e) {
// nothing to do
}
}
for(int i=0; i<initPoolSize; i++) {
try {
logger.warn("<< returnObject LoggingPoolObject-"+ i);
pool.returnObject(pools[i]);
} catch (Exception e) {
// nothing to do
}
}
}
stopped = false;
logger.warn("<< init end");
}
public LoggingPoolObject borrowObject() throws Exception {
if(stopped) throw new PoolShutdownException();
return pool.borrowObject();
}
public void returnObject(LoggingPoolObject object) throws Exception {
if(stopped) throw new PoolShutdownException();
pool.returnObject(object);
}
public void shutdown() {
if(logger.isWarn()) {
logger.warn("<< shutdown start");
}
int retry = 0;
try {
if(pool != null) {
while(true) {
pool.close();
logger.warn("close pool.getNumActive() = "+pool.getNumActive());
if(pool.getNumActive() == 0 || retry > 10) break;
logger.warn("close - sleep 100ms");
Thread.sleep(100);
retry++;
}
}
} catch (Exception e) {
logger.error("shutdown failed.", e);
}
finally {
stopped = true;
pool = null;
}
logger.warn(">> shutdown end");
}
@Override
public void addLifecycleListener(LifecycleListener listener) {
lifecycle.addLifecycleListener(listener);
}
@Override
public LifecycleListener[] findLifecycleListeners() {
return lifecycle.findLifecycleListeners();
}
@Override
public void removeLifecycleListener(LifecycleListener listener) {
lifecycle.removeLifecycleListener(listener);
}
@Override
public void start() throws LifecycleException {
if (started)
throw new LifecycleException("RECEAICRT201");
lifecycle.fireLifecycleEvent(STARTING_EVENT, this);
// init pool & disruptor component
init();
started = true;
lifecycle.fireLifecycleEvent(STARTED_EVENT, this);
}
@Override
public void stop() throws LifecycleException {
if (!started)
throw new LifecycleException("RECEAICRT203");
lifecycle.fireLifecycleEvent(STOPING_EVENT, this);
shutdown();
started = false;
lifecycle.fireLifecycleEvent(STOPPED_EVENT, this);
}
@Override
public boolean isStarted() {
return this.started;
}
}
@@ -0,0 +1,61 @@
package com.eactive.eai.common.logger.async;
import java.util.ArrayList;
import java.util.List;
import com.eactive.eai.common.logger.EAILogException;
import com.eactive.eai.common.logger.EAILogSender;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.util.Logger;
import com.lmax.disruptor.EventHandler;
public class CustomEventHandler implements EventHandler<LoggingEvent> {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
String name;
int sleepMs;
private int batchSize = 1;
private int count = 0;
private final List<LoggingEvent> eventList = new ArrayList<>();
public CustomEventHandler() {
}
public CustomEventHandler(String name, int sleepMs, int batchSize) {
this.name = name;
this.sleepMs = sleepMs;
this.batchSize = batchSize;
}
@Override
public void onEvent(LoggingEvent event, long sequence, boolean endOfBatch) throws Exception {
if(sleepMs > 0) Thread.sleep(sleepMs);
if(batchSize > 1) {
eventList.add(event);
if (++count >= batchSize) {
processBatch();
eventList.clear();
count = 0;
}
}
else {
EAIMessage message = event.getMessage();
if(logger.isInfo()) {
logger.info(String.format("CustomWorkHandler: %s LoggingEvent: %s %s\n"
,name, message.getSvcOgNo() ,message.getLogPssSno())
);
}
EAILogSender.logDirect(event.getMessage(), event.getProperty());
if(event != null) {
event.clear();
event = null;
}
}
}
private void processBatch() throws EAILogException {
for(LoggingEvent event:eventList) {
EAILogSender.logDirect(event.getMessage(), event.getProperty());
}
}
}
@@ -0,0 +1,21 @@
package com.eactive.eai.common.logger.async;
import java.util.concurrent.ThreadFactory;
public class CustomThreadFactory implements ThreadFactory {
// stores the thread count
private int count = 0;
// returns the thread count
public int getCount() { return count; }
// Factory method
@Override
public Thread newThread(Runnable command) {
count++;
// System.out.println( String.format(">> newThread-%d created", count) );
return new Thread(command);
}
public CustomThreadFactory() {
// empty
}
}
@@ -0,0 +1,61 @@
package com.eactive.eai.common.logger.async;
import java.util.ArrayList;
import java.util.List;
import com.eactive.eai.common.logger.EAILogException;
import com.eactive.eai.common.logger.EAILogSender;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.util.Logger;
import com.lmax.disruptor.WorkHandler;
public class CustomWorkHandler implements WorkHandler<LoggingEvent> {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
String name;
int sleepMs;
private int batchSize = 1;
private int count = 0;
private final List<LoggingEvent> eventList = new ArrayList<>();
public CustomWorkHandler() {
}
public CustomWorkHandler(String name, int sleepMs, int batchSize) {
this.name = name;
this.sleepMs = sleepMs;
this.batchSize = batchSize;
}
@Override
public void onEvent(LoggingEvent event) throws Exception {
if(sleepMs > 0) Thread.sleep(sleepMs);
if(batchSize > 1) {
eventList.add(event);
if (++count >= batchSize) {
processBatch();
eventList.clear();
count = 0;
}
}
else {
EAIMessage message = event.getMessage();
if(logger.isInfo()) {
logger.info(String.format("CustomWorkHandler: %s LoggingEvent: %s %s\n"
,name, message.getSvcOgNo() ,message.getLogPssSno())
);
}
EAILogSender.logDirect(event.getMessage(), event.getProperty());
if(event != null) {
event.clear();
event = null;
}
}
}
private void processBatch() throws EAILogException {
for(LoggingEvent event:eventList) {
EAILogSender.logDirect(event.getMessage(), event.getProperty());
}
}
}
@@ -0,0 +1,122 @@
package com.eactive.eai.common.logger.async;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.util.LogKeys;
import com.eactive.eai.data.entity.onl.logger.HttpAdapterExtraHeader;
import com.eactive.eai.data.entity.onl.logger.HttpAdapterExtraLog;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.commons.io.FilenameUtils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
import java.util.Stack;
public class HttpAdapterExtraLogH2Factory {
private SessionFactory sessionFactory ;
private HikariDataSource dataSource;
private static HttpAdapterExtraLogH2Factory httpAdapterExtraLogH2Factory = new HttpAdapterExtraLogH2Factory();
private HttpAdapterExtraLogH2Factory(){
sessionFactory = buildSessionFactory();
}
public static HttpAdapterExtraLogH2Factory getInstance(){
return httpAdapterExtraLogH2Factory;
}
private SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
configuration.setProperty("hibernate.hbm2ddl.auto", "update");
configuration.setProperty("hibernate.show_sql", "true");
configuration.setProperty("hibernate.format_sql", "true");
configuration.setProperty("hibernate.use_sql_comments", "true");
configuration.setProperty("hibernate.auto_quote_keyword", "true");
configuration.setProperty("hibernate.globally_quoted_identifiers", "true");
String logBaseDirectory = PropManager.getInstance().getProperty(LogKeys.LOGGER_INFO, LogKeys.LOG_DIRECOTRY_PREFIX);
String localServer = EAIServerManager.getInstance().getLocalServerName();
String serverLogPath = FilenameUtils.concat(logBaseDirectory, localServer);
makeDirs(serverLogPath);
String httpLogDbFilePath = FilenameUtils.concat(serverLogPath, "http_log");
httpLogDbFilePath = httpLogDbFilePath.replace("\\", "/");
// HikariCP 설정
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setDriverClassName("org.h2.Driver");
hikariConfig.setJdbcUrl("jdbc:h2:file:"+httpLogDbFilePath);
hikariConfig.setUsername("sa");
hikariConfig.setPassword("");
hikariConfig.setMaximumPoolSize(20);
hikariConfig.setMinimumIdle(5);
hikariConfig.setIdleTimeout(300000);
hikariConfig.setMaxLifetime(600000);
dataSource = new HikariDataSource(hikariConfig);
configuration.getProperties().put("hibernate.connection.datasource", dataSource);
// 엔티티 클래스 추가
configuration.addAnnotatedClass(HttpAdapterExtraLog.class);
configuration.addAnnotatedClass(HttpAdapterExtraHeader.class);
return configuration.buildSessionFactory();
} catch (Throwable ex) {
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
public synchronized Session openSession(){
if(sessionFactory == null || sessionFactory.isClosed()){
sessionFactory = buildSessionFactory();
}
return sessionFactory.openSession();
}
public void closeSessionFactory() {
if (sessionFactory != null && !sessionFactory.isClosed()) {
sessionFactory.close();
sessionFactory = null;
}
if (dataSource != null && dataSource instanceof HikariDataSource) {
dataSource.close();
}
}
private static void makeDirs(String path) throws Exception{
File directory = new File(path);
if (directory.exists()){
return;
}
Stack<File> stack = new Stack<File>();
//check
File p = directory;
stack.push(p);
while (true){
p = p.getParentFile();
if (p.exists()){
break;
}else{
stack.push(p);
}
}
while(!stack.empty()){
File s = stack.pop();
s.mkdir();
//그룹까지 rwx로 권한이 필요한 경우가 많음 필요 시 수정 할 것
Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrwxr-x");
Files.setPosixFilePermissions(s.toPath(), perms);
}
}
}
@@ -0,0 +1,16 @@
package com.eactive.eai.common.logger.async;
import com.eactive.eai.common.logger.HttpAdapterExtraLogVo;
import com.lmax.disruptor.EventFactory;
import lombok.Data;
@Data
public class HttpLoggingEvent {
private HttpAdapterExtraLogVo httpAdapterExtraLogVo;
public final static EventFactory<HttpLoggingEvent> EVENT_FACTORY = new EventFactory<HttpLoggingEvent>() {
public HttpLoggingEvent newInstance() {
return new HttpLoggingEvent();
}
};
}
@@ -0,0 +1,117 @@
package com.eactive.eai.common.logger.async;
import com.eactive.eai.common.logger.HttpAdapterExtraLogVo;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.env.ConfigKeys;
import com.lmax.disruptor.*;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import org.jetbrains.annotations.NotNull;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
public class HttpLoggingPoolObject {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
Disruptor<HttpLoggingEvent> disruptor = null;
RingBuffer<HttpLoggingEvent> ringBuffer = null;
int id = 0;
int queueMax = (int)Math.pow(2, 10);
int workerSize = 0;
public HttpLoggingPoolObject() {
}
private WaitStrategy getWaitStrategy(String waitStrategy) {
WaitStrategy ws = null;
if(ConfigKeys.LOGGER_ASYNC_WAITSTRATEGY_BLOCK.equals(waitStrategy)) {
// throughput and low-latency are not as important as CPU resource
return new BlockingWaitStrategy();
}
if(ConfigKeys.LOGGER_ASYNC_WAITSTRATEGY_SLEEP.equals(waitStrategy)) {
// default : 200, 100ns
// return new SleepingWaitStrategy();
// default : 200, 10 ms
return new SleepingWaitStrategy(200, 10 * 1000000);
}
if(ConfigKeys.LOGGER_ASYNC_WAITSTRATEGY_TIME.equals(waitStrategy)) {
// 100ms
return new TimeoutBlockingWaitStrategy(100 * 1000, TimeUnit.MICROSECONDS);
}
if(ConfigKeys.LOGGER_ASYNC_WAITSTRATEGY_BUSYSPIN.equals(waitStrategy)) {
// when threads can be bound to specific CPU cores.
return new BusySpinWaitStrategy();
}
if(ConfigKeys.LOGGER_ASYNC_WAITSTRATEGY_YIELD.equals(waitStrategy)) {
return new YieldingWaitStrategy();
}
return ws;
}
public HttpLoggingPoolObject(int id, int queueSize, int workerSize, String waitStrategy) {
this.id = id;
if(logger.isWarn()) {
logger.warn(String.format(">> Disruptor-%d queueSize = %d", id, queueSize));
logger.warn(String.format(">> Disruptor-%d workerSize = %d", id, workerSize));
logger.warn(String.format(">> Disruptor-%d waitStrategy = %s", id, waitStrategy));
}
CustomThreadFactory tFactory = new CustomThreadFactory();
disruptor = new Disruptor<HttpLoggingEvent>(HttpLoggingEvent.EVENT_FACTORY, queueSize, tFactory,
ProducerType.SINGLE,
getWaitStrategy(waitStrategy));
// BlockingWaitStrategy | SleepingWaitStrategy | YieldingWaitStrategy | BusySpinWaitStrategy
WorkHandler<HttpLoggingEvent>[] handlers = new WorkHandler[workerSize];
for(int i=0; i< handlers.length; i++) {
WorkHandler handler = new HttpLoggingWorkHandler();
handlers[i] = handler;
}
disruptor.handleEventsWithWorkerPool(handlers);
try {
logger.warn(String.format(">> disruptor-%d.start",id));
disruptor.start();
ringBuffer = disruptor.getRingBuffer();
}
catch(Exception ex) {
ex.printStackTrace();
}
finally {
;
}
}
public void putMessage(HttpAdapterExtraLogVo httpAdapterExtraLogVo) {
long seq = ringBuffer.next();
try {
if(logger.isDebug()) {
logger.debug( String.format("disruptor-%d publish : ringBuffer seq = %d uuid=%s",id, seq, httpAdapterExtraLogVo.getGuid()) );
}
HttpLoggingEvent httpLoggingEvent = ringBuffer.get(seq);
httpLoggingEvent.setHttpAdapterExtraLogVo(httpAdapterExtraLogVo);
}
finally {
ringBuffer.publish(seq);
}
}
public void shutdown() {
if(disruptor == null) return;
while(true) {
if(queueMax == disruptor.getRingBuffer().remainingCapacity()) break;
try {
logger.warn(String.format("disruptor-%d Sleep 100 ms.", id));
Thread.sleep(100);
} catch (InterruptedException e) {
;
}
}
if(logger.isWarn()) {
logger.warn(String.format("<< disruptor-%d shutdown remainingCapacity : %d",id, disruptor.getRingBuffer().remainingCapacity()) );
}
if(disruptor !=null) disruptor.shutdown();
}
}
@@ -0,0 +1,42 @@
package com.eactive.eai.common.logger.async;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.env.ElinkConfig;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
public class HttpLoggingPoolObjectFactory extends BasePooledObjectFactory<HttpLoggingPoolObject> {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
private static int i = 0;
public HttpLoggingPoolObjectFactory() {
// empty
}
@Override
public HttpLoggingPoolObject create() throws Exception {
int queueSize = ElinkConfig.getAsyncQueueSize();
int workers = ElinkConfig.getAsyncWorkers();
String waitStrategy = ElinkConfig.getWaitStrategy();
return new HttpLoggingPoolObject(i++, queueSize, workers, waitStrategy);
}
@Override
public PooledObject<HttpLoggingPoolObject> wrap(HttpLoggingPoolObject object) {
return new DefaultPooledObject<>(object);
}
@Override
public void passivateObject(PooledObject<HttpLoggingPoolObject> pooledObject) {
// empty
}
@Override
public void destroyObject(PooledObject<HttpLoggingPoolObject> pooledObject) {
HttpLoggingPoolObject loggingPoolObject = pooledObject.getObject();
if(logger.isWarn()) {
logger.warn("destroyObject - {}", loggingPoolObject.toString());
}
loggingPoolObject.shutdown();
}
}
@@ -0,0 +1,19 @@
package com.eactive.eai.common.logger.async;
import com.eactive.eai.common.logger.HttpLoggingService;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.common.util.Logger;
import com.lmax.disruptor.WorkHandler;
public class HttpLoggingWorkHandler implements WorkHandler<HttpLoggingEvent> {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
@Override
public void onEvent(HttpLoggingEvent httpLoggingEvent) throws Exception {
HttpLoggingService service = ApplicationContextProvider.getContext().getBean(HttpLoggingService.class);
try {
service.insertHttpAdapterExtraLog( httpLoggingEvent.getHttpAdapterExtraLogVo());
} catch (Throwable th) {
logger.error("failed to insert async http log ", th);
}
}
}
@@ -0,0 +1,41 @@
package com.eactive.eai.common.logger.async;
import java.util.Properties;
import com.eactive.eai.common.message.EAIMessage;
import com.lmax.disruptor.EventFactory;
public class LoggingEvent {
EAIMessage message;
Properties prop;
public EAIMessage getMessage() {
return message;
}
public void setMessage(EAIMessage message) {
this.message = message;
}
public Properties getProperty() {
return prop;
}
public void setProperty(Properties prop) {
this.prop = prop;
}
public void clear() {
if(this.message != null) {
this.message.clear();
}
this.message = null;
this.prop = null;
}
public final static EventFactory<LoggingEvent> EVENT_FACTORY = new EventFactory<LoggingEvent>() {
public LoggingEvent newInstance() {
return new LoggingEvent();
}
};
}
@@ -0,0 +1,130 @@
package com.eactive.eai.common.logger.async;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.env.ConfigKeys;
import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.BusySpinWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.SleepingWaitStrategy;
import com.lmax.disruptor.TimeoutBlockingWaitStrategy;
import com.lmax.disruptor.WaitStrategy;
import com.lmax.disruptor.WorkHandler;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
public class LoggingPoolObject {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
Disruptor<LoggingEvent> disruptor = null;
RingBuffer<LoggingEvent> ringBuffer = null;
int id = 0;
int queueMax = (int)Math.pow(2, 10);
int workerSize = 0;
public LoggingPoolObject() {
}
private WaitStrategy getWaitStrategy(String waitStrategy) {
WaitStrategy ws = null;
if(ConfigKeys.LOGGER_ASYNC_WAITSTRATEGY_BLOCK.equals(waitStrategy)) {
// throughput and low-latency are not as important as CPU resource
return new BlockingWaitStrategy();
}
if(ConfigKeys.LOGGER_ASYNC_WAITSTRATEGY_SLEEP.equals(waitStrategy)) {
// default : 200, 100ns
// return new SleepingWaitStrategy();
// default : 200, 10 ms
return new SleepingWaitStrategy(200, 10 * 1000000);
}
if(ConfigKeys.LOGGER_ASYNC_WAITSTRATEGY_TIME.equals(waitStrategy)) {
// 100ms
return new TimeoutBlockingWaitStrategy(100 * 1000, TimeUnit.MICROSECONDS);
}
if(ConfigKeys.LOGGER_ASYNC_WAITSTRATEGY_BUSYSPIN.equals(waitStrategy)) {
// when threads can be bound to specific CPU cores.
return new BusySpinWaitStrategy();
}
if(ConfigKeys.LOGGER_ASYNC_WAITSTRATEGY_YIELD.equals(waitStrategy)) {
return new YieldingWaitStrategy();
}
return ws;
}
public LoggingPoolObject(int id, int queueSize, int workerSize, String waitStrategy) {
this.id = id;
if(logger.isWarn()) {
logger.warn(String.format(">> Disruptor-%d queueSize = %d", id, queueSize));
logger.warn(String.format(">> Disruptor-%d workerSize = %d", id, workerSize));
logger.warn(String.format(">> Disruptor-%d waitStrategy = %s", id, waitStrategy));
}
CustomThreadFactory tFactory = new CustomThreadFactory();
disruptor = new Disruptor<LoggingEvent>(LoggingEvent.EVENT_FACTORY, queueSize, tFactory,
ProducerType.SINGLE,
getWaitStrategy(waitStrategy));
// BlockingWaitStrategy | SleepingWaitStrategy | YieldingWaitStrategy | BusySpinWaitStrategy
if(workerSize > 1) {
WorkHandler<LoggingEvent>[] handlers = new WorkHandler[workerSize];
for(int i=0; i< handlers.length; i++) {
// TODO : 현재는 delay 없이 처리하도록 하고, 추후 DB부하를 줄이려면 sleep을 정의.
CustomWorkHandler handler = new CustomWorkHandler(String.format("CustomWorkHandler%d-%d",id, i), 0, 1);
handlers[i] = handler;
}
disruptor.handleEventsWithWorkerPool(handlers);
}
else {
CustomEventHandler handler = new CustomEventHandler(String.format("CustomEventHandler%d-%d",id, 0), 0, 1);
disruptor.handleEventsWith(handler);
}
try {
logger.warn(String.format(">> disruptor-%d.start",id));
disruptor.start();
ringBuffer = disruptor.getRingBuffer();
}
catch(Exception ex) {
ex.printStackTrace();
}
finally {
;
}
}
public void putMessage(EAIMessage message, Properties prop) {
long seq = ringBuffer.next();
try {
if(logger.isDebug()) {
logger.debug( String.format("disruptor-%d publish : ringBuffer seq = %d uuid=%s logSeq=%s",id, seq, message.getSvcOgNo() ,message.getLogPssSno()) );
}
LoggingEvent loggingEvent = ringBuffer.get(seq);
loggingEvent.setMessage(message);
loggingEvent.setProperty(prop);
}
finally {
ringBuffer.publish(seq);
}
}
public void shutdown() {
if(disruptor == null) return;
while(true) {
if(queueMax == disruptor.getRingBuffer().remainingCapacity()) break;
try {
logger.warn(String.format("disruptor-%d Sleep 100 ms.", id));
Thread.sleep(100);
} catch (InterruptedException e) {
;
}
}
if(logger.isWarn()) {
logger.warn(String.format("<< disruptor-%d shutdown remainingCapacity : %d",id, disruptor.getRingBuffer().remainingCapacity()) );
}
if(disruptor !=null) disruptor.shutdown();
}
}
@@ -0,0 +1,42 @@
package com.eactive.eai.common.logger.async;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.env.ElinkConfig;
public class LoggingPoolObjectFactory extends BasePooledObjectFactory<LoggingPoolObject> {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
private static int i = 0;
public LoggingPoolObjectFactory() {
// empty
}
@Override
public LoggingPoolObject create() throws Exception {
int queueSize = ElinkConfig.getAsyncQueueSize();
int workers = ElinkConfig.getAsyncWorkers();
String waitStrategy = ElinkConfig.getWaitStrategy();
return new LoggingPoolObject(i++, queueSize, workers, waitStrategy);
}
@Override
public PooledObject<LoggingPoolObject> wrap(LoggingPoolObject object) {
return new DefaultPooledObject<>(object);
}
@Override
public void passivateObject(PooledObject<LoggingPoolObject> pooledObject) {
// empty
}
@Override
public void destroyObject(PooledObject<LoggingPoolObject> pooledObject) {
LoggingPoolObject loggingPoolObject = pooledObject.getObject();
if(logger.isWarn()) {
logger.warn("destroyObject - {}", loggingPoolObject.toString());
}
loggingPoolObject.shutdown();
}
}
@@ -0,0 +1,26 @@
package com.eactive.eai.common.logger.async;
public class PoolShutdownException extends Exception {
public PoolShutdownException() {
super("pool is shutdown already.");
}
public PoolShutdownException(String message) {
super(message);
}
public PoolShutdownException(Throwable cause) {
super(cause);
}
public PoolShutdownException(String message, Throwable cause) {
super(message, cause);
}
public PoolShutdownException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
@@ -0,0 +1,22 @@
package com.eactive.eai.common.logger.mapper;
import com.eactive.eai.common.logger.HttpAdapterExtraHeaderVo;
import com.eactive.eai.data.entity.onl.logger.HttpAdapterExtraHeader;
import com.eactive.eai.data.mapper.BaseMapperConfig;
import com.eactive.eai.data.mapper.GenericMapper;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
@Mapper(config = BaseMapperConfig.class)
public interface HttpAdapterExtraHeaderMapper extends GenericMapper<HttpAdapterExtraHeaderVo, HttpAdapterExtraHeader> {
@Override
@Mapping(source = "id.name", target = "name")
HttpAdapterExtraHeaderVo toVo(HttpAdapterExtraHeader entity);
@Override
@InheritInverseConfiguration
HttpAdapterExtraHeader toEntity(HttpAdapterExtraHeaderVo vo);
}
@@ -0,0 +1,42 @@
package com.eactive.eai.common.logger.mapper;
import com.eactive.eai.common.logger.HttpAdapterExtraLogVo;
import com.eactive.eai.data.entity.onl.logger.HttpAdapterExtraHeaderId;
import com.eactive.eai.data.entity.onl.logger.HttpAdapterExtraLog;
import com.eactive.eai.data.mapper.BaseMapperConfig;
import com.eactive.eai.data.mapper.GenericMapper;
import org.mapstruct.*;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.Optional;
@Mapper(config = BaseMapperConfig.class, uses = HttpAdapterExtraHeaderMapper.class)
public interface HttpAdapterExtraLogMapper extends GenericMapper<HttpAdapterExtraLogVo, HttpAdapterExtraLog> {
@Override
@Mapping(source = "id.guid", target = "guid")
@Mapping(source = "id.serviceProcessNumber", target = "serviceProcessNumber")
HttpAdapterExtraLogVo toVo(HttpAdapterExtraLog entity);
@Override
@InheritInverseConfiguration
HttpAdapterExtraLog toEntity(HttpAdapterExtraLogVo vo);
@AfterMapping
default void setHeaderIdAndWeekday(@MappingTarget HttpAdapterExtraLog entity, HttpAdapterExtraLogVo vo) {
DayOfWeek dayOfWeek = LocalDate.now().getDayOfWeek(); // 현재 요일
int dayOfWeekNumber = dayOfWeek.getValue() % 7 + 1; // 1 (일요일)부터 7 (토요일)까지
entity.getId().setWeekday(dayOfWeekNumber);
Optional.ofNullable(entity.getHeaderList())
.ifPresent(headers -> headers.forEach(header -> {
if (header.getId() == null) {
header.setId(new HttpAdapterExtraHeaderId());
}
header.getId().setWeekday(dayOfWeekNumber);
header.getId().setGuid(vo.getGuid());
header.getId().setServiceProcessNumber(vo.getServiceProcessNumber());
}));
}
}
@@ -0,0 +1,42 @@
package com.eactive.eai.common.logger.mapper;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import com.eactive.eai.common.monitor.StatMonitorLogVO;
import com.eactive.eai.data.entity.onl.logger.StatAdapterLog;
import com.eactive.eai.data.mapper.BaseMapperConfig;
import com.eactive.eai.data.mapper.GenericMapper;
@Mapper(config = BaseMapperConfig.class)
public interface StatAdapterLogMapper extends GenericMapper<StatMonitorLogVO, StatAdapterLog> {
@Mapping(source = "id.baseymd", target = "ymd")
@Mapping(source = "id.basehh", target = "hour")
@Mapping(source = "id.basehhmm", target = "min")
@Mapping(source = "id.eaibzwkdstcd", target = "bzwkDstcd")
@Mapping(source = "id.eaisvcname", target = "svcName")
@Mapping(source = "id.adptrbzwkgroupname", target = "key")
@Mapping(source = "id.eaisevrinstncname", target = "sevrInstncName")
@Mapping(source = "eaiprcssttmval", target = "prcssTtmVal", qualifiedByName = "devide")
@Mapping(source = "eaipsvprcssttmval", target = "psvPrcssTtmVal", qualifiedByName = "devide")
@Mapping(source = "eaitotalprcssttmval", target = "totalPrcssTtmVal", qualifiedByName = "devide")
@Mapping(source = "wholprcssnoitm", target = "wholPrcssNoitm")
@Mapping(source = "errznoitm", target = "errzNoitm")
@Mapping(source = "toutnoitm", target = "toutNoitm")
@Mapping(source = "nomalnoitm", target = "nomalNoitm")
@Override
StatMonitorLogVO toVo(StatAdapterLog entity);
@Named("devide")
default Double devide(Double org) {
return org / 1000;
}
@InheritInverseConfiguration
@Override
StatAdapterLog toEntity(StatMonitorLogVO vo);
}
@@ -0,0 +1,41 @@
package com.eactive.eai.common.logger.mapper;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import com.eactive.eai.common.monitor.StatMonitorLogVO;
import com.eactive.eai.data.entity.onl.logger.StatLog;
import com.eactive.eai.data.mapper.BaseMapperConfig;
import com.eactive.eai.data.mapper.GenericMapper;
@Mapper(config = BaseMapperConfig.class)
public interface StatLogMapper extends GenericMapper<StatMonitorLogVO, StatLog> {
@Mapping(source = "id.baseymd", target = "ymd")
@Mapping(source = "id.basehh", target = "hour")
@Mapping(source = "id.basehhmm", target = "min")
@Mapping(source = "id.eaibzwkdstcd", target = "bzwkDstcd")
@Mapping(source = "id.eaisvcname", target = "svcName")
@Mapping(source = "id.eaisevrinstncname", target = "sevrInstncName")
@Mapping(source = "eaiprcssttmval", target = "prcssTtmVal", qualifiedByName = "devide")
@Mapping(source = "eaipsvprcssttmval", target = "psvPrcssTtmVal", qualifiedByName = "devide")
@Mapping(source = "eaitotalprcssttmval", target = "totalPrcssTtmVal", qualifiedByName = "devide")
@Mapping(source = "wholprcssnoitm", target = "wholPrcssNoitm")
@Mapping(source = "errznoitm", target = "errzNoitm")
@Mapping(source = "toutnoitm", target = "toutNoitm")
@Mapping(source = "nomalnoitm", target = "nomalNoitm")
@Override
StatMonitorLogVO toVo(StatLog entity);
@Named("devide")
default Double devide(Double org) {
return org / 1000;
}
@InheritInverseConfiguration
@Override
StatLog toEntity(StatMonitorLogVO vo);
}
@@ -0,0 +1,42 @@
package com.eactive.eai.common.logger.mapper;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import com.eactive.eai.common.monitor.StatMonitorLogVO;
import com.eactive.eai.data.entity.onl.logger.StatTranLog;
import com.eactive.eai.data.mapper.BaseMapperConfig;
import com.eactive.eai.data.mapper.GenericMapper;
@Mapper(config = BaseMapperConfig.class)
public interface StatTranLogMapper extends GenericMapper<StatMonitorLogVO, StatTranLog> {
@Mapping(source = "id.baseymd", target = "ymd")
@Mapping(source = "id.basehh", target = "hour")
@Mapping(source = "id.basehhmm", target = "min")
@Mapping(source = "id.eaibzwkdstcd", target = "bzwkDstcd")
@Mapping(source = "id.eaisvcname", target = "svcName")
@Mapping(source = "id.intfacsendtrancd", target = "key")
@Mapping(source = "id.eaisevrinstncname", target = "sevrInstncName")
@Mapping(source = "eaiprcssttmval", target = "prcssTtmVal", qualifiedByName = "devide")
@Mapping(source = "eaipsvprcssttmval", target = "psvPrcssTtmVal", qualifiedByName = "devide")
@Mapping(source = "eaitotalprcssttmval", target = "totalPrcssTtmVal", qualifiedByName = "devide")
@Mapping(source = "wholprcssnoitm", target = "wholPrcssNoitm")
@Mapping(source = "errznoitm", target = "errzNoitm")
@Mapping(source = "toutnoitm", target = "toutNoitm")
@Mapping(source = "nomalnoitm", target = "nomalNoitm")
@Override
StatMonitorLogVO toVo(StatTranLog entity);
@Named("devide")
default Double devide(Double org) {
return org / 1000;
}
@InheritInverseConfiguration
@Override
StatTranLog toEntity(StatMonitorLogVO vo);
}