1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 package ca.uhn.hl7v2.testpanel.util;
27
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.Map;
31 import java.util.concurrent.ConcurrentLinkedQueue;
32
33 import javax.swing.SwingUtilities;
34
35 import org.apache.log4j.BasicConfigurator;
36 import org.apache.log4j.PatternLayout;
37 import org.apache.log4j.WriterAppender;
38 import org.apache.log4j.spi.LoggingEvent;
39
40 public class SwingLogAppender extends WriterAppender {
41
42 private static Map<String, ArrayList<ILogListener>> listeners = new HashMap<String, ArrayList<ILogListener>>();
43
44 private ConcurrentLinkedQueue<LoggingEvent> buf;
45
46 public SwingLogAppender() {
47 super();
48 this.buf = new ConcurrentLinkedQueue<LoggingEvent>();
49 setLayout(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN));
50 BasicConfigurator.configure(this);
51 }
52
53 @Override
54 public void append(LoggingEvent event) {
55 buf.offer(event);
56
57
58
59
60
61
62
63
64
65 display();
66 }
67
68 void display() {
69 SwingUtilities.invokeLater(new Runnable() {
70
71 public void run() {
72 while (!buf.isEmpty()) {
73 LoggingEvent next = buf.poll();
74 String formattedLine = getLayout().format(next);
75 String ndc = next.getNDC();
76 fireEvent("", next, formattedLine);
77 if (ndc != null) {
78 fireEvent(ndc, next, formattedLine);
79 }
80 }
81 buf.clear();
82 }
83
84 });
85 }
86
87 private void fireEvent(String theNdc, LoggingEvent theEvent, String theFormatted) {
88 ArrayList<ILogListener> list = listeners.get(theNdc);
89 if (list != null) {
90 for (ILogListener next : list) {
91 next.handle(theEvent, theFormatted);
92 }
93 }
94 }
95
96 public static void addListener(ILogListener theListener) {
97 addListener("", theListener);
98 }
99
100 public static void addListener(String theNdc, ILogListener theListener) {
101 if (!listeners.containsKey(theNdc)) {
102 listeners.put(theNdc, new ArrayList<ILogListener>());
103 }
104 listeners.get(theNdc).add(theListener);
105 }
106
107 public static void removeListener(ILogListener theListener) {
108 removeListener("", theListener);
109 }
110
111 public static void removeListener(String theNdc, ILogListener theListener) {
112 listeners.get(theNdc).remove(theListener);
113 }
114
115 public interface ILogListener {
116
117 void handle(LoggingEvent theEvent, String theFormattedLine);
118
119 }
120
121 }