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>
相关推荐
小周不摆烂1 小时前
Java Web从入门到精通:全面探索与实战(一)
java
cherryc_1 小时前
JavaSE基础——第六章 类与对象(二)
java·开发语言
快来卷java1 小时前
JVM虚拟机篇(三):JVM运行时数据区与方法区详解
java·jvm·mysql
whltaoin2 小时前
Java实现N皇后问题的双路径探索:递归回溯与迭代回溯算法详解
java·算法
nlog3n5 小时前
Java策略模式详解
java·bash·策略模式
Mryan20058 小时前
解决GraalVM Native Maven Plugin错误:JAVA_HOME未指向GraalVM Distribution
java·开发语言·spring boot·maven
VX_CXsjNo18 小时前
免费送源码:Java+SSM+Android Studio 基于Android Studio游戏搜索app的设计与实现 计算机毕业设计原创定制
java·spring boot·spring·游戏·eclipse·android studio·android-studio
ylfhpy8 小时前
Java面试黄金宝典33
java·开发语言·数据结构·面试·职场和发展·排序算法
乘风!8 小时前
Java导出excel,表格插入pdf附件,以及实现过程中遇见的坑
java·pdf·excel
小小鸭程序员8 小时前
Vue组件化开发深度解析:Element UI与Ant Design Vue对比实践
java·vue.js·spring·ui·elementui