logback日志打印操作人

logback日志打印操作人

自定义拦截器

java 复制代码
package com.demo.dv.net.config;

import com.demo.dv.net.common.domain.UserInfo;
import com.demo.dv.net.common.utils.CurrentUserUtil;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            //获取当前登录的用户
            UserInfo currentUser = CurrentUserUtil.getCurrentUser();
            MDC.put("user", currentUser.getFullUsername());
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        MDC.clear();
    }
}

注册拦截器

java 复制代码
package com.demo.dv.net.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Autowired
    private AuthInterceptor authInterceptor;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }

    /**
     * {@inheritDoc}
     * <p>This implementation is empty.
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor)
                .addPathPatterns("/**"); //所有的请求都要拦截。
    }
}

配置logback文件

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <property name="PROJECT_NAME" value="net"/>
    <property name="LOG_HOME" value="${LOG_PATH}"/>
    <property name="LOG_FILE"
              value="${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}}/all.${tomcat.port:-net}.log"/>
    <property name="LOG_FILE_ERR"
              value="${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}}/error.${tomcat.port:-net}.log"/>
    <property name="log_pattern"
              value="%d{yyyy-MM-dd HH:mm:ss.SSS} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] %-40.40logger{39}:%L : [TxId : %X{PtxId} , SpanId : %X{PspanId}] %X{user} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>

    <contextName>${PROJECT_NAME}</contextName>

    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <!--    <include resource="org/springframework/boot/logging/logback/console-appender.xml"/>-->
    <include resource="audit-elk-appender.xml"/>
    <jmxConfigurator/>

    <appender name="ALL_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_FILE}</file>
        <encoder>
            <pattern>
                ${log_pattern}
            </pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.%i</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>512MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>

    <appender name="ERR_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>ERROR</level>
        </filter>
        <encoder>
            <pattern>
                ${log_pattern}
            </pattern>
        </encoder>
        <file>${LOG_FILE_ERR}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_FILE_ERR}.%d{yyyy-MM-dd}.%i</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>512MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>
                ${log_pattern}
            </pattern>
            <charset>utf8</charset>
        </encoder>
    </appender>
    <root level="INFO">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="ALL_LOG"/>
        <appender-ref ref="ERR_LOG"/>
    </root>

    <!-- logger level统一在application-xx配置文件中设置 -->

</configuration>
相关推荐
空の鱼4 小时前
java开发,IDEA转战VSCODE配置(mac)
java·vscode
!!!5254 小时前
日志技术-LogBack入门程序&Log配置文件&日志级别
spring boot
P7进阶路4 小时前
Tomcat异常日志中文乱码怎么解决
java·tomcat·firefox
小丁爱养花5 小时前
Spring MVC:HTTP 请求的参数传递2.0
java·后端·spring
CodeClimb5 小时前
【华为OD-E卷 - 第k个排列 100分(python、java、c++、js、c)】
java·javascript·c++·python·华为od
等一场春雨5 小时前
Java设计模式 九 桥接模式 (Bridge Pattern)
java·设计模式·桥接模式
带刺的坐椅5 小时前
[Java] Solon 框架的三大核心组件之一插件扩展体系
java·ioc·solon·plugin·aop·handler
不惑_6 小时前
深度学习 · 手撕 DeepLearning4J ,用Java实现手写数字识别 (附UI效果展示)
java·深度学习·ui
费曼乐园6 小时前
Kafka中bin目录下面kafka-run-class.sh脚本中的JAVA_HOME
java·kafka
feilieren7 小时前
SpringBoot 搭建 SSE
java·spring boot·spring