1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.core.status;
15
16 import ch.qos.logback.core.spi.ContextAwareBase;
17 import ch.qos.logback.core.spi.LifeCycle;
18 import ch.qos.logback.core.util.StatusPrinter;
19
20 import java.io.PrintStream;
21 import java.util.List;
22
23
24
25
26
27
28 abstract public class OnPrintStreamStatusListenerBase extends ContextAwareBase implements StatusListener, LifeCycle {
29
30 boolean isStarted = false;
31
32 static final long DEFAULT_RETROSPECTIVE = 300;
33 long retrospectiveThresold = DEFAULT_RETROSPECTIVE;
34
35 boolean resetResistant = false;
36
37
38
39
40
41
42 String prefix;
43
44
45
46
47
48
49 abstract protected PrintStream getPrintStream();
50
51 private void print(Status status) {
52 StringBuilder sb = new StringBuilder();
53 if (prefix != null)
54 sb.append(prefix);
55
56 StatusPrinter.buildStr(sb, "", status);
57 getPrintStream().print(sb);
58 }
59
60 public void addStatusEvent(Status status) {
61 if (!isStarted)
62 return;
63 print(status);
64 }
65
66
67
68
69 private void retrospectivePrint() {
70 if (context == null)
71 return;
72 long now = System.currentTimeMillis();
73 StatusManager sm = context.getStatusManager();
74 List<Status> statusList = sm.getCopyOfStatusList();
75 for (Status status : statusList) {
76 long timestampOfStatusMesage = status.getTimestamp();
77 if (isElapsedTimeLongerThanThreshold(now, timestampOfStatusMesage)) {
78 print(status);
79 }
80 }
81 }
82
83 private boolean isElapsedTimeLongerThanThreshold(long now, long timestamp) {
84 long elapsedTime = now - timestamp;
85 return elapsedTime < retrospectiveThresold;
86 }
87
88
89
90
91
92 public void start() {
93 isStarted = true;
94 if (retrospectiveThresold > 0) {
95 retrospectivePrint();
96 }
97 }
98
99 public String getPrefix() {
100 return prefix;
101 }
102
103 public void setPrefix(String prefix) {
104 this.prefix = prefix;
105 }
106
107 public void setRetrospective(long retrospective) {
108 this.retrospectiveThresold = retrospective;
109 }
110
111 public long getRetrospective() {
112 return retrospectiveThresold;
113 }
114
115 public void stop() {
116 isStarted = false;
117 }
118
119 public boolean isStarted() {
120 return isStarted;
121 }
122
123 @Override
124 public boolean isResetResistant() {
125 return resetResistant;
126 }
127 public void setResetResistant(boolean resetResistant) {
128 this.resetResistant = resetResistant;
129 }
130
131
132
133 }