SpringBoot【logback 日志脱敏】

自定义PatternLayoutEncoder

package com.logback;

import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class LogbackPatternLayoutEncoder extends PatternLayoutEncoder {
    /**
     * 正则替换规则
     */
    private LogbackReplaces replaces;
    /**
     * 是否开启脱敏,默认关闭(false)
     */
    private Boolean sensitive = false;

    /**
     * 使用自定义TbspLogbackPatternLayout格式化输出
     */
    @Override
    public void start() {
        LogbackPatternLayout patternLayout = new LogbackPatternLayout(replaces, sensitive);
        patternLayout.setContext(context);
        patternLayout.setPattern(this.getPattern());
        patternLayout.setOutputPatternAsHeader(outputPatternAsHeader);
        patternLayout.start();
        this.layout = patternLayout;
        started = true;
    }

    public boolean isSensitive() {
        return sensitive;
    }

    public void setSensitive(boolean sensitive) {
        this.sensitive = sensitive;
    }

    public LogbackReplaces getReplaces() {
        return replaces;
    }

    public void setReplaces(LogbackReplaces replaces) {
        this.replaces = replaces;
    }


    @Slf4j
    public static class LogbackPatternLayout extends PatternLayout {
        /**
         * logger
         */
        /**
         * 正则替换规则
         */
        private LogbackReplaces replaces;
        /**
         * 是否开启脱敏,默认关闭(false)
         */
        private Boolean sensitive;

        public LogbackPatternLayout(LogbackReplaces replaces, Boolean sensitive) {
            super();
            this.replaces = replaces;
            this.sensitive = sensitive;
        }

        /**
         * 格式化日志信息
         *
         * @param event ILoggingEvent
         * @return 日志信息
         */
        @Override
        public String doLayout(ILoggingEvent event) {
            // 占位符填充
            String msg = super.doLayout(event);
            // 脱敏处理
            return this.buildSensitiveMsg(msg);
        }

        /**
         * 根据配置对日志进行脱敏
         *
         * @param msg 消息
         * @return 脱敏后的日志信息
         */
        public String buildSensitiveMsg(String msg) {
            if (sensitive == null || !sensitive) {
                // 未开启脱敏
                return msg;
            }
            if (this.replaces == null || this.replaces.getReplace() == null || this.replaces.getReplace().isEmpty()) {
                log.error("日志脱敏开启,但未配置脱敏规则,请检查配置后重试");
                return msg;
            }

            String sensitiveMsg = msg;

            for (RegexReplacement replace : this.replaces.getReplace()) {
                // 遍历脱敏正则 & 替换敏感数据
                sensitiveMsg = replace.format(sensitiveMsg);
            }
            return sensitiveMsg;
        }
    }

    public static class LogbackReplaces {
        /**
         * 脱敏正则列表
         */
        private List<RegexReplacement> replace = new ArrayList<>();
        /**
         * 添加规则(因为replace类型是list,必须指定addReplace方法用以添加多个)
         *
         * @param replacement replacement
         */
        public void addReplace(RegexReplacement replacement) {
            replace.add(replacement);
        }

        public List<RegexReplacement> getReplace() {
            return replace;
        }

        public void setReplace(List<RegexReplacement> replace) {
            this.replace = replace;
        }
    }

    public static class RegexReplacement {
        /**
         * 脱敏匹配正则
         */
        private Pattern regex;
        /**
         * 替换正则
         */
        private String replacement;
        /**
         * Perform the replacement.
         *
         * @param msg The String to match against.
         * @return the replacement String.
         */
        public String format(final String msg) {
            return regex.matcher(msg).replaceAll(replacement);
        }

        public Pattern getRegex() {
            return regex;
        }

        public void setRegex(String regex) {
            this.regex = Pattern.compile(regex);
        }

        public String getReplacement() {
            return replacement;
        }

        public void setReplacement(String replacement) {
            this.replacement = replacement;
        }
    }
}

配置logback.xml

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="com.logback.LogbackPatternLayoutEncoder">
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>utf8</charset>
            <sensitive>true</sensitive>
            <replaces>
				<replace>
                    <!-- 11位的手机号:保留前3后4 -->
                    <regex>
                        <![CDATA[
				(mobile|手机号)(=|=\[|\":\"|:|:|='|':')(1)([3-9]{1}\d{1})(\d{4})(\d{4})(\]|\"|'|)
							]]>
                    </regex>
                    <replacement>$1$2$3$4****$6$7</replacement>
                </replace>
                <replace>
                    <!--  密码 6位数字,全* -->
                    <regex>
                        <![CDATA[
					(password|密码|验证码)(=|=\[|\":\"|:|:|='|':')([a-z|A-Z|\d]{2,16})(\]|\"|'|)
							]]>
                    </regex>
                    <replacement>$1$2******$4</replacement>
                </replace>
            </replaces>
        </encoder>
    </appender>
(password|密码|验证码)(=|=\[|\":\"|:|:|='|':')([a-z|A-Z|\d]{4,16})(\]|\"|'|)
<replacement>$1$2******$4</replacement>
$1 匹配第一个括号的内容
$1$2******$4 代表隐藏第三个括号匹配的全部内容
    @Test
    void test() {
        log.info("{\"mobile\":\"15727331367\",\"password\":\"Abc123\"}");
    }
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值