org.kaizen4j.common.interceptor.LogSerialMethodInterceptor Maven / Gradle / Ivy
package org.kaizen4j.common.interceptor;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.RegExUtils;
import org.apache.commons.lang3.StringUtils;
import org.kaizen4j.common.base.LogSerial;
import org.kaizen4j.common.base.Symbols;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import java.util.UUID;
/**
* 方法日志序列号生成拦截器。使用示例:
*
*
* {@code
*
*
*
*
*
* }
*
*/
public class LogSerialMethodInterceptor implements MethodInterceptor {
private static final Logger logger = LoggerFactory.getLogger(LogSerialMethodInterceptor.class);
private static final Integer INIT_COUNT = 1;
private static final ThreadLocal invocationHolder = new ThreadLocal<>();
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
String serialNo = initSerialNo();
try {
return methodInvocation.proceed();
} catch (Exception e) {
logger.error("LogSerialMethodInterceptor exception", e);
throw new RuntimeException(e);
} finally {
clearSerialNo(serialNo);
}
}
private String initSerialNo() {
String serialNo = MDC.get(LogSerial.MDC_REQUEST_ID);
if (StringUtils.isBlank(serialNo)) {
serialNo = getSerialNo();
MDC.put(LogSerial.MDC_REQUEST_ID, serialNo);
invocationHolder.set(INIT_COUNT);
if (logger.isDebugEnabled()) {
logger.debug("Initialize log serial value: [{}] and invocation count: [{}]", serialNo, INIT_COUNT);
}
} else {
Integer count = invocationHolder.get();
if (null == count) {
invocationHolder.set(INIT_COUNT);
} else {
invocationHolder.set(++count);
if (logger.isDebugEnabled()) {
logger.debug("Increment invocation count to: [{}]", count);
}
}
}
return serialNo;
}
private String getSerialNo() {
return RegExUtils.replacePattern(UUID.randomUUID().toString(), Symbols.MINUS_SIGN, Symbols.EMPTY).toUpperCase();
}
private void clearSerialNo(String serialNo) {
int count = invocationHolder.get();
if (INIT_COUNT == count) {
MDC.remove(LogSerial.MDC_REQUEST_ID);
invocationHolder.remove();
if (logger.isDebugEnabled()) {
logger.debug("Remove log serial value: [{}] and invocation count: [{}]", serialNo, count);
}
} else {
invocationHolder.set(--count);
if (logger.isDebugEnabled()) {
logger.debug("Decrement invocation count to: [{}]", count);
}
}
}
}