xudzhang
V2EX  ›  Java

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

  •  
  •   xudzhang · Feb 10, 2019 · 3206 views
    This topic created in 2668 days ago, the information mentioned may be changed or developed.

    有一个 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 replies    2019-02-10 14:09:16 +08:00
    PazuLee
        1
    PazuLee  
       Feb 10, 2019   ❤️ 1
    日志 log 之前用正则做处理?
    freedomSky
        2
    freedomSky  
       Feb 10, 2019   ❤️ 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>***</");
    }
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3784 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 00:45 · PVG 08:45 · LAX 17:45 · JFK 20:45
    ♥ Do have faith in what you're doing.