V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
xudzhang
V2EX  ›  Java

log4j 如何在打 log 的时候屏蔽部分信息?

  •  
  •   xudzhang · 2019-02-10 13:14:16 +08:00 · 2650 次点击
    这是一个创建于 1894 天前的主题,其中的信息可能已经有所发展或是发生改变。

    有一个 String 类型的变量 httpRequest,内容如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <request username="my_username" password="my_password">
        <do-some-action id="1001">
        </do-some-action>
    </request>
    

    希望把这个变量 log 下来,但是 username 和 password 的值不能被 log:

    logger.info("HTTP Request: {}", httpRequest);
    

    log 出来最好是像下面的样子,实现这一点有什么好的方法?

    <?xml version="1.0" encoding="UTF-8"?>
    <request username="******" password="******">
        <do-some-action id="1001">
        </do-some-action>
    </request>
    
    2 条回复    2019-02-10 14:09:16 +08:00
    PazuLee
        1
    PazuLee  
       2019-02-10 13:23:54 +08:00   ❤️ 1
    日志 log 之前用正则做处理?
    freedomSky
        2
    freedomSky  
       2019-02-10 14:09:16 +08:00   ❤️ 1
    覆盖 org.apache.log4j.PatternLayout 这个类,改写里面的 format 方法,我这里原来日志里是
    <XXX_PASSWD>我是密码</XXX_PASSWD>
    ,只是改了 return 那句,供参考

    /**
    Produces a formatted string as specified by the conversion pattern.
    */
    public String format(LoggingEvent event) {
    // Reset working stringbuffer
    if(sbuf.capacity() > MAX_CAPACITY) {
    sbuf = new StringBuffer(BUF_SIZE);
    } else {
    sbuf.setLength(0);
    }

    PatternConverter c = head;

    while(c != null) {
    c.format(sbuf, event);
    c = c.next;
    }

    return sbuf.toString().replaceAll("PASSWD>[^<]*</", "PASSWD>***</");
    }
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5388 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 08:07 · PVG 16:07 · LAX 01:07 · JFK 04:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.