如何在中央类中获取log4j所写的内容,以监视应用程序中的所有log4j日志?
由于
编辑:我希望我不必从日志文件中读取它,因为它会使用更多资源
答案 0 :(得分:6)
您可以使用普通配置实现自己的Appender并复制所有日志:
log4j.rootLogger=WARN, file, other
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=${catalina.home}/logs/log.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ISO8601} %p %t %c - %m%n
log4j.appender.other=class.path.of.your.Appender
答案 1 :(得分:4)
也许你的要求和我一样。我只是写了一个相关的课来实现它。
public class FixedBufferAppender extends AppenderSkeleton {
private LimitTailSizeList ll;
public FixedBufferAppender(PatternLayout layOut, int size) {
this.layout = layOut;
ll = new LimitTailSizeList(size);
}
protected void append(LoggingEvent event) {
String log = this.layout.format(event);
ll.add(log);
}
public String getLatentLog() {
StringBuffer sb = new StringBuffer(100000);
for (Iterator iterator = ll.iterator(); iterator.hasNext();) {
String log = (String) iterator.next();
sb.append(log);
}
return sb.toString();
}
public void close() {
ll.clear();
ll = null;
this.closed = true;
}
public boolean requiresLayout() {
return true;
}
}
public class LimitTailSizeList extends ArrayList {
private int limitSize;
public LimitTailSizeList(int limitSize){
this.limitSize= limitSize;
}
public boolean add(Object o) {
boolean add = super.add(o);
if (size() > limitSize) {
removeRange(0, size() - limitSize);
}
return add;
}
private void initAppender(int maxTailLine) {
fba = new FixedBufferAppender(
new PatternLayout("%d [%X{requestURIWithQueryString}] %-5p -[%t] %m [%c{1}:%M %L] %n"),
maxTailLine);
Logger.getRootLogger().removeAppender("UI_APPENDER");
fba.setName("UI_APPENDER");
fba.setThreshold(org.apache.log4j.Level.DEBUG);
Logger.getRootLogger().addAppender(fba);
}
}
答案 2 :(得分:0)
提供log4j配置,将日志消息输出到文件或任何其他位置。