实现单机线程ID打印

1.创建拦截器

package com.test.edu.config;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Slf4j
public class LogInterceptor implements HandlerInterceptor {
    //线程ID常量
    private static final String THREAD_ID = "THREAD_ID";


    /**
     * controller方法前调用
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        log.debug("preHandle running ...");
        //使用UUID生成唯一编号
        String threadId = UUID.randomUUID().toString().trim().replaceAll("-", "");
        //判断MDC(log4j中的上下文对象) 中是否有该threadId
        if (StringUtils.isEmpty(MDC.get(THREAD_ID))) {
            //如果没有,添加
            MDC.put(THREAD_ID,threadId);
        }
        //永远返回true
        return true;
    }

    /**
     * preHandle方法返回true之后
     * 在controller方法处理完之后调用
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object, ModelAndView modelAndView) throws Exception {
        log.debug("postHandle running ...");
        //controller结束之后删除对应的唯一值
        MDC.remove(THREAD_ID);
    }

    /**
     * preHandle方法返回true之后
     * 在DispatcherServlet进行视图的渲染之后调用
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object, Exception e) throws Exception {
        log.debug("afterCompletion running ...");
    }
}

2.实例化

package com.test.edu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class ApplicationWebMvcConfig implements WebMvcConfigurer {
    /**
     * 注解LogInterceptor类到IOC容器中
     */
    @Bean
    public LogInterceptor logInterceptor() {
        return new LogInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册日志拦截器
        registry.addInterceptor(logInterceptor());
    }
}

3.xml


<configuration>

    <springProperty scope="context" name="LOG_HOME" source="log.path"/>

    <property name="CONSOLE_LOG_PATTERN"
              value="%red(%d{HH:mm:ss})-%green([%X{THREAD_ID}])-%highlight(%-5level[%4line])-%boldMagenta(%logger{10}) : %cyan(%msg%n)"/>


    
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder charset="UTF-8">
            <pattern>${CONSOLE_LOG_PATTERN}pattern>
            <charset>UTF-8charset>
        encoder>
    appender>
    


    
    <appender name="INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${LOG_HOME}/info.logFile>
        <append>trueappend>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFOlevel>
        filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/info.log.%dfileNamePattern>
            <maxHistory>365maxHistory>
        rollingPolicy>
        <encoder charset="UTF-8">
            <pattern>${CONSOLE_LOG_PATTERN}pattern>
            <charset>UTF-8charset>
        encoder>
    appender>
    


    
    <appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${LOG_HOME}/error.logFile>
        <append>trueappend>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERRORlevel>
            <onMatch>ACCEPTonMatch>
            <onMismatch>DENYonMismatch>
        filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/error.log.%dfileNamePattern>
            <maxHistory>365maxHistory>
        rollingPolicy>
        <encoder charset="UTF-8">
            <pattern>${CONSOLE_LOG_PATTERN}pattern>
            <charset>UTF-8charset>
        encoder>
    appender>
    


    <springProfile name="dev,test">
        <root level="INFO">
            <appender-ref ref="CONSOLE"/>
        root>
        <logger name="com.test.edu.mapper" level="debug" additivity="false">
            <appender-ref ref="CONSOLE"/>
            <appender-ref ref="INFO"/>
        logger>
    springProfile>
    <springProfile name="dev,test">
        <root level="INFO">
            <appender-ref ref="INFO"/>
            <appender-ref ref="ERROR"/>
        root>
    springProfile>
configuration>

你可能感兴趣的:(随笔,java,spring,servlet)