Location>code7788 >text

spring project implements logging with request link ids

Popularity:237 ℃/2024-12-19 20:10:37

We do java projects usually need to request logs to troubleshoot and locate online problems, in the logs are more and we need to find the entire request of all the logs will be more difficult. Therefore, the need for logging time to talk about the same request for key logs with the same unique identity in series. So that when you look for it will be better to find. The following to use java aop to realize the request id logging. (The support for sub-thread inheritance of the main thread request id)

One: First we need a log request link id cutout class

Note: If multithreading is not considered then (steps 2 and 3 can be left out)

package .iMagine_pro.aop;

import .iMagine_common.;
import .iMagine_pro.;
import .slf4j.Slf4j;
import ;
import ;
import ;
import ;
import org.;
import ;


/**
* @author name one
* @ClassName TraceIdAspect
* @description: Log request linkidsectioning
* @datetime 2024surname Nian 12moon 16date 14:28
* @version: 1.0
*/
@Slf4j
@Aspect
@Component
public class TraceIdAspect {

/** Link trace id */
public final static String TRACE_ID = "TRACE_ID";
/** Users */
public final static String USER = "USER";

/**
* linkidTangent Point Definition
*/
@Pointcut("execution(* .iMagine_pro.controller.*.*(..))")
public void TraceIdCut() {

}

/**
* linkidincrease
*/
@Before("TraceIdCut()")
public void cutProcessBefore() {
(TRACE_ID, ());
//The following code is for logging user information,Facilitates more intuitive identification of log operator information。If you don't need it, you can delete the following part
String nickname = ();
if (null == nickname){
nickname = "Visitor access";
}
(USER, nickname);
}

/**
* linkidremovals
*/
@After("TraceIdCut()")
public void cutProcessAfter() {
();
}
}
package .iMagine_common.utils;

import ;

/**
 * @author Name I
 * @ClassName UUIDUtil
 * @description: UUID tool class
 * @datetime 2024 Apr 23 11:49
 * @datetime@version: 1.0
 */
public class UUIDUtil {

    /**
     * Get UUID
     *
     *@return
     */
    public static String getUUID() {
        //Produce uuid and remove the short horizontal line from the uuid
        return ().toString().replace("-", "");
    }
}

 

II: Create a tool class that handles multi-threaded link tracing

package .iMagine_common.utils;

import .iMagine_common.;
import org.;

import ;

/**
* @author name one
* @ClassName ThreadMdcUtil
* @description: Multi-threaded link tracing tool class
* @datetime 2024surname Nian 12moon 16date 14:57
* @version: 1.0
*/
public class ThreadMdcUtil {

// Getting Unique Identifiers
public static String generateTraceId() {
return ();
}

public static void setTraceIdIfAbsent() {
if ((SysConstant.TRACE_ID) == null) {
(SysConstant.TRACE_ID, generateTraceId());
}
}

/**
* Used when the parent thread submits a task to the thread pool,general term for oneselfMDCThe data in the subthread is copied to the
*
* @param runnable Threads to be executed
* @param context The parent thread of themdc
* @return linkidPost-transmission mandate
*/
public static Runnable wrap(final Runnable runnable, final Map<String, String> context) {
return () -> {
if (context == null) {
();
} else {
(context);
}
setTraceIdIfAbsent();
try {
();
} finally {
();
}
};
}
}

 

III: Doing request link id passing when putting tasks into the thread pool

/**
* Thread Pool Additions [ai server Related operations(psot)]mandates
*
* @param task Tasks added
*/
public static void addSendPostThreadToThreadPool(SendPostThread task) {
("addSendPostThreadToThreadPool pool:{}, task:{}", pool, task);
try {
((task, ()));
} catch (Exception e) {
("addSendPostThreadToThreadPool error pool:{}, task:{}, e:", pool, task, e);
}
}

 

Four: Add the link tracking id to the log output format in the log configuration.

<!-- Log Output Format (included among these%X{TRACE_ID}bemdcLateral link requestid(used form a nominal expression)key,user-%X{USER}be用户信息(used form a nominal expression)key)-->
<property name="ENCODER_PATTERN" value="%d{yyyy-MM-dd HH:mm:} [%thread] %X{TRACE_ID} user-%X{USER} %-5level %logger{32}-[%line] - %msg%n"/>

 

This completes the spring project's implementation of logging with request link ids.