Project

General

Profile

1
package eu.dnetlib.functionality.modular.ui.utils;
2

    
3
import java.text.SimpleDateFormat;
4
import java.util.ArrayList;
5
import java.util.Date;
6
import java.util.List;
7
import java.util.concurrent.LinkedBlockingQueue;
8
import java.util.stream.Collectors;
9
import java.util.stream.StreamSupport;
10

    
11
import org.apache.log4j.AppenderSkeleton;
12
import org.apache.log4j.spi.LoggingEvent;
13

    
14
import com.google.common.base.Joiner;
15

    
16
public class LogUiAppender extends AppenderSkeleton {
17

    
18
	public static final int MAX_LOGS_IN_QUEUE = 2000;
19

    
20
	private final LinkedBlockingQueue<LogLine> logQueue = new LinkedBlockingQueue<>(MAX_LOGS_IN_QUEUE);
21

    
22
	private int count = 0;
23

    
24
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
25

    
26
	@Override
27
	protected void append(final LoggingEvent event) {
28
		synchronized (this.logQueue) {
29
			if (this.logQueue.remainingCapacity() == 0) {
30
				this.logQueue.poll();
31
			}
32
			try {
33
				final String date = dateFormat.format(new Date(event.getTimeStamp()));
34

    
35
				final String[] arr = event.getThrowableStrRep();
36
				final String strace = arr != null && arr.length > 0 ? Joiner.on("\n").join(arr) : "";
37

    
38
				this.logQueue.put(new LogLine(this.count++, event.getLevel().toString(), event.getLoggerName(), date, event.getRenderedMessage(), strace));
39
			} catch (final InterruptedException e) {
40
				throw new RuntimeException(e);
41
			}
42
		}
43
	}
44

    
45
	public List<LogLine> tail_N(final int n) throws Exception {
46
		if (n <= 0) { return new ArrayList<>(); }
47

    
48
		synchronized (this.logQueue) {
49
			return StreamSupport
50
					.stream(this.logQueue.spliterator(), false)
51
					.skip(Math.max(0, this.logQueue.size() - n))
52
					.collect(Collectors.toList());
53
		}
54
	}
55

    
56
	public List<LogLine> tail_continue(final int after) throws Exception {
57
		synchronized (this.logQueue) {
58
			return StreamSupport
59
					.stream(this.logQueue.spliterator(), false)
60
					.filter(ll -> (ll.getId() > after))
61
					.collect(Collectors.toList());
62
		}
63
	}
64

    
65
	@Override
66
	public void close() {}
67

    
68
	@Override
69
	public boolean requiresLayout() {
70
		return false;
71
	}
72

    
73
}
(2-2/3)