我的产品中报告了 CWE 117 问题。
CWE 117 问题是软件没有正确清理或错误地清理写入日志的输出,我得到的一种可能的解决方案是在日志记录时添加以下内容。
String clean = args[1].replace('\n', '_').replace('\r', '_');
log.info(clean);
我的问题是 log4j 中是否有任何中心位置可以通过单个更改解决此问题?
最佳答案
它是Layout
负责序列化日志消息,换行符转换代码就在这里。
我建议创建您自己的 PatternLayout
子类来执行转换。这也在 Log4j 邮件列表上进行了讨论 here .这是该线程中建议的解决方案的略微修改版本:
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent;
public class NewLinePatternLayout extends PatternLayout {
public NewLinePatternLayout() { }
public NewLinePatternLayout(String pattern) {
super(pattern);
}
public boolean ignoresThrowable() {
return false;
}
public String format(LoggingEvent event) {
String original = super.format(event);
// Here your code comes into play
String clean = original.replace('\n', '_').replace('\r', '_');
StringBuilder sb = new StringBuilder(clean);
String[] s = event.getThrowableStrRep();
if (s != null) {
for (int i = 0; i < s.length; i++) {
sb.append(s[i]);
sb.append('_');
}
}
return sb.toString();
}
}
相关问题(可能有用的答案):
关于java - 如何解决 CWE 117 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30912182/