KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > logging > BufferingAppender


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.logging;
5
6 import org.apache.log4j.Appender;
7 import org.apache.log4j.AppenderSkeleton;
8 import org.apache.log4j.spi.LoggingEvent;
9
10 import EDU.oswego.cs.dl.util.concurrent.BoundedBuffer;
11
12 /**
13  * An {@link Appender} that simply buffers records (in a bounded queue) until they're needed. This is used for making
14  * sure all logging information gets to the file; we buffer records created before logging gets sent to a file, then
15  * send them there.
16  */

17 public class BufferingAppender extends AppenderSkeleton {
18
19   private final BoundedBuffer buffer;
20   private boolean on;
21
22   public BufferingAppender(int maxCapacity) {
23     this.buffer = new BoundedBuffer(maxCapacity);
24     this.on = true;
25   }
26
27   protected synchronized void append(LoggingEvent event) {
28     if (on) {
29       try {
30         this.buffer.offer(event, 0);
31       } catch (InterruptedException JavaDoc ie) {
32         // oh, well -- and we can't even log this; that would cause infinite recursion.
33
}
34     }
35   }
36
37   public boolean requiresLayout() {
38     return false;
39   }
40
41   public void close() {
42     // nothing needs to be here.
43
}
44
45   public void stopAndSendContentsTo(Appender otherAppender) {
46     synchronized (this) {
47       on = false;
48     }
49
50     while (true) {
51       try {
52         LoggingEvent event = (LoggingEvent) this.buffer.poll(0);
53         if (event == null) break;
54         otherAppender.doAppend(event);
55       } catch (InterruptedException JavaDoc ie) {
56         // ok, whatever
57
}
58     }
59   }
60
61 }
62
Popular Tags