当日志消息被推送到列表中时,我还需要将时间戳存储在列表中。那么,我们如何获取时间戳并将其推送到列表中呢。我将日志推送到如下列表中
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.RollingFileAppender;
//import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.LoggingEvent;
public class Listappender extends RollingFileAppender {
private List<LoggingEvent> events = new ArrayList<LoggingEvent>();
static List<String> clone = new ArrayList<String>();
@Override
public synchronized void doAppend(LoggingEvent event) {
//System.out.println("hi....");
//events.clear();
events.add(event);
super.doAppend(event);
clone.clear();
clone.add((String) event.getMessage());
//getEvents();
/*
for (int j = 0; j < events.size(); j++){
System.out.println(events.get(j));
System.out.println(j);
}*/
}
public List<String> getEntries()
{
return clone;
}
}
查看如何创建时间戳Java时间戳-如何创建日期为2007年9月23日的时间戳?
你可以简单地做这个
clone.add(timestamp.toString() + event.getMessage());
只需将LoggingEvent
保存在列表中即可。您不必获取邮件并将其保存在其他列表中。LoggingEvent
具有public final long getTimeStamp()
方法来提供时间。尝试使用此代码:
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.RollingFileAppender;
import org.apache.log4j.spi.LoggingEvent;
public class ListAppender extends RollingFileAppender {
private final List<LoggingEvent> events = new ArrayList<LoggingEvent>();
@Override
public synchronized void doAppend(LoggingEvent event) {
events.add(event);
super.doAppend(event);
}
public synchronized List<LoggingEvent> getLoggingEvents() {
List<LoggingEvent> clone = new ArrayList<>(events);
events.clear();
return clone;
}
}