cvs commit: jakarta-log4j/src/java/org/apache/log4j WriterAppender.java TTCCLayout.java RollingFileAppender.java PropertyConfigurator.java PatternLayout.java Logger.java Hierarchy.java HTMLLayout.java FileAppender.java DailyRollingFileAppender.java ConsoleAppender.java Category.java BasicConfigurator.java AsyncAppender.java
[email protected] 24 Apr 2002 01:16:15 -0000
| Newsgroups | gmane.comp.jakarta.log4j.cvs |
|---|---|
| Message-ID | <[email protected]> |
oburn 02/04/23 18:16:14
Modified: src/java/org/apache/log4j/xml/examples XMLSample.java
src/java/org/apache/log4j/varia
ExternallyRolledFileAppender.java
src/java/org/apache/log4j/test/serialization
SerializationUT.java
src/java/org/apache/log4j/test SysoutConfigurator.java
StressNDC.java StressAsyncAppender.java
ShortSocketServer.java Shallow.java ROFile.java
Finalize.java DefaultInit.java DRFATest.java
src/java/org/apache/log4j/spi RepositorySelector.java
RendererSupport.java OptionHandler.java
LoggingEvent.java LoggerRepository.java
LocationInfo.java DefaultRepositorySelector.java
src/java/org/apache/log4j/performance NullAppender.java
NotLogging.java Logging.java
src/java/org/apache/log4j/or/sax AttributesRenderer.java
src/java/org/apache/log4j/or/jms MessageRenderer.java
src/java/org/apache/log4j/or RendererMap.java
src/java/org/apache/log4j/nt/test NTMin.java
src/java/org/apache/log4j/nt NTEventLogAppender.java
src/java/org/apache/log4j/net/test SyslogMin.java
SocketMin.java SMTPMin.java
src/java/org/apache/log4j/net TelnetAppender.java
SyslogAppender.java SocketServer.java
SocketNode.java SocketAppender.java
SimpleSocketServer.java SMTPAppender.java
JMSSink.java JMSAppender.java
src/java/org/apache/log4j/jmx LoggerDynamicMBean.java
LayoutDynamicMBean.java HierarchyDynamicMBean.java
AppenderDynamicMBean.java Agent.java
AbstractDynamicMBean.java
src/java/org/apache/log4j/jdbc JDBCAppender.java
src/java/org/apache/log4j/helpers SyslogQuietWriter.java
PatternParser.java OptionConverter.java
ISO8601DateFormat.java DateTimeDateFormat.java
CountingQuietWriter.java
src/java/org/apache/log4j/config PropertyGetter.java
src/java/org/apache/log4j WriterAppender.java
TTCCLayout.java RollingFileAppender.java
PropertyConfigurator.java PatternLayout.java
Logger.java Hierarchy.java HTMLLayout.java
FileAppender.java DailyRollingFileAppender.java
ConsoleAppender.java Category.java
BasicConfigurator.java AsyncAppender.java
Log:
House keeping by removing unused import statements (detected using
Checkstyle). My Emacs setup will also remove trailing white space on any files
I save (which explains the extra changes).
The purpose of removing unused import statements is to remove unnecessary
coupling between classes.
Revision Changes Path
1.4 +10 -11 jakarta-log4j/src/java/org/apache/log4j/xml/examples/XMLSample.java
Index: XMLSample.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/xml/examples/XMLSample.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- XMLSample.java 20 Dec 2000 15:57:30 -0000 1.3
+++ XMLSample.java 24 Apr 2002 01:16:11 -0000 1.4
@@ -3,7 +3,6 @@
import org.apache.log4j.xml.DOMConfigurator;
import org.apache.log4j.Category;
-import org.apache.log4j.Priority;
import java.net.*;
/**
@@ -14,24 +13,24 @@
<p>Sample XML files <a href="doc-files/sample1.xml">sample1.xml</a>
and <a href="doc-files/sample2.xml">sample2.xml</a> are provided.
-
+
<p>Note that the log4j.dtd is not in the local directory.
It is found by the class loader.
-
+
@author Ceki Gülcü
*/
public class XMLSample {
-
+
static Category cat = Category.getInstance(XMLSample.class.getName());
- public
- static
+ public
+ static
void main(String argv[]) {
- if(argv.length == 1)
+ if(argv.length == 1)
init(argv[0]);
- else
+ else
Usage("Wrong number of arguments.");
sample();
}
@@ -43,7 +42,7 @@
"configFile");
System.exit(1);
}
-
+
static
void init(String configFile) {
DOMConfigurator.configure(configFile);
@@ -52,10 +51,10 @@
static
void sample() {
int i = -1;
- Category root = Category.getRoot();
+ Category root = Category.getRoot();
cat.debug("Message " + ++i);
cat.warn ("Message " + ++i);
- cat.error("Message " + ++i);
+ cat.error("Message " + ++i);
Exception e = new Exception("Just testing");
cat.debug("Message " + ++i, e);
}
1.11 +15 -17 jakarta-log4j/src/java/org/apache/log4j/varia/ExternallyRolledFileAppender.java
Index: ExternallyRolledFileAppender.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/varia/ExternallyRolledFileAppender.java,v
retrieving revision 1.10
retrieving revision 1.11
diff -u -r1.10 -r1.11
--- ExternallyRolledFileAppender.java 9 Aug 2001 20:16:31 -0000 1.10
+++ ExternallyRolledFileAppender.java 24 Apr 2002 01:16:11 -0000 1.11
@@ -13,8 +13,6 @@
import java.net.ServerSocket;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.RollingFileAppender;
-import org.apache.log4j.Layout;
-import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.helpers.LogLog;
/**
@@ -26,7 +24,7 @@
<p>This method of triggering roll over has the advantage of being
operating system independent, fast and reliable.
-
+
<p>A simple application {@link Roller} is provided to initiate the
roll over.
@@ -41,7 +39,7 @@
/**
The string constant sent to initiate a roll over. Current value of
- this string constant is <b>RollOver</b>.
+ this string constant is <b>RollOver</b>.
*/
static final public String ROLL_OVER = "RollOver";
@@ -58,18 +56,18 @@
The default constructor does nothing but calls its super-class
constructor. */
public
- ExternallyRolledFileAppender() {
+ ExternallyRolledFileAppender() {
}
-
+
/**
The <b>Port</b> [roperty is used for setting the port for
- listening to external roll over messages.
+ listening to external roll over messages.
*/
public
void setPort(int port) {
this.port = port;
}
-
+
/**
Returns value of the <b>Port</b> option.
*/
@@ -77,7 +75,7 @@
int getPort() {
return port;
}
-
+
/**
Start listening on the port specified by a preceding call to
{@link #setPort}. */
@@ -88,7 +86,7 @@
if(hup != null) {
hup.interrupt();
}
- hup = new HUP(this, port);
+ hup = new HUP(this, port);
hup.setDaemon(true);
hup.start();
}
@@ -105,11 +103,11 @@
this.er = er;
this.port = port;
}
-
+
public
void run() {
while(!isInterrupted()) {
- try {
+ try {
ServerSocket serverSocket = new ServerSocket(port);
while(true) {
Socket socket = serverSocket.accept();
@@ -120,7 +118,7 @@
catch(Exception e) {
e.printStackTrace();
}
- }
+ }
}
}
@@ -130,7 +128,7 @@
DataInputStream dis;
DataOutputStream dos;
ExternallyRolledFileAppender er;
-
+
public
HUPNode(Socket socket, ExternallyRolledFileAppender er) {
this.socket = socket;
@@ -143,11 +141,11 @@
e.printStackTrace();
}
}
-
+
public void run() {
try {
String line = dis.readUTF();
- LogLog.debug("Got external roll over signal.");
+ LogLog.debug("Got external roll over signal.");
if(ExternallyRolledFileAppender.ROLL_OVER.equals(line)) {
synchronized(er) {
er.rollOver();
@@ -161,7 +159,7 @@
}
catch(Exception e) {
LogLog.error("Unexpected exception. Exiting HUPNode.", e);
- }
+ }
}
}
1.5 +31 -32 jakarta-log4j/src/java/org/apache/log4j/test/serialization/SerializationUT.java
Index: SerializationUT.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/test/serialization/SerializationUT.java,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -r1.4 -r1.5
--- SerializationUT.java 8 Feb 2002 12:54:16 -0000 1.4
+++ SerializationUT.java 24 Apr 2002 01:16:11 -0000 1.5
@@ -12,7 +12,6 @@
import java.net.URL;
import java.net.URLClassLoader;
-import java.net.MalformedURLException;
import java.lang.reflect.Method;
/**
@@ -33,7 +32,7 @@
static URLClassLoader classLoader113;
- static Class class113;
+ static Class class113;
static Object o113;
static Method serMethod113;
static Method deserMethod113;
@@ -43,43 +42,43 @@
static Object o12a7;
static Method serMethod12a7;
static Method deserMethod12a7;
-
+
public SerializationUT(String name) {
super(name);
}
public
void setUp() throws Exception {
-
+
try {
URL urlLocal = new URL("file:T/");
URL url113 = new URL("file:T/log4j-1.1.3.jar");
-
- classLoader113 = new URLClassLoader(new URL[] {urlLocal, url113});
+
+ classLoader113 = new URLClassLoader(new URL[] {urlLocal, url113});
class113 = classLoader113.loadClass("T113");
o113 = class113.newInstance();
- serMethod113 = class113.getMethod("serialize",
+ serMethod113 = class113.getMethod("serialize",
new Class[] {java.util.Hashtable.class});
-
- deserMethod113 = class113.getMethod("deserialize",
- new Class[] {byte[].class});
-
+
+ deserMethod113 = class113.getMethod("deserialize",
+ new Class[] {byte[].class});
+
URL url2a7 = new URL("file:T/log4j-1.2alpha7.jar");
-
+
classLoader12a7 = new URLClassLoader(new URL[] {urlLocal, url2a7});
class12a7 = classLoader12a7.loadClass("T12");
o12a7 = class12a7.newInstance();
- serMethod12a7 = class12a7.getMethod("serialize",
+ serMethod12a7 = class12a7.getMethod("serialize",
new Class[] {java.util.Hashtable.class});
- deserMethod12a7 = class12a7.getMethod("deserialize",
- new Class[] {byte[].class});
+ deserMethod12a7 = class12a7.getMethod("deserialize",
+ new Class[] {byte[].class});
} catch(Exception e) {
e.printStackTrace();
throw e;
}
-
+
System.out.println("---Exiting setup");
}
@@ -91,16 +90,16 @@
/**
Test writing in 1.1.3 and reading from 1.1.3. Here we are testing
the test. */
- public
+ public
void test1() throws Exception {
-
+
Hashtable inHt = new Hashtable();
Hashtable witness = new Hashtable();
inHt.put("categoryName", "a.b.c");
inHt.put("priorityStr", "DEBUG");
inHt.put("message", "hello");
-
+
witness.put("categoryName", "a.b.c");
witness.put("priorityStr", "DEBUG");
witness.put("renderedMessage", "hello");
@@ -118,16 +117,16 @@
/**
Test writing 1.2 and reading from 1.2. Here we are testing the test.
*/
- public
+ public
void test2() throws Exception {
-
+
Hashtable inHt = new Hashtable();
Hashtable witness = new Hashtable();
inHt.put("categoryName", "a.b.c");
inHt.put("priorityStr", "DEBUG");
inHt.put("message", "hello");
-
+
witness.put("categoryName", "a.b.c");
witness.put("priorityStr", "DEBUG");
witness.put("renderedMessage", "hello");
@@ -139,18 +138,18 @@
}
/**
- Test writing 1.1.3 and reading from 1.2.
+ Test writing 1.1.3 and reading from 1.2.
*/
- public
+ public
void test3() throws Exception {
-
+
Hashtable inHt = new Hashtable();
Hashtable witness = new Hashtable();
inHt.put("categoryName", "a.b.c");
inHt.put("priorityStr", "DEBUG");
inHt.put("message", "hello");
-
+
witness.put("categoryName", "a.b.c");
witness.put("priorityStr", "DEBUG");
witness.put("renderedMessage", "hello");
@@ -162,9 +161,9 @@
/**
Test writing 1.2 and reading from 1.1.3.
*/
- public
+ public
void test4() throws Exception {
-
+
Hashtable inHt = new Hashtable();
Hashtable witness = new Hashtable();
@@ -189,7 +188,7 @@
assertEquals(witness, outHt);
}
-
+
public
static
Test suite() {
@@ -199,7 +198,7 @@
suite.addTest(new SerializationUT("test3"));
suite.addTest(new SerializationUT("test4"));
return suite;
- }
+ }
}
class ComparableException extends Exception {
@@ -210,11 +209,11 @@
public boolean equals(Object o) {
System.out.println("ComparableException.equals called.");
- if(!(o instanceof ComparableException))
+ if(!(o instanceof ComparableException))
return false;
ComparableException r = (ComparableException) o;
-
+
if(r.getMessage() == null) {
if(getMessage() != null)
return false;
1.6 +0 -1 jakarta-log4j/src/java/org/apache/log4j/test/SysoutConfigurator.java
Index: SysoutConfigurator.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/test/SysoutConfigurator.java,v
retrieving revision 1.5
retrieving revision 1.6
diff -u -r1.5 -r1.6
--- SysoutConfigurator.java 5 Sep 2001 06:45:29 -0000 1.5
+++ SysoutConfigurator.java 24 Apr 2002 01:16:11 -0000 1.6
@@ -1,6 +1,5 @@
package org.apache.log4j.test;
-import java.util.Properties;
import org.apache.log4j.spi.*;
import org.apache.log4j.*;
1.5 +24 -27 jakarta-log4j/src/java/org/apache/log4j/test/StressNDC.java
Index: StressNDC.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/test/StressNDC.java,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -r1.4 -r1.5
--- StressNDC.java 2 Sep 2001 20:05:40 -0000 1.4
+++ StressNDC.java 24 Apr 2002 01:16:11 -0000 1.5
@@ -1,14 +1,11 @@
-// Copyright 1996-1999, International Business Machines
+// Copyright 1996-1999, International Business Machines
// Corporation and others. All Rights Reserved.
package org.apache.log4j.test;
import org.apache.log4j.Category;
-import org.apache.log4j.FileAppender;
-import org.apache.log4j.SimpleLayout;
import org.apache.log4j.BasicConfigurator;
-import org.apache.log4j.Level;
import org.apache.log4j.NDC;
@@ -17,31 +14,31 @@
/**
Stress test {@link NDC}.
-
+
*/
public class StressNDC extends Thread {
- static Category root = Category.getRoot();
+ static Category root = Category.getRoot();
static Random random = new Random(101);
static final int LOOP_LENGTH = 24;
- static final int PUSH_MISS = LOOP_LENGTH/2;
- static final int POP_MISS = PUSH_MISS*2;
+ static final int PUSH_MISS = LOOP_LENGTH/2;
+ static final int POP_MISS = PUSH_MISS*2;
static final int BRANCHING_FACTOR = 4 + 1; // add 1 to the number you want
-
- static int maxThreads;
+
+ static int maxThreads;
static int msgCounter = 0;
- static int threadCounter = 0;
+ static int threadCounter = 0;
static double LOG_2 = Math.log(2);
static Object lock = new Object();
-
- public
- static
+
+ public
+ static
void main(String args[]) {
BasicConfigurator.configure();
@@ -56,14 +53,14 @@
System.err.println(e);
usage();
}
-
+
root.debug( "push(IP=127.0.0.1)");
-
+
NDC.push("IP=127.0.0.1");
while(true) {
synchronized(lock) {
- // Adding 1 to ensure that at least 1 child is created.
+ // Adding 1 to ensure that at least 1 child is created.
createChildren(randomInt(BRANCHING_FACTOR) + 1);
// wait until all threads are finished
@@ -88,7 +85,7 @@
Stack parentDC;
-
+
public
StressNDC(Stack parentDC) {
this.setName(randomID());
@@ -98,28 +95,28 @@
public
void run() {
NDC.inherit(parentDC);
-
+
int loopLength = StressNDC.randomInt(LOOP_LENGTH);
root.debug("In run loop.debug( loopLength = "+loopLength);
int createIndex = loopLength/2;
-
+
for(int i = 0; i <= loopLength; i++) {
if(i == createIndex)
createChildren(randomInt(BRANCHING_FACTOR));
-
+
if(randomInt(PUSH_MISS) == 0) {
String id = randomID();
- root.debug( "push("+id+")");
+ root.debug( "push("+id+")");
NDC.push(id);
- }
- root.debug( "Message number " + StressNDC.msgCounter++);
+ }
+ root.debug( "Message number " + StressNDC.msgCounter++);
if(randomInt(POP_MISS) == 0) {
root.debug( "pop()");
NDC.pop();
}
- }
+ }
synchronized(lock) {
StressNDC.threadCounter--;
@@ -144,7 +141,7 @@
return;
synchronized(lock) {
- n = maxThreadsConstained(n);
+ n = maxThreadsConstained(n);
root.debug("Creating " + n+ " child StressNDC threads.");
for(int i = 0; i < n; i++) {
root.debug("New StressNDC, threadCounter = " + (++threadCounter));
@@ -156,7 +153,7 @@
static
public
int maxThreadsConstained(int a) {
- int maxAllowed = StressNDC.maxThreads - StressNDC.threadCounter;
+ int maxAllowed = StressNDC.maxThreads - StressNDC.threadCounter;
return a <= maxAllowed ? a : maxAllowed;
}
1.4 +19 -24 jakarta-log4j/src/java/org/apache/log4j/test/StressAsyncAppender.java
Index: StressAsyncAppender.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/test/StressAsyncAppender.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- StressAsyncAppender.java 18 Jan 2001 17:25:34 -0000 1.3
+++ StressAsyncAppender.java 24 Apr 2002 01:16:11 -0000 1.4
@@ -5,40 +5,35 @@
import org.apache.log4j.Category;
-import org.apache.log4j.FileAppender;
-import org.apache.log4j.SimpleLayout;
import org.apache.log4j.xml.DOMConfigurator;
-import org.apache.log4j.Priority;
-import org.apache.log4j.NDC;
import java.util.Random;
-import java.util.Stack;
/**
Stress test {@link AsyncAppender}.
-
+
*/
public class StressAsyncAppender extends Thread {
- static Category root = Category.getRoot();
+ static Category root = Category.getRoot();
static Random random = new Random(101);
static final int LOOP_LENGTH = 24;
static final int BRANCHING_FACTOR = 4;
-
- static int maxThreads;
+
+ static int maxThreads;
static long msgCounter = 0;
- static int threadCounter = 0;
+ static int threadCounter = 0;
static double LOG_2 = Math.log(2);
static Object lock = new Object();
-
- public
- static
+
+ public
+ static
void main(String args[]) {
if(args.length != 1) {
usage();
@@ -53,10 +48,10 @@
System.err.println(e);
usage();
}
-
+
while(true) {
synchronized(lock) {
- // Adding 1 to ensure that at least 1 child is created.
+ // Adding 1 to ensure that at least 1 child is created.
createChildren(randomInt(BRANCHING_FACTOR) + 1);
// wait until all threads are finished
@@ -92,17 +87,17 @@
// half of the way, create new childres
int createIndex = loopLength/2;
-
+
for(int i = 0; i <= loopLength; i++) {
if(i == createIndex)
createChildren(randomInt(BRANCHING_FACTOR));
-
- synchronized(lock) {
- root.debug("Message number " + msgCounter++);
+
+ synchronized(lock) {
+ root.debug("Message number " + msgCounter++);
}
//delay(1+randomInt(4)*100);
- }
+ }
synchronized(lock) {
StressAsyncAppender.threadCounter--;
@@ -122,7 +117,7 @@
return;
synchronized(lock) {
- n = maxThreadsConstrained(n);
+ n = maxThreadsConstrained(n);
root.debug("Creating " + n+ " child StressAsyncAppender threads.");
for(int i = 0; i < n; i++) {
root.debug("New StressAsyncAppender, threadCounter = " + (++threadCounter));
@@ -134,7 +129,7 @@
static
public
int maxThreadsConstrained(int a) {
- int maxAllowed = StressAsyncAppender.maxThreads -
+ int maxAllowed = StressAsyncAppender.maxThreads -
StressAsyncAppender.threadCounter;
return a <= maxAllowed ? a : maxAllowed;
}
@@ -149,12 +144,12 @@
return r >= 0 ? r : -r;
}
-
+
public
void delay(long millis) {
try {
Thread.currentThread().sleep(millis);
} catch(Exception e) {}
}
-
+
}
1.8 +11 -13 jakarta-log4j/src/java/org/apache/log4j/test/ShortSocketServer.java
Index: ShortSocketServer.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/test/ShortSocketServer.java,v
retrieving revision 1.7
retrieving revision 1.8
diff -u -r1.7 -r1.8
--- ShortSocketServer.java 22 Jan 2001 12:16:37 -0000 1.7
+++ ShortSocketServer.java 24 Apr 2002 01:16:11 -0000 1.8
@@ -4,13 +4,11 @@
import java.net.Socket;
import java.net.ServerSocket;
-import java.io.IOException;
import org.apache.log4j.Category;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.net.SocketNode;
-import org.apache.log4j.net.SocketServer;
/**
*/
@@ -20,26 +18,26 @@
static Category cat = Category.getInstance(ShortSocketServer.class.getName());
static int port;
-
- public
- static
+
+ public
+ static
void main(String argv[]) {
if(argv.length == 2) {
init(argv[0], argv[1]);
} else {
- usage("Wrong number of arguments.");
+ usage("Wrong number of arguments.");
}
-
+
try {
LogLog.debug("Listening on port " + port);
ServerSocket serverSocket = new ServerSocket(port);
LogLog.debug("Waiting to accept a new client.");
Socket socket = serverSocket.accept();
LogLog.debug("Connected to client at " + socket.getInetAddress());
- LogLog.debug("Starting new socket node.");
+ LogLog.debug("Starting new socket node.");
SocketNode sn = new SocketNode(socket, Category.getDefaultHierarchy());
Thread t = new Thread(sn);
- t.start();
+ t.start();
t.join();
}
catch(Exception e) {
@@ -47,7 +45,7 @@
}
}
-
+
static
void usage(String msg) {
System.err.println(msg);
@@ -55,16 +53,16 @@
"Usage: java " +ShortSocketServer.class.getName() + " port configFile");
System.exit(1);
}
-
+
static
void init(String portStr, String configFile) {
try {
- port = Integer.parseInt(portStr);
+ port = Integer.parseInt(portStr);
}
catch(java.lang.NumberFormatException e) {
e.printStackTrace();
usage("Could not interpret port number ["+ portStr +"].");
}
- PropertyConfigurator.configure(configFile);
+ PropertyConfigurator.configure(configFile);
}
}
1.8 +24 -26 jakarta-log4j/src/java/org/apache/log4j/test/Shallow.java
Index: Shallow.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/test/Shallow.java,v
retrieving revision 1.7
retrieving revision 1.8
diff -u -r1.7 -r1.8
--- Shallow.java 17 Nov 2001 01:04:22 -0000 1.7
+++ Shallow.java 24 Apr 2002 01:16:11 -0000 1.8
@@ -5,29 +5,27 @@
* the LICENSE.txt file.
*/
// NOTICE: Some tests are sensitive to line numbers!
-package org.apache.log4j.test;
+package org.apache.log4j.test;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.xml.DOMConfigurator;
import org.apache.log4j.Category;
import org.apache.log4j.NDC;
import org.apache.log4j.Priority;
-import java.io.IOException;
-import java.util.Enumeration;
-/**
+/**
This class is a shallow test of the various appenders and
layouts. It also tests their reading of the configuration file.
@author Ceki Gülcü
*/
public class Shallow {
-
+
static Category cat = Category.getInstance(Shallow.class);
-
- public
- static
+
+ public
+ static
void main(String argv[]) {
- if(argv.length == 1)
+ if(argv.length == 1)
init(argv[0]);
- else
+ else
usage("Wrong number of arguments.");
test();
}
@@ -39,49 +37,49 @@
System.exit(1);
}
- static
+ static
void init(String configFile) {
if(configFile.endsWith(".xml"))
DOMConfigurator.configure(configFile);
- else
+ else
PropertyConfigurator.configure(configFile);
}
- static
+ static
void test() {
- int i = -1;
- NDC.push("NDC");
+ int i = -1;
+ NDC.push("NDC");
Category root = Category.getRoot();
cat.debug("Message " + ++i);
- root.debug("Message " + i);
+ root.debug("Message " + i);
cat.info ("Message " + ++i);
- root.info("Message " + i);
+ root.info("Message " + i);
cat.warn ("Message " + ++i);
- root.warn("Message " + i);
+ root.warn("Message " + i);
cat.error("Message " + ++i);
root.error("Message " + i);
-
+
cat.log(Priority.FATAL, "Message " + ++i);
- root.log(Priority.FATAL, "Message " + i);
-
+ root.log(Priority.FATAL, "Message " + i);
+
Exception e = new Exception("Just testing");
cat.debug("Message " + ++i, e);
root.debug("Message " + i, e);
-
+
cat.info("Message " + ++i, e);
- root.info("Message " + i, e);
+ root.info("Message " + i, e);
cat.warn("Message " + ++i , e);
- root.warn("Message " + i , e);
+ root.warn("Message " + i , e);
cat.error("Message " + ++i, e);
- root.error("Message " + i, e);
+ root.error("Message " + i, e);
cat.log(Priority.FATAL, "Message " + ++i, e);
- root.log(Priority.FATAL, "Message " + i, e);
+ root.log(Priority.FATAL, "Message " + i, e);
root.setPriority(Priority.FATAL);
1.3 +6 -8 jakarta-log4j/src/java/org/apache/log4j/test/ROFile.java
Index: ROFile.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/test/ROFile.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- ROFile.java 14 Dec 2000 21:08:13 -0000 1.2
+++ ROFile.java 24 Apr 2002 01:16:11 -0000 1.3
@@ -1,21 +1,19 @@
-package org.apache.log4j.test;
+package org.apache.log4j.test;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.Category;
-import org.apache.log4j.Priority;
-import java.io.IOException;
public class ROFile {
static Category cat = Category.getInstance(ROFile.class.getName());
-
- public
- static
+
+ public
+ static
void main(String argv[]) {
- if(argv.length == 1)
+ if(argv.length == 1)
init(argv[0]);
- else
+ else
Usage("Wrong number of arguments.");
test();
1.3 +16 -18 jakarta-log4j/src/java/org/apache/log4j/test/Finalize.java
Index: Finalize.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/test/Finalize.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- Finalize.java 14 Dec 2000 21:08:13 -0000 1.2
+++ Finalize.java 24 Apr 2002 01:16:11 -0000 1.3
@@ -1,11 +1,9 @@
-package org.apache.log4j.test;
+package org.apache.log4j.test;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.Category;
-import org.apache.log4j.Priority;
-import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
@@ -13,13 +11,13 @@
static Category CAT = Category.getInstance(Finalize.class.getName());
- public
- static
+ public
+ static
void main(String argv[]) {
- if(argv.length == 1)
+ if(argv.length == 1)
init(argv[0]);
- else
+ else
Usage("Wrong number of arguments.");
test();
@@ -33,7 +31,7 @@
System.exit(1);
}
-
+
static
void init(String configFile) {
PropertyConfigurator.configure(configFile);
@@ -43,13 +41,13 @@
void test() {
int i = -1;
- InputStreamReader in = new InputStreamReader(System.in);
+ InputStreamReader in = new InputStreamReader(System.in);
Category root = Category.getRoot();
System.out.println("Type 'q' to quit");
int j = 0;
while (true) {
- System.gc();
+ System.gc();
try {i = in.read(); }
catch(Exception e) { return; }
System.gc();
@@ -58,27 +56,27 @@
break;
else if(i == 'q')
break;
- else
+ else
root.debug("Hello " + (++j));
- }
+ }
//foo(root);
root.removeAllAppenders();
System.gc(); delay(3000);
- System.gc(); delay(3000);
+ System.gc(); delay(3000);
System.gc(); delay(3000); System.gc();
}
-
+
static
- void foo(Category cat) {
+ void foo(Category cat) {
Enumeration enum = cat.getAllAppenders();
while(enum != null && enum.hasMoreElements()) {
((org.apache.log4j.Appender) enum.nextElement()).close();
}
}
-
-
+
+
static
void delay(int amount) {
try {
@@ -86,5 +84,5 @@
}
catch(Exception e) {}
}
-
+
}
1.4 +1 -5 jakarta-log4j/src/java/org/apache/log4j/test/DefaultInit.java
Index: DefaultInit.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/test/DefaultInit.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- DefaultInit.java 28 Sep 2001 13:37:48 -0000 1.3
+++ DefaultInit.java 24 Apr 2002 01:16:11 -0000 1.4
@@ -2,11 +2,7 @@
package org.apache.log4j.test;
import org.apache.log4j.Category;
-import org.apache.log4j.BasicConfigurator;
-import org.apache.log4j.PropertyConfigurator;
-import org.apache.log4j.SimpleLayout;
-import org.apache.log4j.FileAppender;
-
+
public class DefaultInit {
static Category cat = Category.getInstance(DefaultInit.class);
1.2 +10 -12 jakarta-log4j/src/java/org/apache/log4j/test/DRFATest.java
Index: DRFATest.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/test/DRFATest.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- DRFATest.java 25 Jul 2001 22:30:05 -0000 1.1
+++ DRFATest.java 24 Apr 2002 01:16:11 -0000 1.2
@@ -5,7 +5,7 @@
* the LICENSE.txt file.
*/
-package org.apache.log4j.test;
+package org.apache.log4j.test;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Category;
import org.apache.log4j.Layout;
@@ -13,25 +13,23 @@
import org.apache.log4j.Appender;
import org.apache.log4j.DailyRollingFileAppender;
-import java.io.IOException;
-import java.util.Enumeration;
-/**
+/**
This class is used in testing the DailyRollingFileAppender.
@author Ceki Gülcü
*/
public class DRFATest {
-
+
static Category cat = Category.getInstance(DRFATest.class);
static int limit;
- public
- static
+ public
+ static
void main(String argv[]) {
- if(argv.length == 1)
+ if(argv.length == 1)
init(argv[0]);
- else
+ else
usage("Wrong number of arguments.");
test();
}
@@ -43,7 +41,7 @@
System.exit(1);
}
- static
+ static
void init(String limitStr) {
try {
limit = Integer.parseInt(limitStr);
@@ -52,12 +50,12 @@
}
}
- static
+ static
void test() {
Layout layout = new PatternLayout("%d{yyyy-MM-dd-HH-mm ss:SSS} %m%n");
try {
- Appender appender = new DailyRollingFileAppender(layout, "test",
+ Appender appender = new DailyRollingFileAppender(layout, "test",
"'.'yyyy-MM-dd-HH-mm" );
appender.setName("drfa");
BasicConfigurator.configure(appender);
1.3 +2 -3 jakarta-log4j/src/java/org/apache/log4j/spi/RepositorySelector.java
Index: RepositorySelector.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/spi/RepositorySelector.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- RepositorySelector.java 26 Sep 2001 10:42:08 -0000 1.2
+++ RepositorySelector.java 24 Apr 2002 01:16:11 -0000 1.3
@@ -3,10 +3,9 @@
package org.apache.log4j.spi;
-import org.apache.log4j.Logger;
/**
-
+
The <code>LogManager</code> uses one (and only one)
<code>RepositorySelector</code> implementation to select the
{@link LoggerRepository} for a particular application context.
@@ -29,6 +28,6 @@
LoggerRepository is returned.
*/
public
- LoggerRepository getLoggerRepository();
+ LoggerRepository getLoggerRepository();
}
1.2 +0 -1 jakarta-log4j/src/java/org/apache/log4j/spi/RendererSupport.java
Index: RendererSupport.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/spi/RendererSupport.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- RendererSupport.java 5 Sep 2001 07:58:08 -0000 1.1
+++ RendererSupport.java 24 Apr 2002 01:16:11 -0000 1.2
@@ -6,7 +6,6 @@
import org.apache.log4j.or.RendererMap;
import org.apache.log4j.or.ObjectRenderer;
-import java.util.Enumeration;
public interface RendererSupport {
1.10 +2 -3 jakarta-log4j/src/java/org/apache/log4j/spi/OptionHandler.java
Index: OptionHandler.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/spi/OptionHandler.java,v
retrieving revision 1.9
retrieving revision 1.10
diff -u -r1.9 -r1.10
--- OptionHandler.java 20 Jul 2001 15:56:03 -0000 1.9
+++ OptionHandler.java 24 Apr 2002 01:16:11 -0000 1.10
@@ -7,7 +7,6 @@
package org.apache.log4j.spi;
-import org.apache.log4j.FileAppender;
/**
A string based interface to configure package components.
@@ -35,7 +34,7 @@
/**
Return list of strings that the OptionHandler instance recognizes.
-
+
@deprecated We now use JavaBeans style getters/setters.
*/
// String[] getOptionStrings();
@@ -47,7 +46,7 @@
instance. Some options may become active immediately whereas
other may be activated only when {@link #activateOptions} is
called.
-
+
@deprecated We now use JavaBeans style getters/setters.
*/
//void setOption(String option, String value);
1.28 +38 -41 jakarta-log4j/src/java/org/apache/log4j/spi/LoggingEvent.java
Index: LoggingEvent.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/spi/LoggingEvent.java,v
retrieving revision 1.27
retrieving revision 1.28
diff -u -r1.27 -r1.28
--- LoggingEvent.java 16 Apr 2002 14:37:32 -0000 1.27
+++ LoggingEvent.java 24 Apr 2002 01:16:11 -0000 1.28
@@ -10,10 +10,7 @@
import org.apache.log4j.*;
import org.apache.log4j.helpers.LogLog;
-import org.apache.log4j.helpers.Loader;
-import java.io.StringWriter;
-import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
@@ -29,11 +26,11 @@
is created. This instance is passed around to the different log4j
components.
- <p>This class is of concern to those wishing to extend log4j.
+ <p>This class is of concern to those wishing to extend log4j.
@author Ceki Gülcü
@author James P. Cakalic
-
+
@since 0.8.2 */
public class LoggingEvent implements java.io.Serializable {
@@ -43,7 +40,7 @@
transient public final String fqnOfCategoryClass;
/** The category of the logging event. The category field is not
- serialized for performance reasons.
+ serialized for performance reasons.
<p>It is set by the LoggingEvent constructor or set by a remote
entity after deserialization. */
@@ -51,7 +48,7 @@
/** The category (logger) name. */
public final String categoryName;
-
+
/** Level of logging event. Level cannot be serializable
because it is a flyweight. Due to its special seralization it
cannot be declared final either. */
@@ -89,8 +86,8 @@
private String threadName;
- /** This
- variable contains information about this event's throwable
+ /** This
+ variable contains information about this event's throwable
*/
private ThrowableInformation throwableInfo;
@@ -100,7 +97,7 @@
/** Location information for the caller. */
private LocationInfo locationInfo;
- // Serialization
+ // Serialization
static final long serialVersionUID = -868428216207166145L;
static final Integer[] PARAM_ARRAY = new Integer[1];
@@ -110,7 +107,7 @@
/**
Instantiate a LoggingEvent from the supplied parameters.
-
+
<p>Except {@link #timeStamp} all the other fields of
<code>LoggingEvent</code> are filled when actually needed.
<p>
@@ -118,22 +115,22 @@
@param level The level of this event.
@param message The message of this event.
@param throwable The throwable of this event. */
- public LoggingEvent(String fqnOfCategoryClass, Category logger,
+ public LoggingEvent(String fqnOfCategoryClass, Category logger,
Priority priority, Object message, Throwable throwable) {
this.fqnOfCategoryClass = fqnOfCategoryClass;
this.logger = logger;
this.categoryName = logger.getName();
- this.level = priority;
+ this.level = priority;
this.message = message;
if(throwable != null) {
this.throwableInfo = new ThrowableInformation(throwable);
}
timeStamp = System.currentTimeMillis();
- }
+ }
/**
Instantiate a LoggingEvent from the supplied parameters.
-
+
<p>Except {@link #timeStamp} all the other fields of
<code>LoggingEvent</code> are filled when actually needed.
<p>
@@ -142,20 +139,20 @@
@param level The level of this event.
@param message The message of this event.
@param throwable The throwable of this event. */
- public LoggingEvent(String fqnOfCategoryClass, Category logger,
- long timeStamp, Priority priority, Object message,
+ public LoggingEvent(String fqnOfCategoryClass, Category logger,
+ long timeStamp, Priority priority, Object message,
Throwable throwable) {
this.fqnOfCategoryClass = fqnOfCategoryClass;
this.logger = logger;
this.categoryName = logger.getName();
- this.level = priority;
+ this.level = priority;
this.message = message;
if(throwable != null) {
this.throwableInfo = new ThrowableInformation(throwable);
}
this.timeStamp = timeStamp;
- }
+ }
@@ -173,12 +170,12 @@
/**
- Return the message for this logging event.
+ Return the message for this logging event.
<p>Before serialization, the returned object is the message
passed by the user to generate the logging event. After
serialization, the returned value equals the String form of the
- message possibly after object rendering.
+ message possibly after object rendering.
@since 1.1 */
public
@@ -196,11 +193,11 @@
ndcLookupRequired = false;
ndc = NDC.get();
}
- return ndc;
+ return ndc;
}
- /**
+ /**
Retrung the the context corresponding to the <code>key</code>
parameter. If there is a local MDC copy (probably from a remote
machine, the search try it first, if that fails then search this
@@ -209,13 +206,13 @@
public
Object getMDC(String key) {
Object r;
-
+
if(mdcCopy != null) {
r = mdcCopy.get(key);
if(r != null) {
return r;
}
- }
+ }
return MDC.get(key);
}
@@ -233,11 +230,11 @@
public
String getRenderedMessage() {
if(renderedMessage == null && message != null) {
- if(message instanceof String)
+ if(message instanceof String)
renderedMessage = (String) message;
else {
LoggerRepository repository = logger.getHierarchy();
-
+
if(repository instanceof RendererSupport) {
RendererSupport rs = (RendererSupport) repository;
renderedMessage= rs.getRendererMap().findAndRender(message);
@@ -247,13 +244,13 @@
}
}
return renderedMessage;
- }
+ }
/**
Returns the time when the application started, in milliseconds
elapsed since 01.01.1970. */
public
- static
+ static
long getStartTime() {
return startTime;
}
@@ -281,32 +278,32 @@
/**
Return this event's throwable's string[] representaion.
*/
- public
+ public
String[] getThrowableStrRep() {
if(throwableInfo == null)
return null;
- else
+ else
return throwableInfo.getThrowableStrRep();
}
-
- private
- void readLevel(ObjectInputStream ois)
+
+ private
+ void readLevel(ObjectInputStream ois)
throws java.io.IOException, ClassNotFoundException {
int p = ois.readInt();
try {
- String className = (String) ois.readObject();
+ String className = (String) ois.readObject();
if(className == null) {
level = Level.toLevel(p);
} else {
- Method m = (Method) methodCache.get(className);
+ Method m = (Method) methodCache.get(className);
if(m == null) {
Class clazz = Class.forName(className);
m = clazz.getDeclaredMethod(TO_LEVEL, TO_LEVEL_PARAMS);
methodCache.put(className, m);
- }
+ }
PARAM_ARRAY[0] = new Integer(p);
level = (Level) m.invoke(null, PARAM_ARRAY);
}
@@ -318,7 +315,7 @@
private void readObject(ObjectInputStream ois)
throws java.io.IOException, ClassNotFoundException {
- ois.defaultReadObject();
+ ois.defaultReadObject();
readLevel(ois);
// Make sure that no location info is available to Layouts
@@ -330,7 +327,7 @@
void writeObject(ObjectOutputStream oos) throws java.io.IOException {
// Aside from returning the current thread name the wgetThreadName
// method sets the threadName variable.
- this.getThreadName();
+ this.getThreadName();
// This sets the renders the message in case it wasn't up to now.
this.getRenderedMessage();
@@ -347,12 +344,12 @@
this.getThrowableStrRep();
oos.defaultWriteObject();
-
+
// serialize this event's level
writeLevel(oos);
}
- private
+ private
void writeLevel(ObjectOutputStream oos) throws java.io.IOException {
oos.writeInt(level.toInt());
1.9 +10 -11 jakarta-log4j/src/java/org/apache/log4j/spi/LoggerRepository.java
Index: LoggerRepository.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/spi/LoggerRepository.java,v
retrieving revision 1.8
retrieving revision 1.9
diff -u -r1.8 -r1.9
--- LoggerRepository.java 1 Oct 2001 21:16:37 -0000 1.8
+++ LoggerRepository.java 24 Apr 2002 01:16:11 -0000 1.9
@@ -8,7 +8,6 @@
package org.apache.log4j.spi;
import org.apache.log4j.*;
-import org.apache.log4j.or.RendererMap;
import java.util.Enumeration;
/**
@@ -16,7 +15,7 @@
<code>Loggers</code>. The relation between loggers in a repository
depends on the repository but typically loggers are arranged in a
named hierarchy.
-
+
<p>In addition to the creational methods, a
<code>LoggerRepository</code> can be queried for existing loggers,
can act as a point of registry for events related to loggers.
@@ -26,9 +25,9 @@
public interface LoggerRepository {
/**
- Add a {@link HierarchyEventListener} event to the repository.
+ Add a {@link HierarchyEventListener} event to the repository.
*/
- public
+ public
void addHierarchyEventListener(HierarchyEventListener listener);
/**
@@ -41,18 +40,18 @@
Set the repository-wide threshold. All logging requests below the
threshold are immediately dropped. By default, the threshold is
set to <code>Level.ALL</code> which has the lowest possible rank. */
- public
+ public
void setThreshold(Level level);
-
- /**
+
+ /**
Another form of {@link #setThreshold(Level)} accepting a string
parameter instead of a <code>Level</code>. */
- public
+ public
void setThreshold(String val);
-
+
public
void emitNoAppenderWarning(Category cat);
-
+
/**
Get the repository-wide threshold. See {@link
#setThreshold(Level)} for an explanation. */
@@ -75,7 +74,7 @@
public
abstract
void shutdown();
-
+
public
Enumeration getCurrentLoggers();
1.12 +30 -31 jakarta-log4j/src/java/org/apache/log4j/spi/LocationInfo.java
Index: LocationInfo.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/spi/LocationInfo.java,v
retrieving revision 1.11
retrieving revision 1.12
diff -u -r1.11 -r1.12
--- LocationInfo.java 22 Feb 2002 10:39:55 -0000 1.11
+++ LocationInfo.java 24 Apr 2002 01:16:11 -0000 1.12
@@ -13,15 +13,14 @@
import java.io.PrintWriter;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.Layout;
-import org.apache.log4j.helpers.Loader;
/**
The internal representation of caller location information.
-
+
@since 0.8.3
*/
public class LocationInfo implements java.io.Serializable {
-
+
/**
Caller's line number.
*/
@@ -63,7 +62,7 @@
Class dummy = Class.forName("com.ibm.uvm.tools.DebugSupport");
inVisualAge = true;
LogLog.debug("Detected IBM VisualAge environment.");
- } catch(Throwable e) {
+ } catch(Throwable e) {
// nothing to do
}
}
@@ -107,28 +106,28 @@
// This method of searching may not be fastest but it's safer
// than counting the stack depth which is not guaranteed to be
- // constant across JVM implementations.
+ // constant across JVM implementations.
ibegin = s.lastIndexOf(fqnOfCallingClass);
- if(ibegin == -1)
+ if(ibegin == -1)
return;
- ibegin = s.indexOf(Layout.LINE_SEP, ibegin);
- if(ibegin == -1)
+ ibegin = s.indexOf(Layout.LINE_SEP, ibegin);
+ if(ibegin == -1)
return;
ibegin+= Layout.LINE_SEP_LEN;
-
+
// determine end of line
- iend = s.indexOf(Layout.LINE_SEP, ibegin);
- if(iend == -1)
+ iend = s.indexOf(Layout.LINE_SEP, ibegin);
+ if(iend == -1)
return;
- // VA has a different stack trace format which doesn't
+ // VA has a different stack trace format which doesn't
// need to skip the inital 'at'
if(!inVisualAge) {
// back up to first blank character
- ibegin = s.lastIndexOf("at ", iend);
- if(ibegin == -1)
+ ibegin = s.lastIndexOf("at ", iend);
+ if(ibegin == -1)
return;
// Add 3 to skip "at ";
ibegin += 3;
@@ -142,13 +141,13 @@
logging request.
*/
public
- String getClassName() {
- if(fullInfo == null) return NA;
+ String getClassName() {
+ if(fullInfo == null) return NA;
if(className == null) {
// Starting the search from '(' is safer because there is
// potentially a dot between the parentheses.
int iend = fullInfo.lastIndexOf('(');
- if(iend == -1)
+ if(iend == -1)
className = NA;
else {
iend =fullInfo.lastIndexOf('.', iend);
@@ -167,7 +166,7 @@
ibegin = fullInfo.lastIndexOf(' ', iend)+1;
}
- if(iend == -1)
+ if(iend == -1)
className = NA;
else
className = this.fullInfo.substring(ibegin, iend);
@@ -181,18 +180,18 @@
<p>This information is not always available.
*/
- public
+ public
String getFileName() {
if(fullInfo == null) return NA;
-
+
if(fileName == null) {
- int iend = fullInfo.lastIndexOf(':');
+ int iend = fullInfo.lastIndexOf(':');
if(iend == -1)
fileName = NA;
else {
int ibegin = fullInfo.lastIndexOf('(', iend - 1);
fileName = this.fullInfo.substring(ibegin + 1, iend);
- }
+ }
}
return fileName;
}
@@ -200,19 +199,19 @@
/**
Returns the line number of the caller.
- <p>This information is not always available.
+ <p>This information is not always available.
*/
- public
+ public
String getLineNumber() {
if(fullInfo == null) return NA;
-
+
if(lineNumber == null) {
- int iend = fullInfo.lastIndexOf(')');
+ int iend = fullInfo.lastIndexOf(')');
int ibegin = fullInfo.lastIndexOf(':', iend -1);
if(ibegin == -1)
lineNumber = NA;
- else
- lineNumber = this.fullInfo.substring(ibegin + 1, iend);
+ else
+ lineNumber = this.fullInfo.substring(ibegin + 1, iend);
}
return lineNumber;
}
@@ -222,14 +221,14 @@
*/
public
String getMethodName() {
- if(fullInfo == null) return NA;
+ if(fullInfo == null) return NA;
if(methodName == null) {
- int iend = fullInfo.lastIndexOf('(');
+ int iend = fullInfo.lastIndexOf('(');
int ibegin = fullInfo.lastIndexOf('.', iend);
if(ibegin == -1)
methodName = NA;
else
- methodName = this.fullInfo.substring(ibegin + 1, iend);
+ methodName = this.fullInfo.substring(ibegin + 1, iend);
}
return methodName;
}
1.2 +2 -3 jakarta-log4j/src/java/org/apache/log4j/spi/DefaultRepositorySelector.java
Index: DefaultRepositorySelector.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/spi/DefaultRepositorySelector.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- DefaultRepositorySelector.java 3 Sep 2001 22:33:21 -0000 1.1
+++ DefaultRepositorySelector.java 24 Apr 2002 01:16:11 -0000 1.2
@@ -3,13 +3,12 @@
package org.apache.log4j.spi;
-import org.apache.log4j.Logger;
public class DefaultRepositorySelector implements RepositorySelector {
final LoggerRepository repository;
-
- public
+
+ public
DefaultRepositorySelector(LoggerRepository repository) {
this.repository = repository;
}
1.3 +5 -7 jakarta-log4j/src/java/org/apache/log4j/performance/NullAppender.java
Index: NullAppender.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/performance/NullAppender.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- NullAppender.java 14 Dec 2000 21:08:08 -0000 1.2
+++ NullAppender.java 24 Apr 2002 01:16:11 -0000 1.3
@@ -9,22 +9,20 @@
import org.apache.log4j.Layout;
import org.apache.log4j.spi.LoggingEvent;
-import org.apache.log4j.Category;
-import org.apache.log4j.Priority;
import org.apache.log4j.AppenderSkeleton;
/**
A bogus appender which calls the format method of its layout object
- but does not write the result anywhere.
+ but does not write the result anywhere.
*/
public class NullAppender extends AppenderSkeleton {
public static String s;
- public String t;
+ public String t;
public
NullAppender() {}
-
+
public
NullAppender(Layout layout) {
this.layout = layout;
@@ -32,7 +30,7 @@
public
void close() {}
-
+
public
void doAppend(LoggingEvent event) {
if(layout != null) {
@@ -51,5 +49,5 @@
public
boolean requiresLayout() {
return true;
- }
+ }
}
1.10 +28 -30 jakarta-log4j/src/java/org/apache/log4j/performance/NotLogging.java
Index: NotLogging.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/performance/NotLogging.java,v
retrieving revision 1.9
retrieving revision 1.10
diff -u -r1.9 -r1.10
--- NotLogging.java 11 Feb 2002 16:14:34 -0000 1.9
+++ NotLogging.java 24 Apr 2002 01:16:11 -0000 1.10
@@ -1,14 +1,12 @@
-// Copyright 1996-2000, International Business Machines
+// Copyright 1996-2000, International Business Machines
// Corporation. All Rights Reserved.
package org.apache.log4j.performance;
import org.apache.log4j.Category;
-import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.ConsoleAppender;
-import org.apache.log4j.Layout;
import org.apache.log4j.Level;
@@ -45,23 +43,23 @@
static int runLength;
- final static int INITIAL_HASH_SIZE = 101;
+ final static int INITIAL_HASH_SIZE = 101;
static String SHORT_MSG = "Hello World";
static Category SHORT_CAT = Category.getInstance("A0123456789");
static Category MEDIUM_CAT= Category.getInstance("A0123456789.B0123456789");
- static Category LONG_CAT =
+ static Category LONG_CAT =
Category.getInstance("A0123456789.B0123456789.C0123456789");
static Category INEXISTENT_SHORT_CAT = Category.getInstance("I0123456789");
static Category INEXISTENT_MEDIUM_CAT=
Category.getInstance("I0123456789.B0123456789");
- static Category INEXISTENT_LONG_CAT=
+ static Category INEXISTENT_LONG_CAT=
Category.getInstance("I0123456789.B0123456789.C0123456789");
- static Category[] CAT_ARRAY = new Category[] {SHORT_CAT, MEDIUM_CAT,
+ static Category[] CAT_ARRAY = new Category[] {SHORT_CAT, MEDIUM_CAT,
LONG_CAT, INEXISTENT_SHORT_CAT,
INEXISTENT_MEDIUM_CAT,
INEXISTENT_LONG_CAT};
@@ -80,91 +78,91 @@
if(argv.length != 2) {
Usage();
- }
+ }
ProgramInit(argv);
double delta;
-
+
System.out.println();
for(int i = 0; i < CAT_ARRAY.length; i++) {
delta = SimpleMessage(CAT_ARRAY[i], SHORT_MSG, runLength);
- System.out.println("Simple argument, " + delta
+ System.out.println("Simple argument, " + delta
+ " micros. Cat: " + CAT_ARRAY[i].getName());
}
System.out.println();
for(int i = 0; i < CAT_ARRAY.length; i++) {
delta = FullyOptimizedComplexMessage(CAT_ARRAY[i], runLength);
- System.out.println("Fully optimized complex, " + delta +
+ System.out.println("Fully optimized complex, " + delta +
" micros. Cat: " + CAT_ARRAY[i].getName());
}
System.out.println();
for(int i = 0; i < CAT_ARRAY.length; i++) {
delta = ComplexMessage(CAT_ARRAY[i], runLength);
- System.out.println("Complex message argument, " + delta +
+ System.out.println("Complex message argument, " + delta +
" micros. Cat: " + CAT_ARRAY[i].getName());
}
-
+
}
-
+
/**
Program wide initialization method. */
static
void ProgramInit(String[] args) {
try {
- runLength = Integer.parseInt(args[1]);
+ runLength = Integer.parseInt(args[1]);
}
catch(java.lang.NumberFormatException e) {
System.err.println(e);
Usage();
- }
+ }
+
-
ConsoleAppender appender = new ConsoleAppender(new SimpleLayout());
-
+
if("false".equals(args[0])) {
// nothing to do
} else if ("true".equals(args[0])) {
System.out.println("Flagging as shipped code.");
Category.getDefaultHierarchy().setThreshold((Level) Level.WARN);
- } else
+ } else
Usage();
- SHORT_CAT.setLevel((Level) Level.INFO);
+ SHORT_CAT.setLevel((Level) Level.INFO);
Category.getRoot().setLevel((Level) Level.INFO);
- }
-
+ }
+
static
- double SimpleMessage(Category category, String msg, long runLength) {
+ double SimpleMessage(Category category, String msg, long runLength) {
long before = System.currentTimeMillis();
for(int i = 0; i < runLength; i++) {
category.debug(msg);
}
- return (System.currentTimeMillis() - before)*1000.0/runLength;
+ return (System.currentTimeMillis() - before)*1000.0/runLength;
}
static
- double FullyOptimizedComplexMessage(Category category, long runLength) {
+ double FullyOptimizedComplexMessage(Category category, long runLength) {
long before = System.currentTimeMillis();
for(int i = 0; i < runLength; i++) {
if(category.isDebugEnabled())
- category.debug("Message" + i +
+ category.debug("Message" + i +
" bottles of beer standing on the wall.");
- }
- return (System.currentTimeMillis() - before)*1000.0/runLength;
+ }
+ return (System.currentTimeMillis() - before)*1000.0/runLength;
}
static
- double ComplexMessage(Category category, long runLength) {
+ double ComplexMessage(Category category, long runLength) {
long before = System.currentTimeMillis();
for(int i = 0; i < runLength; i++) {
category.debug("Message" + i +
" bottles of beer standing on the wall.");
}
- return (System.currentTimeMillis() - before)*1000.0/runLength;
+ return (System.currentTimeMillis() - before)*1000.0/runLength;
}
}
1.11 +25 -33 jakarta-log4j/src/java/org/apache/log4j/performance/Logging.java
Index: Logging.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/performance/Logging.java,v
retrieving revision 1.10
retrieving revision 1.11
diff -u -r1.10 -r1.11
--- Logging.java 19 Dec 2001 20:48:32 -0000 1.10
+++ Logging.java 24 Apr 2002 01:16:11 -0000 1.11
@@ -1,4 +1,4 @@
-// Copyright 1996-1999, International Business Machines
+// Copyright 1996-1999, International Business Machines
// Corporation. All Rights Reserved.
// Copyright 2000, Ceki Gulcu. All Rights Reserved.
@@ -8,19 +8,11 @@
package org.apache.log4j.performance;
import org.apache.log4j.Category;
-import org.apache.log4j.Layout;
import org.apache.log4j.xml.DOMConfigurator;
-import org.apache.log4j.Appender;
-import org.apache.log4j.net.SyslogAppender;
-import org.apache.log4j.net.SocketAppender;
-import org.apache.log4j.FileAppender;
-import org.apache.log4j.Priority;
-import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.NDC;
import org.apache.log4j.performance.NOPWriter;
-import java.util.Enumeration;
/**
Measure the performance of logging.
@@ -32,21 +24,21 @@
<p><table border=1>
<tr>
-<th>Layout
-<th>NullAppender
+<th>Layout
+<th>NullAppender
<th>FileAppender
<th>FileAppender (no flush)
<th>AsyncAppender (no flush)
<tr>
-<td>SimpleLayout
+<td>SimpleLayout
<td>4
<td>21
<td>16
<td>33
<tr>
-<td>PatternLayout "%p - %m%n"
+<td>PatternLayout "%p - %m%n"
<td>4
<td>21
<td>16
@@ -124,7 +116,7 @@
<tr>
<td>PatternLayout "%C.%M.%L - %m%n"
-<td>267
+<td>267
<td>NA
<td>NA
<td>NA
@@ -148,7 +140,7 @@
java.text.SimpleDateFormat} because of its poor performance. See
the <b>%d</b> conversion character in {@link
org.apache.log4j.PatternLayout}.
-
+
<p><li>Avoiding the flush operation at the end of each append
results in a performance gain of 10 to 20 percent. However, there
is safety tradeoff invloved in skipping flushing. Indeed, when
@@ -161,7 +153,7 @@
performance. The performance tests done here very quickly fill up
the bounded buffer of the <code>AsyncAppender</code> and there is
cosiderable overhead in managing this bounded buffer.
-
+
<p>On the other hand, had we interleaved logging operations with
long blocking and non CPU-intensive operations, such as I/O,
network access, sleeping threads, then the
@@ -193,7 +185,7 @@
requests. The default value of this constant is 100. */
static int burstLen = 100;
static int DELAY_MULT = 1000/burstLen;
-
+
static Category cat = Category.getInstance("A0123456789.B0123456789.C0123456789");
static
@@ -228,27 +220,27 @@
else
Usage("Wrong number of arguments.");
-
+
NDC.push("some context");
double delta;
String msg = "ABCDEGHIJKLMNOPQRSTUVWXYZabcdeghijklmnopqrstuvwxyz1234567890";
- if(delay <= 0)
+ if(delay <= 0)
delta = NoDelayLoop(cat, msg);
else
delta = DelayedLoop(cat, msg);
-
- System.out.print((int)delta);
+
+ System.out.print((int)delta);
Category.shutdown();
}
-
+
/**
Program wide initialization method.
*/
static
- void init(String configFile, String runLengthStr, String delayStr,
+ void init(String configFile, String runLengthStr, String delayStr,
String burstLenStr) {
try {
runLength = Integer.parseInt(runLengthStr);
@@ -257,26 +249,26 @@
}
if(delayStr != null) {
burstLen = Integer.parseInt(burstLenStr);
- DELAY_MULT = 1000/burstLen;
- }
+ DELAY_MULT = 1000/burstLen;
+ }
}
catch(java.lang.NumberFormatException e) {
e.printStackTrace();
- }
+ }
DOMConfigurator.configure(configFile);
}
-
+
static
- double NoDelayLoop(Category category, String msg) {
+ double NoDelayLoop(Category category, String msg) {
long before = System.currentTimeMillis();
for(int i = 0; i < runLength; i++) {
category.info(msg);
}
- return ((System.currentTimeMillis() - before)*1000.0)/runLength;
+ return ((System.currentTimeMillis() - before)*1000.0)/runLength;
}
static
- double DelayedLoop(Category category, String msg) {
+ double DelayedLoop(Category category, String msg) {
long before = System.currentTimeMillis();
int j = 0;
Thread currentThread = Thread.currentThread();
@@ -286,10 +278,10 @@
j = 0;
try{currentThread.sleep(delay);}catch(Exception e){}
}
-
+
}
double actualTime = ((System.currentTimeMillis()-before)*1000.0/runLength);
System.out.println("actual time: "+actualTime);
- return (actualTime - delay*DELAY_MULT);
- }
+ return (actualTime - delay*DELAY_MULT);
+ }
}
1.5 +2 -5 jakarta-log4j/src/java/org/apache/log4j/or/sax/AttributesRenderer.java
Index: AttributesRenderer.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/or/sax/AttributesRenderer.java,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -r1.4 -r1.5
--- AttributesRenderer.java 25 Sep 2001 10:29:04 -0000 1.4
+++ AttributesRenderer.java 24 Apr 2002 01:16:12 -0000 1.5
@@ -7,11 +7,8 @@
package org.apache.log4j.or.sax;
-import org.apache.log4j.Layout;
-import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.or.ObjectRenderer;
-import java.util.Enumeration;
import org.xml.sax.Attributes;
/**
@@ -25,13 +22,13 @@
AttributesRenderer() {
}
-
+
/**
Render a {@link org.xml.sax.Attributes}.
*/
public
String doRender(Object o) {
- if(o instanceof Attributes) {
+ if(o instanceof Attributes) {
StringBuffer sbuf = new StringBuffer();
Attributes a = (Attributes) o;
int len = a.getLength();
1.3 +4 -6 jakarta-log4j/src/java/org/apache/log4j/or/jms/MessageRenderer.java
Index: MessageRenderer.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/or/jms/MessageRenderer.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- MessageRenderer.java 25 Sep 2001 10:29:04 -0000 1.2
+++ MessageRenderer.java 24 Apr 2002 01:16:12 -0000 1.3
@@ -7,14 +7,12 @@
package org.apache.log4j.or.jms;
-import org.apache.log4j.Layout;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.or.ObjectRenderer;
import javax.jms.Message;
import javax.jms.JMSException;
import javax.jms.DeliveryMode;
-import java.util.Enumeration;
/**
Render <code>javax.jms.Message</code> objects.
@@ -27,22 +25,22 @@
MessageRenderer() {
}
-
+
/**
Render a {@link javax.jms.Message}.
*/
public
String doRender(Object o) {
- if(o instanceof Message) {
+ if(o instanceof Message) {
StringBuffer sbuf = new StringBuffer();
Message m = (Message) o;
try {
sbuf.append("DeliveryMode=");
switch(m.getJMSDeliveryMode()) {
- case DeliveryMode.NON_PERSISTENT :
+ case DeliveryMode.NON_PERSISTENT :
sbuf.append("NON_PERSISTENT");
break;
- case DeliveryMode.PERSISTENT :
+ case DeliveryMode.PERSISTENT :
sbuf.append("PERSISTENT");
break;
default: sbuf.append("UNKNOWN");
1.9 +20 -21 jakarta-log4j/src/java/org/apache/log4j/or/RendererMap.java
Index: RendererMap.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/or/RendererMap.java,v
retrieving revision 1.8
retrieving revision 1.9
diff -u -r1.8 -r1.9
--- RendererMap.java 22 Feb 2002 10:39:55 -0000 1.8
+++ RendererMap.java 24 Apr 2002 01:16:12 -0000 1.9
@@ -9,7 +9,6 @@
import org.apache.log4j.spi.RendererSupport;
import org.apache.log4j.helpers.LogLog;
-import org.apache.log4j.helpers.Loader;
import org.apache.log4j.helpers.OptionConverter;
import java.util.Hashtable;
@@ -34,12 +33,12 @@
*/
static
public
- void addRenderer(RendererSupport repository, String renderedClassName,
+ void addRenderer(RendererSupport repository, String renderedClassName,
String renderingClassName) {
LogLog.debug("Rendering class: ["+renderingClassName+"], Rendered class: ["+
renderedClassName+"].");
- ObjectRenderer renderer = (ObjectRenderer)
- OptionConverter.instantiateByClassName(renderingClassName,
+ ObjectRenderer renderer = (ObjectRenderer)
+ OptionConverter.instantiateByClassName(renderingClassName,
ObjectRenderer.class,
null);
if(renderer == null) {
@@ -66,7 +65,7 @@
String findAndRender(Object o) {
if(o == null)
return null;
- else
+ else
return get(o.getClass()).doRender(o);
}
@@ -74,19 +73,19 @@
/**
Syntactic sugar method that calls {@link #get(Class)} with the
class of the object parameter. */
- public
+ public
ObjectRenderer get(Object o) {
- if(o == null)
+ if(o == null)
return null;
else
return get(o.getClass());
}
-
+
/**
Search the parents of <code>clazz</code> for a renderer. The
renderer closest in the hierarchy will be returned. If no
- renderers could be found, then the default renderer is returned.
+ renderers could be found, then the default renderer is returned.
<p>The search first looks for a renderer configured for
<code>clazz</code>. If a renderer could not be found, then the
@@ -112,19 +111,19 @@
<tr><th>Added renderers</th><th>Value returned by <code>get(A2.class)</code></th>
<tr><td><code>A0Renderer</code>
- <td align="center"><code>A0Renderer</code>
+ <td align="center"><code>A0Renderer</code>
<tr><td><code>A0Renderer, A1Renderer</code>
- <td align="center"><code>A1Renderer</code>
+ <td align="center"><code>A1Renderer</code>
<tr><td><code>X0Renderer</code>
- <td align="center"><code>X0Renderer</code>
+ <td align="center"><code>X0Renderer</code>
<tr><td><code>A1Renderer, X0Renderer</code>
- <td align="center"><code>X0Renderer</code>
+ <td align="center"><code>X0Renderer</code>
</table>
-
+
<p>This search algorithm is not the most natural, although it is
particularly easy to implement. Future log4j versions
<em>may</em> implement a more intuitive search
@@ -134,24 +133,24 @@
*/
public
ObjectRenderer get(Class clazz) {
- //System.out.println("\nget: "+clazz);
+ //System.out.println("\nget: "+clazz);
ObjectRenderer r = null;
for(Class c = clazz; c != null; c = c.getSuperclass()) {
//System.out.println("Searching for class: "+c);
r = (ObjectRenderer) map.get(c);
if(r != null) {
return r;
- }
+ }
r = searchInterfaces(c);
if(r != null)
return r;
}
return defaultRenderer;
- }
-
+ }
+
ObjectRenderer searchInterfaces(Class c) {
//System.out.println("Searching interfaces of class: "+c);
-
+
ObjectRenderer r = (ObjectRenderer) map.get(c);
if(r != null) {
return r;
@@ -160,7 +159,7 @@
for(int i = 0; i < ia.length; i++) {
r = searchInterfaces(ia[i]);
if(r != null)
- return r;
+ return r;
}
}
return null;
@@ -179,7 +178,7 @@
}
/**
- Register an {@link ObjectRenderer} for <code>clazz</code>.
+ Register an {@link ObjectRenderer} for <code>clazz</code>.
*/
public
void put(Class clazz, ObjectRenderer or) {
1.3 +6 -9 jakarta-log4j/src/java/org/apache/log4j/nt/test/NTMin.java
Index: NTMin.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/nt/test/NTMin.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- NTMin.java 14 Dec 2000 21:08:04 -0000 1.2
+++ NTMin.java 24 Apr 2002 01:16:12 -0000 1.3
@@ -9,21 +9,18 @@
import org.apache.log4j.Category;
-import org.apache.log4j.Layout;
import org.apache.log4j.BasicConfigurator;
-import org.apache.log4j.Appender;
import org.apache.log4j.nt.NTEventLogAppender;
import org.apache.log4j.Priority;
import org.apache.log4j.NDC;
-import java.io.IOException;
public class NTMin {
-
+
static Category cat = Category.getInstance(NTMin.class.getName());
-
- public
- static
+
+ public
+ static
void main(String argv[]) {
//if(argv.length == 1) {
@@ -35,7 +32,7 @@
test("someHost");
}
-
+
static
void Usage(String msg) {
System.err.println(msg);
@@ -43,7 +40,7 @@
System.exit(1);
}
-
+
static
void init() {
1.15 +22 -23 jakarta-log4j/src/java/org/apache/log4j/nt/NTEventLogAppender.java
Index: NTEventLogAppender.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/nt/NTEventLogAppender.java,v
retrieving revision 1.14
retrieving revision 1.15
diff -u -r1.14 -r1.15
--- NTEventLogAppender.java 2 Sep 2001 20:05:39 -0000 1.14
+++ NTEventLogAppender.java 24 Apr 2002 01:16:12 -0000 1.15
@@ -10,14 +10,13 @@
import org.apache.log4j.*;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.Level;
-import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.helpers.LogLog;
import java.io.*;
/**
- Append to the NT event log system.
+ Append to the NT event log system.
<p><b>WARNING</b> This appender can only be installed and used on a
Windows system.
@@ -39,27 +38,27 @@
private static final int WARN = Level.WARN.toInt();
private static final int INFO = Level.INFO.toInt();
private static final int DEBUG = Level.DEBUG.toInt();
-
+
public NTEventLogAppender() {
this(null, null, null);
}
-
+
public NTEventLogAppender(String source) {
this(null, source, null);
}
-
+
public NTEventLogAppender(String server, String source) {
this(server, source, null);
}
-
+
public NTEventLogAppender(Layout layout) {
this(null, null, layout);
}
-
+
public NTEventLogAppender(String source, Layout layout) {
this(null, source, layout);
}
-
+
public NTEventLogAppender(String server, String source, Layout layout) {
if (source == null) {
source = "Log4j";
@@ -69,7 +68,7 @@
} else {
this.layout = layout;
}
-
+
try {
_handle = registerEventSource(server, source);
} catch (Exception e) {
@@ -84,7 +83,7 @@
}
public
- void activateOptions() {
+ void activateOptions() {
if (source != null) {
try {
_handle = registerEventSource(server, source);
@@ -95,19 +94,19 @@
}
}
-
+
public void append(LoggingEvent event) {
- StringBuffer sbuf = new StringBuffer();
+ StringBuffer sbuf = new StringBuffer();
sbuf.append(layout.format(event));
if(layout.ignoresThrowable()) {
String[] s = event.getThrowableStrRep();
if (s != null) {
int len = s.length;
- for(int i = 0; i < len; i++) {
+ for(int i = 0; i < len; i++) {
sbuf.append(s[i]);
- }
+ }
}
}
// Normalize the log message level into the supported categories
@@ -119,14 +118,14 @@
//}
reportEvent(_handle, sbuf.toString(), nt_category);
}
-
-
- public
+
+
+ public
void finalize() {
deregisterEventSource(_handle);
_handle = 0;
}
-
+
/**
The <b>Source</b> option which names the source of the event. The
current value of this constant is <b>Source</b>.
@@ -135,12 +134,12 @@
void setSource(String source) {
this.source = source.trim();
}
-
+
public
String getSource() {
return source;
}
-
+
/**
The <code>NTEventLogAppender</code> requires a layout. Hence,
this method always returns <code>true</code>. */
@@ -148,12 +147,12 @@
boolean requiresLayout() {
return true;
}
-
+
native private int registerEventSource(String server, String source);
native private void reportEvent(int handle, String message, int level);
native private void deregisterEventSource(int handle);
-
+
static {
System.loadLibrary("NTEventLogAppender");
}
-}
+}
1.3 +6 -10 jakarta-log4j/src/java/org/apache/log4j/net/test/SyslogMin.java
Index: SyslogMin.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/net/test/SyslogMin.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- SyslogMin.java 14 Dec 2000 21:07:59 -0000 1.2
+++ SyslogMin.java 24 Apr 2002 01:16:12 -0000 1.3
@@ -9,21 +9,17 @@
package org.apache.log4j.net.test;
import org.apache.log4j.Category;
-import org.apache.log4j.Layout;
import org.apache.log4j.PropertyConfigurator;
-import org.apache.log4j.Appender;
-import org.apache.log4j.net.SocketAppender;
import org.apache.log4j.Priority;
import org.apache.log4j.NDC;
-import java.io.IOException;
public class SyslogMin {
-
+
static Category CAT = Category.getInstance(SyslogMin.class.getName());
-
- public
- static
+
+ public
+ static
void main(String argv[]) {
if(argv.length == 1) {
@@ -35,7 +31,7 @@
test("someHost");
}
-
+
static
void Usage(String msg) {
System.err.println(msg);
@@ -43,7 +39,7 @@
System.exit(1);
}
-
+
static
void ProgramInit(String configFile) {
int port = 0;
1.3 +9 -11 jakarta-log4j/src/java/org/apache/log4j/net/test/SocketMin.java
Index: SocketMin.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/net/test/SocketMin.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- SocketMin.java 14 Dec 2000 21:07:59 -0000 1.2
+++ SocketMin.java 24 Apr 2002 01:16:12 -0000 1.3
@@ -9,39 +9,37 @@
import org.apache.log4j.Category;
import org.apache.log4j.BasicConfigurator;
-import org.apache.log4j.Appender;
import org.apache.log4j.net.SocketAppender;
import org.apache.log4j.Priority;
import org.apache.log4j.NDC;
-import java.io.IOException;
import java.io.InputStreamReader;
public class SocketMin {
-
+
static Category cat = Category.getInstance(SyslogMin.class.getName());
static SocketAppender s;
- public
- static
+ public
+ static
void main(String argv[]) {
- if(argv.length == 3)
+ if(argv.length == 3)
init(argv[0], argv[1]);
- else
- usage("Wrong number of arguments.");
-
+ else
+ usage("Wrong number of arguments.");
+
NDC.push("some context");
if(argv[2].equals("true"))
loop();
else
test();
-
+
s.close();
}
static
void usage(String msg) {
System.err.println(msg);
- System.err.println("Usage: java " + SocketMin.class
+ System.err.println("Usage: java " + SocketMin.class
+ " host port true|false");
System.exit(1);
}
1.4 +8 -10 jakarta-log4j/src/java/org/apache/log4j/net/test/SMTPMin.java
Index: SMTPMin.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/net/test/SMTPMin.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- SMTPMin.java 26 Dec 2000 21:42:47 -0000 1.3
+++ SMTPMin.java 24 Apr 2002 01:16:12 -0000 1.4
@@ -8,21 +8,19 @@
package org.apache.log4j.net.test;
import org.apache.log4j.*;
-import java.io.IOException;
-import java.io.InputStreamReader;
public class SMTPMin {
-
+
static Category cat = Category.getInstance(SMTPMin.class);
- public
- static
+ public
+ static
void main(String argv[]) {
- if(argv.length == 1)
+ if(argv.length == 1)
init(argv[0]);
- else
- usage("Wrong number of arguments.");
-
+ else
+ usage("Wrong number of arguments.");
+
NDC.push("some context");
test();
}
@@ -53,5 +51,5 @@
Category.shutdown();
Thread.currentThread().getThreadGroup().list();
}
-
+
}
1.2 +124 -129 jakarta-log4j/src/java/org/apache/log4j/net/TelnetAppender.java
Index: TelnetAppender.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/net/TelnetAppender.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- TelnetAppender.java 24 Sep 2001 23:58:25 -0000 1.1
+++ TelnetAppender.java 24 Apr 2002 01:16:12 -0000 1.2
@@ -7,67 +7,62 @@
package org.apache.log4j.net;
-import java.io.*;
-import java.net.*;
-import java.util.*;
-import org.apache.log4j.Layout;
-import org.apache.log4j.spi.Filter;
-import org.apache.log4j.spi.ErrorHandler;
-import org.apache.log4j.spi.OptionHandler;
-import org.apache.log4j.spi.LoggingEvent;
-import org.apache.log4j.helpers.OnlyOnceErrorHandler;
-import org.apache.log4j.helpers.LogLog;
-import org.apache.log4j.AppenderSkeleton;
+import java.io.*;
+import java.net.*;
+import java.util.*;
+import org.apache.log4j.Layout;
+import org.apache.log4j.spi.LoggingEvent;
+import org.apache.log4j.AppenderSkeleton;
-/**
+/**
<p>The TelnetAppender is a log4j appender that specializes in
writing to a read-only socket. The output is provided in a
telnet-friendly way so that a log can be monitored over TCP/IP.
Clients using telnet connect to the socket and receive log data.
This is handy for remote monitoring, especially when monitoring a
servlet.
-
+
<p>Here is a list of the available configuration options:
-
- <table border=1>
- <tr>
- <th>Name</th>
- <th>Requirement</th>
- <th>Description</th>
- <th>Sample Value</th>
- </tr>
-
- <tr>
- <td>Port</td>
- <td>optional</td>
- <td>This parameter determines the port to use for announcing log events. The default port is 23 (telnet).</td>
- <td>5875</td>
- </table>
-
- @author <a HREF="mailto:[email protected]">Jay Funnell</a>
+
+ <table border=1>
+ <tr>
+ <th>Name</th>
+ <th>Requirement</th>
+ <th>Description</th>
+ <th>Sample Value</th>
+ </tr>
+
+ <tr>
+ <td>Port</td>
+ <td>optional</td>
+ <td>This parameter determines the port to use for announcing log events. The default port is 23 (telnet).</td>
+ <td>5875</td>
+ </table>
+
+ @author <a HREF="mailto:[email protected]">Jay Funnell</a>
*/
-public class TelnetAppender extends AppenderSkeleton {
+public class TelnetAppender extends AppenderSkeleton {
- private SocketHandler sh;
- private int port = 23;
+ private SocketHandler sh;
+ private int port = 23;
+
+ /** this appender requires a layout to format the text to the attached client(s). */
+ public boolean requiresLayout() {
+ return true;
+ }
- /** this appender requires a layout to format the text to the attached client(s). */
- public boolean requiresLayout() {
- return true;
- }
-
/** all of the options have been set, create the socket handler and
wait for connections. */
- public void activateOptions() {
- try {
- sh = new SocketHandler(port);
- sh.start();
- }
- catch(Exception e) {
- e.printStackTrace();
- }
- }
+ public void activateOptions() {
+ try {
+ sh = new SocketHandler(port);
+ sh.start();
+ }
+ catch(Exception e) {
+ e.printStackTrace();
+ }
+ }
public
int getPort() {
@@ -79,17 +74,17 @@
this.port = port;
}
-
- /** shuts down the appender. */
- public void close() {
- sh.finalize();
- }
-
+
+ /** shuts down the appender. */
+ public void close() {
+ sh.finalize();
+ }
+
/** Handles a log event. For this appender, that means writing the
message to each connected client. */
- protected void append(LoggingEvent event) {
- sh.send(this.layout.format(event));
- if(layout.ignoresThrowable()) {
+ protected void append(LoggingEvent event) {
+ sh.send(this.layout.format(event));
+ if(layout.ignoresThrowable()) {
String[] s = event.getThrowableStrRep();
if (s != null) {
int len = s.length;
@@ -98,83 +93,83 @@
sh.send(Layout.LINE_SEP);
}
}
- }
- }
-
- //---------------------------------------------------------- SocketHandler:
-
+ }
+ }
+
+ //---------------------------------------------------------- SocketHandler:
+
/** The SocketHandler class is used to accept connections from
clients. It is threaded so that clients can connect/disconnect
asynchronously. */
- protected class SocketHandler extends Thread {
+ protected class SocketHandler extends Thread {
+
+ private Vector writers = new Vector();
+ private Vector connections = new Vector();
+ private ServerSocket serverSocket;
+ private int MAX_CONNECTIONS = 20;
+
+ /** make sure we close all network connections when this handler is destroyed. */
+ public void finalize() {
+ for(Enumeration e = connections.elements();e.hasMoreElements();) {
+ try {
+ ((Socket)e.nextElement()).close();
+ }
+ catch(Exception ex) {
+ }
+ }
+ try {
+ serverSocket.close();
+ }
+ catch(Exception ex) {
+ }
+ }
+
+ /** sends a message to each of the clients in telnet-friendly output. */
+ public void send(String message) {
+ Enumeration ce = connections.elements();
+ for(Enumeration e = writers.elements();e.hasMoreElements();) {
+ Socket sock = (Socket)ce.nextElement();
+ PrintWriter writer = (PrintWriter)e.nextElement();
+ writer.print(message);
+ if(writer.checkError()) {
+
+ // The client has closed the connection, remove it from our list:
+
+ connections.remove(sock);
+ writers.remove(writer);
+
+ }
+ }
+ }
- private Vector writers = new Vector();
- private Vector connections = new Vector();
- private ServerSocket serverSocket;
- private int MAX_CONNECTIONS = 20;
-
- /** make sure we close all network connections when this handler is destroyed. */
- public void finalize() {
- for(Enumeration e = connections.elements();e.hasMoreElements();) {
- try {
- ((Socket)e.nextElement()).close();
- }
- catch(Exception ex) {
- }
- }
- try {
- serverSocket.close();
- }
- catch(Exception ex) {
- }
- }
-
- /** sends a message to each of the clients in telnet-friendly output. */
- public void send(String message) {
- Enumeration ce = connections.elements();
- for(Enumeration e = writers.elements();e.hasMoreElements();) {
- Socket sock = (Socket)ce.nextElement();
- PrintWriter writer = (PrintWriter)e.nextElement();
- writer.print(message);
- if(writer.checkError()) {
-
- // The client has closed the connection, remove it from our list:
-
- connections.remove(sock);
- writers.remove(writer);
-
- }
- }
- }
-
/** continually accepts client connections. Client connections
are refused when MAX_CONNECTIONS is reached. */
- public void run() {
- while(true) {
- try {
- Socket newClient = serverSocket.accept();
- PrintWriter pw = new PrintWriter(newClient.getOutputStream());
- if(connections.size() < MAX_CONNECTIONS) {
- connections.addElement(newClient);
- writers.addElement(pw);
- pw.print("TelnetAppender v1.0 (" + connections.size() + " active connections)\r\n\r\n");
- pw.flush();
- }
- else {
- pw.print("Too many connections.\r\n");
- pw.flush();
- newClient.close();
- }
- }
- catch(Exception e) {
- e.printStackTrace();
- }
- }
- }
-
- public SocketHandler(int port) throws IOException {
- serverSocket = new ServerSocket(port);
- }
+ public void run() {
+ while(true) {
+ try {
+ Socket newClient = serverSocket.accept();
+ PrintWriter pw = new PrintWriter(newClient.getOutputStream());
+ if(connections.size() < MAX_CONNECTIONS) {
+ connections.addElement(newClient);
+ writers.addElement(pw);
+ pw.print("TelnetAppender v1.0 (" + connections.size() + " active connections)\r\n\r\n");
+ pw.flush();
+ }
+ else {
+ pw.print("Too many connections.\r\n");
+ pw.flush();
+ newClient.close();
+ }
+ }
+ catch(Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ public SocketHandler(int port) throws IOException {
+ serverSocket = new ServerSocket(port);
+ }
- }
-}
+ }
+}
1.15 +56 -65 jakarta-log4j/src/java/org/apache/log4j/net/SyslogAppender.java
Index: SyslogAppender.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/net/SyslogAppender.java,v
retrieving revision 1.14
retrieving revision 1.15
diff -u -r1.14 -r1.15
--- SyslogAppender.java 2 Sep 2001 20:05:39 -0000 1.14
+++ SyslogAppender.java 24 Apr 2002 01:16:12 -0000 1.15
@@ -7,17 +7,8 @@
package org.apache.log4j.net;
-import java.net.DatagramSocket;
-import java.net.InetAddress;
-import java.net.DatagramPacket;
-import java.net.UnknownHostException;
-import java.net.SocketException;
-
-import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
-import org.apache.log4j.Category;
-import org.apache.log4j.Level;
import org.apache.log4j.Layout;
import org.apache.log4j.helpers.SyslogWriter;
import org.apache.log4j.helpers.SyslogQuietWriter;
@@ -27,7 +18,7 @@
/**
Use SyslogAppender to send log messages to a remote syslog daemon.
-
+
@author Ceki Gülcü
@author Anders Kristensen
*/
@@ -35,77 +26,77 @@
// The following constants are extracted from a syslog.h file
// copyrighted by the Regents of the University of California
// I hope nobody at Berkley gets offended.
-
+
/** Kernel messages */
- final static public int LOG_KERN = 0;
+ final static public int LOG_KERN = 0;
/** Random user-level messages */
- final static public int LOG_USER = 1<<3;
+ final static public int LOG_USER = 1<<3;
/** Mail system */
- final static public int LOG_MAIL = 2<<3;
+ final static public int LOG_MAIL = 2<<3;
/** System daemons */
- final static public int LOG_DAEMON = 3<<3;
+ final static public int LOG_DAEMON = 3<<3;
/** security/authorization messages */
- final static public int LOG_AUTH = 4<<3;
+ final static public int LOG_AUTH = 4<<3;
/** messages generated internally by syslogd */
- final static public int LOG_SYSLOG = 5<<3;
-
- /** line printer subsystem */
- final static public int LOG_LPR = 6<<3;
+ final static public int LOG_SYSLOG = 5<<3;
+
+ /** line printer subsystem */
+ final static public int LOG_LPR = 6<<3;
/** network news subsystem */
- final static public int LOG_NEWS = 7<<3;
+ final static public int LOG_NEWS = 7<<3;
/** UUCP subsystem */
- final static public int LOG_UUCP = 8<<3;
+ final static public int LOG_UUCP = 8<<3;
/** clock daemon */
- final static public int LOG_CRON = 9<<3;
+ final static public int LOG_CRON = 9<<3;
/** security/authorization messages (private) */
- final static public int LOG_AUTHPRIV = 10<<3;
+ final static public int LOG_AUTHPRIV = 10<<3;
/** ftp daemon */
- final static public int LOG_FTP = 11<<3;
+ final static public int LOG_FTP = 11<<3;
// other codes through 15 reserved for system use
/** reserved for local use */
- final static public int LOG_LOCAL0 = 16<<3;
+ final static public int LOG_LOCAL0 = 16<<3;
/** reserved for local use */
- final static public int LOG_LOCAL1 = 17<<3;
+ final static public int LOG_LOCAL1 = 17<<3;
/** reserved for local use */
- final static public int LOG_LOCAL2 = 18<<3;
+ final static public int LOG_LOCAL2 = 18<<3;
/** reserved for local use */
- final static public int LOG_LOCAL3 = 19<<3;
+ final static public int LOG_LOCAL3 = 19<<3;
/** reserved for local use */
- final static public int LOG_LOCAL4 = 20<<3;
+ final static public int LOG_LOCAL4 = 20<<3;
/** reserved for local use */
- final static public int LOG_LOCAL5 = 21<<3;
+ final static public int LOG_LOCAL5 = 21<<3;
/** reserved for local use */
- final static public int LOG_LOCAL6 = 22<<3;
+ final static public int LOG_LOCAL6 = 22<<3;
/** reserved for local use*/
- final static public int LOG_LOCAL7 = 23<<3;
+ final static public int LOG_LOCAL7 = 23<<3;
protected static final int SYSLOG_HOST_OI = 0;
protected static final int FACILITY_OI = 1;
-
+
static final String TAB = " ";
// Have LOG_USER as default
int syslogFacility = LOG_USER;
- String facilityStr;
+ String facilityStr;
boolean facilityPrinting = false;
-
+
//SyslogTracerPrintWriter stp;
- SyslogQuietWriter sqw;
+ SyslogQuietWriter sqw;
String syslogHost;
-
+
public
SyslogAppender() {
this.initSyslogFacilityStr();
}
-
+
public
SyslogAppender(Layout layout, int syslogFacility) {
this.layout = layout;
- this.syslogFacility = syslogFacility;
+ this.syslogFacility = syslogFacility;
this.initSyslogFacilityStr();
}
-
+
public
SyslogAppender(Layout layout, String syslogHost, int syslogFacility) {
this(layout, syslogFacility);
@@ -122,14 +113,14 @@
void close() {
closed = true;
// A SyslogWriter is UDP based and needs no opening. Hence, it
- // can't be closed. We just unset the variables here.
+ // can't be closed. We just unset the variables here.
sqw = null;
}
-
+
private
void initSyslogFacilityStr() {
facilityStr = getFacilityString(this.syslogFacility);
-
+
if (facilityStr == null) {
System.err.println("\"" + syslogFacility +
"\" is an unknown syslog facility. Defaulting to \"USER\".");
@@ -138,7 +129,7 @@
} else {
facilityStr += ":";
}
- }
+ }
/**
Returns the specified syslog facility as a lower-case String,
@@ -169,8 +160,8 @@
case LOG_LOCAL6: return "local6";
case LOG_LOCAL7: return "local7";
default: return null;
- }
- }
+ }
+ }
/**
Returns the integer value corresponding to the named syslog
@@ -180,7 +171,7 @@
AUTH, SYSLOG, LPR, NEWS, UUCP, CRON, AUTHPRIV, FTP, LOCAL0,
LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7.
The matching is case-insensitive.
-
+
@since 1.1
*/
public
@@ -233,13 +224,13 @@
return -1;
}
}
-
+
public
void append(LoggingEvent event) {
if(!isAsSevereAsThreshold(event.level))
return;
-
+
// We must not attempt to append if sqw is null.
if(sqw == null) {
errorHandler.error("No syslog host is set for SyslogAppedender named \""+
@@ -250,7 +241,7 @@
String buffer = (facilityPrinting? facilityStr : "") +
layout.format(event);
- sqw.setLevel(event.level.getSyslogEquivalent());
+ sqw.setLevel(event.level.getSyslogEquivalent());
sqw.write(buffer);
String[] s = event.getThrowableStrRep();
@@ -258,10 +249,10 @@
int len = s.length;
if(len > 0) {
sqw.write(s[0]);
-
+
for(int i = 1; i < len; i++) {
sqw.write(TAB+s[i].substring(1));
- }
+ }
}
}
@@ -284,22 +275,22 @@
boolean requiresLayout() {
return true;
}
-
+
/**
The <b>SyslogHost</b> option is the name of the the syslog host
where log output should go.
<b>WARNING</b> If the SyslogHost is not set, then this appender
- will fail.
+ will fail.
*/
public
void setSyslogHost(String syslogHost) {
- this.sqw = new SyslogQuietWriter(new SyslogWriter(syslogHost),
+ this.sqw = new SyslogQuietWriter(new SyslogWriter(syslogHost),
syslogFacility, errorHandler);
- //this.stp = new SyslogTracerPrintWriter(sqw);
+ //this.stp = new SyslogTracerPrintWriter(sqw);
this.syslogHost = syslogHost;
}
-
+
/**
Returns the value of the <b>SyslogHost</b> option.
*/
@@ -307,7 +298,7 @@
String getSyslogHost() {
return syslogHost;
}
-
+
/**
Set the syslog facility. This is the <b>Facility</b> option.
@@ -315,20 +306,20 @@
strings KERN, USER, MAIL, DAEMON, AUTH, SYSLOG, LPR, NEWS, UUCP,
CRON, AUTHPRIV, FTP, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4,
LOCAL5, LOCAL6, LOCAL7. Case is unimportant.
-
+
@since 0.8.1 */
public
void setFacility(String facilityName) {
if(facilityName == null)
return;
-
+
syslogFacility = getFacility(facilityName);
if (syslogFacility == -1) {
System.err.println("["+facilityName +
"] is an unknown syslog facility. Defaulting to [USER].");
syslogFacility = LOG_USER;
}
-
+
this.initSyslogFacilityStr();
// If there is already a sqw, make it use the new facility.
@@ -336,7 +327,7 @@
sqw.setSyslogFacility(this.syslogFacility);
}
}
-
+
/**
Returns the value of the <b>Facility</b> option.
*/
@@ -344,7 +335,7 @@
String getFacility() {
return getFacilityString(syslogFacility);
}
-
+
/**
If the <b>FacilityPrinting</b> option is set to true, the printed
message will include the facility name of the application. It is
@@ -354,7 +345,7 @@
void setFacilityPrinting(boolean on) {
facilityPrinting = on;
}
-
+
/**
Returns the value of the <b>FacilityPrinting</b> option.
*/
1.10 +21 -23 jakarta-log4j/src/java/org/apache/log4j/net/SocketServer.java
Index: SocketServer.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/net/SocketServer.java,v
retrieving revision 1.9
retrieving revision 1.10
diff -u -r1.9 -r1.10
--- SocketServer.java 11 Feb 2002 16:14:34 -0000 1.9
+++ SocketServer.java 24 Apr 2002 01:16:12 -0000 1.10
@@ -10,8 +10,6 @@
import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
-import java.net.MalformedURLException;
-import java.io.IOException;
import java.io.File;
import java.util.Hashtable;
@@ -56,7 +54,7 @@
<p>Having different client hosts log using different hierarchies
ensures the total independence of the clients with respect to
- their logging settings.
+ their logging settings.
<p>Currently, the hierarchy that will be used for a given request
depends on the IP address of the client host. For example, two
@@ -67,9 +65,9 @@
as an example to be enhanced in order to implement more elaborate
policies.
-
+
@author Ceki Gülcü
-
+
@since 1.0 */
public class SocketServer {
@@ -77,7 +75,7 @@
static String GENERIC = "generic";
static String CONFIG_FILE_EXT = ".lcf";
- static Category cat = Category.getInstance(SocketServer.class);
+ static Category cat = Category.getInstance(SocketServer.class);
static SocketServer server;
static int port;
@@ -86,14 +84,14 @@
LoggerRepository genericHierarchy;
File dir;
- public
- static
+ public
+ static
void main(String argv[]) {
- if(argv.length == 3)
+ if(argv.length == 3)
init(argv[0], argv[1], argv[2]);
- else
- usage("Wrong number of arguments.");
-
+ else
+ usage("Wrong number of arguments.");
+
try {
cat.info("Listening on port " + port);
ServerSocket serverSocket = new ServerSocket(port);
@@ -106,9 +104,9 @@
LoggerRepository h = (LoggerRepository) server.hierarchyMap.get(inetAddress);
if(h == null) {
h = server.configureHierarchy(inetAddress);
- }
+ }
- cat.info("Starting new socket node.");
+ cat.info("Starting new socket node.");
new Thread(new SocketNode(socket, h)).start();
}
}
@@ -117,7 +115,7 @@
}
}
-
+
static
void usage(String msg) {
System.err.println(msg);
@@ -125,20 +123,20 @@
"Usage: java " +SocketServer.class.getName() + " port configFile directory");
System.exit(1);
}
-
+
static
void init(String portStr, String configFile, String dirStr) {
try {
- port = Integer.parseInt(portStr);
+ port = Integer.parseInt(portStr);
}
catch(java.lang.NumberFormatException e) {
e.printStackTrace();
usage("Could not interpret port number ["+ portStr +"].");
}
-
+
PropertyConfigurator.configure(configFile);
-
- File dir = new File(dirStr);
+
+ File dir = new File(dirStr);
if(!dir.isDirectory()) {
usage("["+dirStr+"] is not a directory.");
}
@@ -166,15 +164,15 @@
return genericHierarchy();
} else {
String key = s.substring(0, i);
-
+
File configFile = new File(dir, key+CONFIG_FILE_EXT);
if(configFile.exists()) {
Hierarchy h = new Hierarchy(new RootCategory((Level) Priority.DEBUG));
hierarchyMap.put(inetAddress, h);
-
+
new PropertyConfigurator().doConfigure(configFile.getAbsolutePath(), h);
- return h;
+ return h;
} else {
cat.warn("Could not find config file ["+configFile+"].");
return genericHierarchy();
1.18 +9 -12 jakarta-log4j/src/java/org/apache/log4j/net/SocketNode.java
Index: SocketNode.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/net/SocketNode.java,v
retrieving revision 1.17
retrieving revision 1.18
diff -u -r1.17 -r1.18
--- SocketNode.java 3 Apr 2002 22:18:14 -0000 1.17
+++ SocketNode.java 24 Apr 2002 01:16:12 -0000 1.18
@@ -8,10 +8,7 @@
package org.apache.log4j.net;
-import java.net.InetAddress;
import java.net.Socket;
-import java.net.ServerSocket;
-import java.io.InputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
@@ -28,9 +25,9 @@
<p>For example, the socket node might decide to log events to a
local file and also resent them to a second socket node.
-
+
@author Ceki Gülcü
-
+
@since 0.8.4
*/
public class SocketNode implements Runnable {
@@ -41,7 +38,7 @@
static Logger logger = Logger.getLogger(SocketNode.class);
- public
+ public
SocketNode(Socket socket, LoggerRepository hierarchy) {
this.socket = socket;
this.hierarchy = hierarchy;
@@ -64,12 +61,12 @@
Logger remoteLogger;
try {
- while(true) {
- event = (LoggingEvent) ois.readObject();
+ while(true) {
+ event = (LoggingEvent) ois.readObject();
remoteLogger = hierarchy.getLogger(event.categoryName);
event.logger = remoteLogger;
if(event.level.isGreaterOrEqual(remoteLogger.getEffectiveLevel())) {
- remoteLogger.callAppenders(event);
+ remoteLogger.callAppenders(event);
}
}
}
@@ -83,11 +80,11 @@
} catch(Exception e) {
logger.error("Unexpected exception. Closing conneciton.", e);
}
-
+
try {
ois.close();
} catch(Exception e) {
- logger.info("Could not close connection.", e);
- }
+ logger.info("Could not close connection.", e);
+ }
}
}
1.12 +34 -41 jakarta-log4j/src/java/org/apache/log4j/net/SocketAppender.java
Index: SocketAppender.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/net/SocketAppender.java,v
retrieving revision 1.11
retrieving revision 1.12
diff -u -r1.11 -r1.12
--- SocketAppender.java 4 Apr 2002 14:46:02 -0000 1.11
+++ SocketAppender.java 24 Apr 2002 01:16:12 -0000 1.12
@@ -12,19 +12,12 @@
import java.net.InetAddress;
import java.net.Socket;
-import java.io.OutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.ObjectOutputStream;
-import java.io.OutputStreamWriter;
-import java.io.StringWriter;
-import java.io.PrintWriter;
import org.apache.log4j.helpers.LogLog;
-import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.spi.LoggingEvent;
-import org.apache.log4j.Category;
-import org.apache.log4j.Priority;
import org.apache.log4j.AppenderSkeleton;
/**
@@ -47,13 +40,13 @@
<p><li>Remote logging uses the TCP protocol. Consequently, if
the server is reachable, then log events will eventually arrive
at the server.
-
+
<p><li>If the remote server is down, the logging requests are
simply dropped. However, if and when the server comes back up,
then event transmission is resumed transparently. This
transparent reconneciton is performed by a <em>connector</em>
thread which periodically attempts to connect to the server.
-
+
<p><li>Logging events are automatically <em>buffered</em> by the
native TCP implementation. This means that if the link to server
is slow but still faster than the rate of (log) event production
@@ -92,7 +85,7 @@
</ul>
-
+
@author Ceki Gülcü
@since 0.8.4 */
@@ -102,7 +95,7 @@
The default port number of remote logging server (4560).
*/
static final int DEFAULT_PORT = 4560;
-
+
/**
The default reconnection delay (30000 milliseconds or 30 seconds).
*/
@@ -113,7 +106,7 @@
InetAddress so that it can be returned via getOption().
*/
String remoteHost;
-
+
InetAddress address;
int port = DEFAULT_PORT;
ObjectOutputStream oos;
@@ -122,8 +115,8 @@
private Connector connector;
- int counter = 0;
-
+ int counter = 0;
+
// reset the ObjectOutputStream every 70 calls
//private static final int RESET_FREQUENCY = 70;
@@ -147,15 +140,15 @@
Connects to remote server at <code>host</code> and <code>port</code>.
*/
public
- SocketAppender(String host, int port) {
+ SocketAppender(String host, int port) {
this.port = port;
this.address = getAddressByName(host);
this.remoteHost = host;
connect(address, port);
}
-
+
/**
- Connect to the specified <b>RemoteHost</b> and <b>Port</b>.
+ Connect to the specified <b>RemoteHost</b> and <b>Port</b>.
*/
public
void activateOptions() {
@@ -163,7 +156,7 @@
}
/**
- Close this appender.
+ Close this appender.
<p>This will mark the appender as closed and
call then {@link #cleanUp} method.
*/
@@ -181,7 +174,7 @@
Drop the connection to the remote host and release the underlying
connector thread if it has been created
*/
- public
+ public
void cleanUp() {
if(oos != null) {
try {
@@ -190,10 +183,10 @@
catch(IOException e) {
LogLog.error("Could not close oos.", e);
}
- oos = null;
+ oos = null;
}
if(connector != null) {
- //LogLog.debug("Interrupting the connector.");
+ //LogLog.debug("Interrupting the connector.");
connector.interrupted = true;
connector = null; // allow gc
}
@@ -204,7 +197,7 @@
return;
try {
// First, close the previous connection if any.
- cleanUp();
+ cleanUp();
oos = new ObjectOutputStream(new Socket(address, port).getOutputStream());
}
catch(IOException e) {
@@ -229,8 +222,8 @@
if(oos != null) {
try {
if(locationInfo) {
- event.getLocationInformation();
- }
+ event.getLocationInformation();
+ }
oos.writeObject(event);
//LogLog.debug("=========Flushing.");
oos.flush();
@@ -258,15 +251,15 @@
connector = new Connector();
connector.setDaemon(true);
connector.setPriority(Thread.MIN_PRIORITY);
- connector.start();
+ connector.start();
}
}
-
+
static
InetAddress getAddressByName(String host) {
try {
return InetAddress.getByName(host);
- }
+ }
catch(Exception e) {
LogLog.error("Could not find address of ["+host+"].", e);
return null;
@@ -291,7 +284,7 @@
address = getAddressByName(host);
remoteHost = host;
}
-
+
/**
Returns value of the <b>RemoteHost</b> option.
*/
@@ -299,7 +292,7 @@
String getRemoteHost() {
return remoteHost;
}
-
+
/**
The <b>Port</b> option takes a positive integer representing
the port where the server is waiting for connections.
@@ -308,7 +301,7 @@
void setPort(int port) {
this.port = port;
}
-
+
/**
Returns value of the <b>Port</b> option.
*/
@@ -316,7 +309,7 @@
int getPort() {
return port;
}
-
+
/**
The <b>LocationInfo</b> option takes a boolean value. If true,
the information sent to the remote host will include location
@@ -326,7 +319,7 @@
void setLocationInfo(boolean locationInfo) {
this.locationInfo = locationInfo;
}
-
+
/**
Returns value of the <b>LocationInfo</b> option.
*/
@@ -334,13 +327,13 @@
boolean getLocationInfo() {
return locationInfo;
}
-
+
/**
The <b>ReconnectionDelay</b> option takes a positive integer
representing the number of milliseconds to wait between each
failed connection attempt to the server. The default value of
this option is 30000 which corresponds to 30 seconds.
-
+
<p>Setting this option to zero turns off reconnection
capability.
*/
@@ -348,7 +341,7 @@
void setReconnectionDelay(int delay) {
this.reconnectionDelay = delay;
}
-
+
/**
Returns value of the <b>ReconnectionDelay</b> option.
*/
@@ -356,7 +349,7 @@
int getReconnectionDelay() {
return reconnectionDelay;
}
-
+
/**
The Connector will reconnect when the server becomes available
again. It does this by attempting to open a new connection every
@@ -366,7 +359,7 @@
restart to try reconnect to the server when previpously open
connection is droppped.
- @author Ceki Gülcü
+ @author Ceki Gülcü
@since 0.8.4
*/
class Connector extends Thread {
@@ -375,14 +368,14 @@
public
void run() {
- Socket socket;
+ Socket socket;
while(!interrupted) {
try {
sleep(reconnectionDelay);
LogLog.debug("Attempting connection to "+address.getHostName());
socket = new Socket(address, port);
synchronized(this) {
- oos = new ObjectOutputStream(socket.getOutputStream());
+ oos = new ObjectOutputStream(socket.getOutputStream());
connector = null;
break;
}
@@ -395,14 +388,14 @@
LogLog.debug("Remote host "+address.getHostName()
+" refused connection.");
}
- catch(IOException e) {
+ catch(IOException e) {
LogLog.debug("Could not connect to " + address.getHostName()+
". Exception is " + e);
}
}
//LogLog.debug("Exiting Connector.run() method.");
}
-
+
/**
public
void finalize() {
1.3 +14 -16 jakarta-log4j/src/java/org/apache/log4j/net/SimpleSocketServer.java
Index: SimpleSocketServer.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/net/SimpleSocketServer.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- SimpleSocketServer.java 5 Sep 2001 06:45:28 -0000 1.2
+++ SimpleSocketServer.java 24 Apr 2002 01:16:12 -0000 1.3
@@ -9,12 +9,10 @@
import java.net.Socket;
import java.net.ServerSocket;
-import java.io.IOException;
import org.apache.log4j.Category;
import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
-import org.apache.log4j.spi.LoggerRepository;
/**
@@ -29,7 +27,7 @@
</pre>
@author Ceki Gülcü
-
+
@since 0.8.4 */
public class SimpleSocketServer {
@@ -37,15 +35,15 @@
static Category cat = Category.getInstance(SimpleSocketServer.class.getName());
static int port;
-
- public
- static
+
+ public
+ static
void main(String argv[]) {
- if(argv.length == 2)
+ if(argv.length == 2)
init(argv[0], argv[1]);
- else
- usage("Wrong number of arguments.");
-
+ else
+ usage("Wrong number of arguments.");
+
try {
cat.info("Listening on port " + port);
ServerSocket serverSocket = new ServerSocket(port);
@@ -53,8 +51,8 @@
cat.info("Waiting to accept a new client.");
Socket socket = serverSocket.accept();
cat.info("Connected to client at " + socket.getInetAddress());
- cat.info("Starting new socket node.");
- new Thread(new SocketNode(socket,
+ cat.info("Starting new socket node.");
+ new Thread(new SocketNode(socket,
LogManager.getLoggerRepository())).start();
}
}
@@ -63,7 +61,7 @@
}
}
-
+
static
void usage(String msg) {
System.err.println(msg);
@@ -71,16 +69,16 @@
"Usage: java " +SimpleSocketServer.class.getName() + " port configFile");
System.exit(1);
}
-
+
static
void init(String portStr, String configFile) {
try {
- port = Integer.parseInt(portStr);
+ port = Integer.parseInt(portStr);
}
catch(java.lang.NumberFormatException e) {
e.printStackTrace();
usage("Could not interpret port number ["+ portStr +"].");
}
- PropertyConfigurator.configure(configFile);
+ PropertyConfigurator.configure(configFile);
}
}
1.28 +34 -37 jakarta-log4j/src/java/org/apache/log4j/net/SMTPAppender.java
Index: SMTPAppender.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/net/SMTPAppender.java,v
retrieving revision 1.27
retrieving revision 1.28
diff -u -r1.27 -r1.28
--- SMTPAppender.java 23 Sep 2001 21:59:08 -0000 1.27
+++ SMTPAppender.java 24 Apr 2002 01:16:12 -0000 1.28
@@ -8,14 +8,12 @@
package org.apache.log4j.net;
import org.apache.log4j.AppenderSkeleton;
-import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.helpers.CyclicBuffer;
import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.ErrorCode;
-import org.apache.log4j.spi.ErrorHandler;
import org.apache.log4j.spi.TriggeringEventEvaluator;
import java.util.Properties;
import java.util.Date;
@@ -30,7 +28,6 @@
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.AddressException;
-import javax.mail.internet.MimeUtility;
/**
Send an e-mail when a specific logging event occurs, typically on
@@ -42,7 +39,7 @@
<code>BufferSize</code> logging events in its cyclic buffer. This
keeps memory requirements at a reasonable level while still
delivering useful application context.
-
+
@author Ceki Gülcü
@since 1.0 */
public class SMTPAppender extends AppenderSkeleton {
@@ -69,11 +66,11 @@
this(new DefaultEvaluator());
}
-
+
/**
Use <code>evaluator</code> passed as parameter as the {@link
TriggeringEventEvaluator} for this SMTPAppender. */
- public
+ public
SMTPAppender(TriggeringEventEvaluator evaluator) {
this.evaluator = evaluator;
}
@@ -88,11 +85,11 @@
if (smtpHost != null)
props.put("mail.smtp.host", smtpHost);
-
+
Session session = Session.getInstance(props, null);
//session.setDebug(true);
msg = new MimeMessage(session);
-
+
try {
if (from != null)
msg.setFrom(getAddress(from));
@@ -106,7 +103,7 @@
LogLog.error("Could not activate SMTPAppender options.", e );
}
}
-
+
/**
Perform SMTPAppender specific appending actions, mainly adding
the event to a cyclic buffer and checking if the event triggers
@@ -121,9 +118,9 @@
event.getThreadName();
event.getNDC();
if(locationInfo) {
- event.getLocationInformation();
+ event.getLocationInformation();
}
- cb.add(event);
+ cb.add(event);
if(evaluator.isTriggeringEvent(event)) {
sendBuffer();
}
@@ -131,7 +128,7 @@
/**
This method determines if there is a sense in attempting to append.
-
+
<p>It checks whether there is a set output target and also if
there is a set layout. If these checks fail, then the boolean
value <code>false</code> is returned. */
@@ -148,7 +145,7 @@
return false;
}
-
+
if(this.layout == null) {
errorHandler.error("No layout set for appender named ["+name+"].");
return false;
@@ -193,7 +190,7 @@
/**
- The <code>SMTPAppender</code> requires a {@link Layout layout}.
+ The <code>SMTPAppender</code> requires a {@link Layout layout}.
*/
public
boolean requiresLayout() {
@@ -208,14 +205,14 @@
// Note: this code already owns the monitor for this
// appender. This frees us from needing to synchronize on 'cb'.
- try {
+ try {
MimeBodyPart part = new MimeBodyPart();
StringBuffer sbuf = new StringBuffer();
String t = layout.getHeader();
if(t != null)
sbuf.append(t);
- int len = cb.length();
+ int len = cb.length();
for(int i = 0; i < len; i++) {
//sbuf.append(MimeUtility.encodeText(layout.format(cb.get())));
LoggingEvent event = cb.get();
@@ -232,19 +229,19 @@
t = layout.getFooter();
if(t != null)
sbuf.append(t);
- part.setContent(sbuf.toString(), layout.getContentType());
+ part.setContent(sbuf.toString(), layout.getContentType());
Multipart mp = new MimeMultipart();
mp.addBodyPart(part);
msg.setContent(mp);
msg.setSentDate(new Date());
- Transport.send(msg);
+ Transport.send(msg);
} catch(Exception e) {
LogLog.error("Error occured while sending e-mail notification.", e);
}
}
-
+
/**
@@ -254,7 +251,7 @@
String getEvaluatorClass() {
return evaluator == null ? null : evaluator.getClass().getName();
}
-
+
/**
Returns value of the <b>From</b> option.
*/
@@ -270,7 +267,7 @@
String getSubject() {
return subject;
}
-
+
/**
The <b>From</b> option takes a string value which should be a
e-mail address of the sender.
@@ -279,7 +276,7 @@
void setFrom(String from) {
this.from = from;
}
-
+
/**
The <b>Subject</b> option takes a string value which should be a
the subject of the e-mail message.
@@ -288,7 +285,7 @@
void setSubject(String subject) {
this.subject = subject;
}
-
+
/**
The <b>BufferSize</b> option takes a positive integer
@@ -302,7 +299,7 @@
this.bufferSize = bufferSize;
cb.resize(bufferSize);
}
-
+
/**
The <b>SMTPHost</b> option takes a string value which should be a
the host name of the SMTP server that will send the e-mail message.
@@ -311,7 +308,7 @@
void setSMTPHost(String smtpHost) {
this.smtpHost = smtpHost;
}
-
+
/**
Returns value of the <b>SMTPHost</b> option.
*/
@@ -329,7 +326,7 @@
this.to = to;
}
-
+
/**
Returns value of the <b>BufferSize</b> option.
@@ -338,7 +335,7 @@
int getBufferSize() {
return bufferSize;
}
-
+
/**
The <b>EvaluatorClass</b> option takes a string value
representing the name of the class implementing the {@link
@@ -348,13 +345,13 @@
*/
public
void setEvaluatorClass(String value) {
- evaluator = (TriggeringEventEvaluator)
- OptionConverter.instantiateByClassName(value,
+ evaluator = (TriggeringEventEvaluator)
+ OptionConverter.instantiateByClassName(value,
TriggeringEventEvaluator.class,
- evaluator);
+ evaluator);
}
-
-
+
+
/**
The <b>LocationInfo</b> option takes a boolean value. By
default, it is set to false which means there will be no effort
@@ -362,7 +359,7 @@
result, the layout that formats the events as they are sent out
in an e-mail is likely to place the wrong location information
(if present in the format).
-
+
<p>Location information extraction is comparatively very slow and
should be avoided unless performance is not a concern.
*/
@@ -370,7 +367,7 @@
void setLocationInfo(boolean locationInfo) {
this.locationInfo = locationInfo;
}
-
+
/**
Returns value of the <b>LocationInfo</b> option.
*/
@@ -383,12 +380,12 @@
class DefaultEvaluator implements TriggeringEventEvaluator {
/**
Is this <code>event</code> the e-mail triggering event?
-
+
<p>This method returns <code>true</code>, if the event level
has ERROR level or higher. Otherwise it returns
<code>false</code>. */
- public
+ public
boolean isTriggeringEvent(LoggingEvent event) {
- return event.level.isGreaterOrEqual(Level.ERROR);
+ return event.level.isGreaterOrEqual(Level.ERROR);
}
}
1.12 +16 -18 jakarta-log4j/src/java/org/apache/log4j/net/JMSSink.java
Index: JMSSink.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/net/JMSSink.java,v
retrieving revision 1.11
retrieving revision 1.12
diff -u -r1.11 -r1.12
--- JMSSink.java 30 Mar 2002 10:33:29 -0000 1.11
+++ JMSSink.java 24 Apr 2002 01:16:12 -0000 1.12
@@ -7,10 +7,8 @@
package org.apache.log4j.net;
-import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.Category;
-import org.apache.log4j.Hierarchy;
import org.apache.log4j.LogManager;
import org.apache.log4j.spi.RendererSupport;
import org.apache.log4j.spi.LoggerRepository;
@@ -27,7 +25,7 @@
/**
A simple application receiving the logging events sent by a JMSAppender.
-
+
@author Ceki Gülcü
*/
@@ -35,47 +33,47 @@
static public void main(String[] args) {
if(args.length != 3) {
- usage("Wrong number of arguments.");
+ usage("Wrong number of arguments.");
}
String tcfBindingName = args[0];
String topicBindingName = args[1];
PropertyConfigurator.configure(args[2]);
-
+
LoggerRepository rep = LogManager.getLoggerRepository();
if(rep instanceof RendererSupport) {
((RendererSupport) rep).setRenderer(Message.class, new MessageRenderer());
}
try {
- Context ctx = new InitialContext();
+ Context ctx = new InitialContext();
TopicConnectionFactory topicConnectionFactory;
- topicConnectionFactory = (TopicConnectionFactory) lookup(ctx,
+ topicConnectionFactory = (TopicConnectionFactory) lookup(ctx,
tcfBindingName);
- TopicConnection topicConnection =
- topicConnectionFactory.createTopicConnection();
+ TopicConnection topicConnection =
+ topicConnectionFactory.createTopicConnection();
topicConnection.start();
-
+
TopicSession topicSession = topicConnection.createTopicSession(false,
Session.AUTO_ACKNOWLEDGE);
Topic topic = (Topic)ctx.lookup(topicBindingName);
//TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic);
- TopicSubscriber topicSubscriber =
+ TopicSubscriber topicSubscriber =
topicSession.createDurableSubscriber(topic, "x");
-
+
LoggingEvent event;
- Category remoteCategory;
+ Category remoteCategory;
while(true) {
- ObjectMessage msg = (ObjectMessage)topicSubscriber.receive();
+ ObjectMessage msg = (ObjectMessage)topicSubscriber.receive();
event = (LoggingEvent) msg.getObject();
remoteCategory = Category.getInstance(event.categoryName);
- remoteCategory.callAppenders(event);
-
+ remoteCategory.callAppenders(event);
+
// dump the JMSMessage
// remoteCategory.debug(msg);
@@ -94,8 +92,8 @@
} catch(NameNotFoundException e) {
LogLog.error("Could not find name ["+name+"].");
throw e;
- }
- }
+ }
+ }
static
1.13 +30 -33 jakarta-log4j/src/java/org/apache/log4j/net/JMSAppender.java
Index: JMSAppender.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/net/JMSAppender.java,v
retrieving revision 1.12
retrieving revision 1.13
diff -u -r1.12 -r1.13
--- JMSAppender.java 28 Nov 2001 22:20:44 -0000 1.12
+++ JMSAppender.java 24 Apr 2002 01:16:12 -0000 1.13
@@ -9,12 +9,9 @@
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
-import org.apache.log4j.spi.ErrorHandler;
import org.apache.log4j.spi.ErrorCode;
import org.apache.log4j.helpers.LogLog;
-import org.apache.log4j.helpers.OptionConverter;
-import java.util.Properties;
import javax.jms.*;
import javax.naming.InitialContext;
import javax.naming.Context;
@@ -23,11 +20,11 @@
/**
A simple appender based on JMS.
-
+
@author Ceki Gülcü
*/
public class JMSAppender extends AppenderSkeleton {
-
+
TopicConnection topicConnection;
TopicSession topicSession;
TopicPublisher topicPublisher;
@@ -35,7 +32,7 @@
String tcfBindingName;
boolean locationInfo;
- public
+ public
JMSAppender() {
}
@@ -48,7 +45,7 @@
void setTopicConnectionFactoryBindingName(String tcfBindingName) {
this.tcfBindingName = tcfBindingName;
}
-
+
/**
Returns the value of the <b>TopicConnectionFactoryBindingName</b> option.
*/
@@ -56,7 +53,7 @@
String getTopicConnectionFactoryBindingName() {
return tcfBindingName;
}
-
+
/**
The <b>TopicBindingName</b> option takes a
string value. Its value will be used to lookup the appropriate
@@ -66,7 +63,7 @@
void setTopicBindingName(String topicBindingName) {
this.topicBindingName = topicBindingName;
}
-
+
/**
Returns the value of the <b>TopicBindingName</b> option.
*/
@@ -84,30 +81,30 @@
boolean getLocationInfo() {
return locationInfo;
}
-
+
public
void activateOptions() {
TopicConnectionFactory topicConnectionFactory;
try {
- Context ctx = new InitialContext();
+ Context ctx = new InitialContext();
topicConnectionFactory = (TopicConnectionFactory) lookup(ctx, tcfBindingName);
topicConnection = topicConnectionFactory.createTopicConnection();
topicConnection.start();
-
+
topicSession = topicConnection.createTopicSession(false,
Session.AUTO_ACKNOWLEDGE);
-
+
Topic topic = (Topic) lookup(ctx, topicBindingName);
topicPublisher = topicSession.createPublisher(topic);
- ctx.close();
+ ctx.close();
} catch(Exception e) {
errorHandler.error("Error while activating options for appender named ["+name+
"].", e, ErrorCode.GENERIC_FAILURE);
}
}
-
+
protected
Object lookup(Context ctx, String name) throws NamingException {
try {
@@ -115,9 +112,9 @@
} catch(NameNotFoundException e) {
LogLog.error("Could not find name ["+name+"].");
throw e;
- }
+ }
}
-
+
protected
boolean checkEntryConditions() {
String fail = null;
@@ -128,10 +125,10 @@
fail = "No TopicSession";
} else if(this.topicPublisher == null) {
fail = "No TopicPublisher";
- }
+ }
if(fail != null) {
- errorHandler.error(fail +" for JMSAppender named ["+name+"].");
+ errorHandler.error(fail +" for JMSAppender named ["+name+"].");
return false;
} else {
return true;
@@ -141,23 +138,23 @@
/**
Close this JMSAppender. Closing releases all resources used by the
appender. A closed appender cannot be re-opened. */
- public
+ public
synchronized // avoid concurrent append and close operations
void close() {
- if(this.closed)
+ if(this.closed)
return;
LogLog.debug("Closing appender ["+name+"].");
- this.closed = true;
+ this.closed = true;
try {
- if(topicSession != null)
- topicSession.close();
- if(topicConnection != null)
+ if(topicSession != null)
+ topicSession.close();
+ if(topicConnection != null)
topicConnection.close();
} catch(Exception e) {
- LogLog.error("Error while closing JMSAppender ["+name+"].", e);
- }
+ LogLog.error("Error while closing JMSAppender ["+name+"].", e);
+ }
// Help garbage collection
topicPublisher = null;
topicSession = null;
@@ -176,17 +173,17 @@
try {
ObjectMessage msg = topicSession.createObjectMessage();
if(locationInfo) {
- event.getLocationInformation();
- }
+ event.getLocationInformation();
+ }
msg.setObject(event);
topicPublisher.publish(msg);
} catch(Exception e) {
- errorHandler.error("Could not publish message in JMSAppender ["+name+"].", e,
+ errorHandler.error("Could not publish message in JMSAppender ["+name+"].", e,
ErrorCode.GENERIC_FAILURE);
}
}
- /**
+ /**
If true, the information sent to the remote subscriber will include
location information. By default no location information is sent
to the subscriber. */
@@ -194,10 +191,10 @@
void setLocationInfo(boolean locationInfo) {
this.locationInfo = locationInfo;
}
-
+
public
boolean requiresLayout() {
return false;
- }
+ }
}
1.2 +43 -47 jakarta-log4j/src/java/org/apache/log4j/jmx/LoggerDynamicMBean.java
Index: LoggerDynamicMBean.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/jmx/LoggerDynamicMBean.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- LoggerDynamicMBean.java 24 Sep 2001 22:16:27 -0000 1.1
+++ LoggerDynamicMBean.java 24 Apr 2002 01:16:13 -0000 1.2
@@ -2,7 +2,6 @@
package org.apache.log4j.jmx;
import java.lang.reflect.Constructor;
-import org.apache.log4j.Hierarchy;
import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import org.apache.log4j.Appender;
@@ -19,19 +18,16 @@
import javax.management.ObjectName;
import javax.management.MBeanInfo;
import javax.management.Attribute;
-import javax.management.MBeanRegistration;
-import javax.management.MBeanServer;
import javax.management.MBeanException;
import javax.management.AttributeNotFoundException;
import javax.management.RuntimeOperationsException;
import javax.management.ReflectionException;
import javax.management.InvalidAttributeValueException;
-import javax.management.MBeanRegistration;
import javax.management.NotificationListener;
import javax.management.Notification;
-public class LoggerDynamicMBean extends AbstractDynamicMBean
+public class LoggerDynamicMBean extends AbstractDynamicMBean
implements NotificationListener {
private MBeanConstructorInfo[] dConstructors = new MBeanConstructorInfo[1];
@@ -40,7 +36,7 @@
private Vector dAttributes = new Vector();
private String dClassName = this.getClass().getName();
- private String dDescription =
+ private String dDescription =
"This MBean acts as a management facade for a org.apache.log4j.Logger instance.";
// This Logger instance is for logging.
@@ -57,12 +53,12 @@
public
void handleNotification(Notification notification, Object handback) {
cat.debug("Received notification: "+notification.getType());
- registerAppenderMBean((Appender) notification.getUserData() );
-
+ registerAppenderMBean((Appender) notification.getUserData() );
+
}
- private
+ private
void buildDynamicMBeanInfo() {
Constructor[] constructors = this.getClass().getConstructors();
dConstructors[0] = new MBeanConstructorInfo(
@@ -74,31 +70,31 @@
"The name of this Logger.",
true,
false,
- false));
+ false));
dAttributes.add(new MBeanAttributeInfo("priority",
"java.lang.String",
"The priority of this logger.",
true,
true,
- false));
+ false));
+
-
MBeanParameterInfo[] params = new MBeanParameterInfo[2];
- params[0] = new MBeanParameterInfo("class name", "java.lang.String",
+ params[0] = new MBeanParameterInfo("class name", "java.lang.String",
"add an appender to this logger");
- params[1] = new MBeanParameterInfo("appender name", "java.lang.String",
+ params[1] = new MBeanParameterInfo("appender name", "java.lang.String",
"name of the appender");
dOperations[0] = new MBeanOperationInfo("addAppender",
"addAppender(): add an appender",
- params,
- "void",
+ params,
+ "void",
MBeanOperationInfo.ACTION);
- }
+ }
protected
Logger getLogger() {
@@ -106,7 +102,7 @@
}
- public
+ public
MBeanInfo getMBeanInfo() {
//cat.debug("getMBeanInfo called.");
@@ -123,29 +119,29 @@
return mb;
}
- public
+ public
Object invoke(String operationName, Object params[], String signature[])
throws MBeanException,
ReflectionException {
-
+
if(operationName.equals("addAppender")) {
- addAppender((String) params[0], (String) params[1]);
+ addAppender((String) params[0], (String) params[1]);
return "Hello world.";
}
return null;
}
-
- public
- Object getAttribute(String attributeName) throws AttributeNotFoundException,
- MBeanException,
+
+ public
+ Object getAttribute(String attributeName) throws AttributeNotFoundException,
+ MBeanException,
ReflectionException {
// Check attributeName is not null to avoid NullPointerException later on
if (attributeName == null) {
throw new RuntimeOperationsException(new IllegalArgumentException(
- "Attribute name cannot be null"),
+ "Attribute name cannot be null"),
"Cannot invoke a getter of " + dClassName + " with null attribute name");
}
@@ -166,10 +162,10 @@
cat.error("Could not create ObjectName" + attributeName);
}
}
-
-
+
+
// If attributeName has not been recognized throw an AttributeNotFoundException
- throw(new AttributeNotFoundException("Cannot find " + attributeName +
+ throw(new AttributeNotFoundException("Cannot find " + attributeName +
" attribute in " + dClassName));
}
@@ -177,41 +173,41 @@
void addAppender(String appenderClass, String appenderName) {
cat.debug("addAppender called with "+appenderClass+", "+appenderName);
- Appender appender = (Appender)
+ Appender appender = (Appender)
OptionConverter.instantiateByClassName(appenderClass,
org.apache.log4j.Appender.class,
null);
appender.setName(appenderName);
logger.addAppender(appender);
-
+
//appenderMBeanRegistration();
-
+
}
- public
+ public
void setAttribute(Attribute attribute) throws AttributeNotFoundException,
InvalidAttributeValueException,
- MBeanException,
+ MBeanException,
ReflectionException {
-
+
// Check attribute is not null to avoid NullPointerException later on
if (attribute == null) {
throw new RuntimeOperationsException(
- new IllegalArgumentException("Attribute cannot be null"),
- "Cannot invoke a setter of " + dClassName +
+ new IllegalArgumentException("Attribute cannot be null"),
+ "Cannot invoke a setter of " + dClassName +
" with null attribute");
}
String name = attribute.getName();
Object value = attribute.getValue();
-
+
if (name == null) {
throw new RuntimeOperationsException(
- new IllegalArgumentException("Attribute name cannot be null"),
+ new IllegalArgumentException("Attribute name cannot be null"),
"Cannot invoke the setter of "+dClassName+
" with null attribute name");
}
-
+
if(name.equals("priority")) {
if (value instanceof String) {
@@ -226,16 +222,16 @@
}
} else {
throw(new AttributeNotFoundException("Attribute " + name +
- " not found in " +
+ " not found in " +
this.getClass().getName()));
}
- }
+ }
void appenderMBeanRegistration() {
Enumeration enum = logger.getAllAppenders();
while(enum.hasMoreElements()) {
Appender appender = (Appender) enum.nextElement();
- registerAppenderMBean(appender);
+ registerAppenderMBean(appender);
}
}
@@ -247,21 +243,21 @@
AppenderDynamicMBean appenderMBean = new AppenderDynamicMBean(appender);
objectName = new ObjectName("log4j", "appender", name);
server.registerMBean(appenderMBean, objectName);
-
+
dAttributes.add(new MBeanAttributeInfo("appender="+name,
"javax.management.ObjectName",
"The "+name+" appender.",
true,
true,
false));
-
+
} catch(Exception e) {
cat.error("Could not add appenderMBean for ["+name+"].", e);
}
}
public
- void postRegister(java.lang.Boolean registrationDone) {
+ void postRegister(java.lang.Boolean registrationDone) {
appenderMBeanRegistration();
- }
+ }
}
1.3 +32 -36 jakarta-log4j/src/java/org/apache/log4j/jmx/LayoutDynamicMBean.java
Index: LayoutDynamicMBean.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/jmx/LayoutDynamicMBean.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- LayoutDynamicMBean.java 24 Sep 2001 22:43:04 -0000 1.2
+++ LayoutDynamicMBean.java 24 Apr 2002 01:16:13 -0000 1.3
@@ -8,7 +8,6 @@
package org.apache.log4j.jmx;
import java.lang.reflect.Constructor;
-import org.apache.log4j.Hierarchy;
import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import org.apache.log4j.Layout;
@@ -21,11 +20,8 @@
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanNotificationInfo;
-import javax.management.ObjectName;
import javax.management.MBeanInfo;
import javax.management.Attribute;
-import javax.management.MBeanRegistration;
-import javax.management.MBeanServer;
import javax.management.MBeanException;
import javax.management.AttributeNotFoundException;
@@ -48,7 +44,7 @@
private Hashtable dynamicProps = new Hashtable(5);
private MBeanOperationInfo[] dOperations = new MBeanOperationInfo[1];
- private String dDescription =
+ private String dDescription =
"This MBean acts as a management facade for log4j layouts.";
// This category instance is for logging.
@@ -62,7 +58,7 @@
buildDynamicMBeanInfo();
}
- private
+ private
void buildDynamicMBeanInfo() throws IntrospectionException {
Constructor[] constructors = this.getClass().getConstructors();
dConstructors[0] = new MBeanConstructorInfo(
@@ -72,7 +68,7 @@
BeanInfo bi = Introspector.getBeanInfo(layout.getClass());
PropertyDescriptor[] pd = bi.getPropertyDescriptors();
-
+
int size = pd.length;
for(int i = 0; i < size; i++) {
@@ -88,7 +84,7 @@
} else {
returnClassName = returnClass.getName();
}
-
+
dAttributes.add(new MBeanAttributeInfo(name,
returnClassName,
"Dynamic",
@@ -96,7 +92,7 @@
writeMethod != null,
false));
dynamicProps.put(name, new MethodUnion(readMethod, writeMethod));
- }
+ }
}
}
@@ -104,8 +100,8 @@
dOperations[0] = new MBeanOperationInfo("activateOptions",
"activateOptions(): add an layout",
- params,
- "void",
+ params,
+ "void",
MBeanOperationInfo.ACTION);
}
@@ -121,13 +117,13 @@
if(clazz.isAssignableFrom(Level.class)) {
return true;
}
-
+
return false;
}
- public
+ public
MBeanInfo getMBeanInfo() {
cat.debug("getMBeanInfo called.");
@@ -142,12 +138,12 @@
new MBeanNotificationInfo[0]);
}
- public
+ public
Object invoke(String operationName, Object params[], String signature[])
throws MBeanException,
ReflectionException {
-
- if(operationName.equals("activateOptions") &&
+
+ if(operationName.equals("activateOptions") &&
layout instanceof OptionHandler) {
OptionHandler oh = (OptionHandler) layout;
oh.activateOptions();
@@ -160,21 +156,21 @@
Logger getLogger() {
return cat;
}
-
- public
- Object getAttribute(String attributeName) throws AttributeNotFoundException,
- MBeanException,
+
+ public
+ Object getAttribute(String attributeName) throws AttributeNotFoundException,
+ MBeanException,
ReflectionException {
// Check attributeName is not null to avoid NullPointerException later on
if (attributeName == null) {
throw new RuntimeOperationsException(new IllegalArgumentException(
- "Attribute name cannot be null"),
+ "Attribute name cannot be null"),
"Cannot invoke a getter of " + dClassName + " with null attribute name");
}
-
+
MethodUnion mu = (MethodUnion) dynamicProps.get(attributeName);
cat.debug("----name="+attributeName+", mu="+mu);
@@ -190,37 +186,37 @@
// If attributeName has not been recognized throw an AttributeNotFoundException
- throw(new AttributeNotFoundException("Cannot find " + attributeName +
+ throw(new AttributeNotFoundException("Cannot find " + attributeName +
" attribute in " + dClassName));
}
- public
+ public
void setAttribute(Attribute attribute) throws AttributeNotFoundException,
InvalidAttributeValueException,
- MBeanException,
+ MBeanException,
ReflectionException {
-
+
// Check attribute is not null to avoid NullPointerException later on
if (attribute == null) {
throw new RuntimeOperationsException(
- new IllegalArgumentException("Attribute cannot be null"),
- "Cannot invoke a setter of " + dClassName +
+ new IllegalArgumentException("Attribute cannot be null"),
+ "Cannot invoke a setter of " + dClassName +
" with null attribute");
}
String name = attribute.getName();
Object value = attribute.getValue();
-
+
if (name == null) {
throw new RuntimeOperationsException(
- new IllegalArgumentException("Attribute name cannot be null"),
+ new IllegalArgumentException("Attribute name cannot be null"),
"Cannot invoke the setter of "+dClassName+
" with null attribute name");
}
-
-
+
+
MethodUnion mu = (MethodUnion) dynamicProps.get(name);
if(mu != null && mu.writeMethod != null) {
@@ -228,23 +224,23 @@
Class[] params = mu.writeMethod.getParameterTypes();
if(params[0] == org.apache.log4j.Priority.class) {
- value = OptionConverter.toLevel((String) value,
+ value = OptionConverter.toLevel((String) value,
(Level) getAttribute(name));
}
o[0] = value;
try {
mu.writeMethod.invoke(layout, o);
-
+
} catch(Exception e) {
cat.error("FIXME", e);
}
} else {
throw(new AttributeNotFoundException("Attribute " + name +
- " not found in " +
+ " not found in " +
this.getClass().getName()));
}
- }
+ }
}
1.5 +44 -45 jakarta-log4j/src/java/org/apache/log4j/jmx/HierarchyDynamicMBean.java
Index: HierarchyDynamicMBean.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/jmx/HierarchyDynamicMBean.java,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -r1.4 -r1.5
--- HierarchyDynamicMBean.java 11 Feb 2002 16:14:34 -0000 1.4
+++ HierarchyDynamicMBean.java 24 Apr 2002 01:16:13 -0000 1.5
@@ -25,7 +25,6 @@
import javax.management.ObjectName;
import javax.management.MBeanInfo;
import javax.management.Attribute;
-import javax.management.MBeanServer;
import javax.management.MBeanException;
import javax.management.AttributeNotFoundException;
@@ -40,26 +39,26 @@
import javax.management.NotificationFilterSupport;
import javax.management.ListenerNotFoundException;
-public class HierarchyDynamicMBean extends AbstractDynamicMBean
+public class HierarchyDynamicMBean extends AbstractDynamicMBean
implements HierarchyEventListener,
NotificationBroadcaster {
-
- static final String ADD_APPENDER = "addAppender.";
- static final String THRESHOLD = "threshold";
+
+ static final String ADD_APPENDER = "addAppender.";
+ static final String THRESHOLD = "threshold";
private MBeanConstructorInfo[] dConstructors = new MBeanConstructorInfo[1];
private MBeanOperationInfo[] dOperations = new MBeanOperationInfo[1];
private Vector vAttributes = new Vector();
private String dClassName = this.getClass().getName();
- private String dDescription =
+ private String dDescription =
"This MBean acts as a management facade for org.apache.log4j.Hierarchy.";
private NotificationBroadcasterSupport nbs = new NotificationBroadcasterSupport();
private LoggerRepository hierarchy;
-
+
private static Logger log = Logger.getLogger(HierarchyDynamicMBean.class);
public HierarchyDynamicMBean() {
@@ -67,7 +66,7 @@
buildDynamicMBeanInfo();
}
- private
+ private
void buildDynamicMBeanInfo() {
Constructor[] constructors = this.getClass().getConstructors();
dConstructors[0] = new MBeanConstructorInfo(
@@ -82,20 +81,20 @@
false));
MBeanParameterInfo[] params = new MBeanParameterInfo[1];
- params[0] = new MBeanParameterInfo("name", "java.lang.String",
+ params[0] = new MBeanParameterInfo("name", "java.lang.String",
"Create a logger MBean" );
dOperations[0] = new MBeanOperationInfo("addLoggerMBean",
"addLoggerMBean(): add a loggerMBean",
- params ,
- "javax.management.ObjectName",
+ params ,
+ "javax.management.ObjectName",
MBeanOperationInfo.ACTION);
- }
+ }
- public
+ public
ObjectName addLoggerMBean(String name) {
Logger cat = Logger.exists(name);
-
+
if(cat != null) {
return addLoggerMBean(cat);
} else {
@@ -110,14 +109,14 @@
LoggerDynamicMBean loggerMBean = new LoggerDynamicMBean(logger);
objectName = new ObjectName("log4j", "logger", name);
server.registerMBean(loggerMBean, objectName);
-
+
NotificationFilterSupport nfs = new NotificationFilterSupport();
nfs.enableType(ADD_APPENDER+logger.getName());
log.debug("---Adding logger ["+name+"] as listener.");
nbs.addNotificationListener(loggerMBean, nfs, null);
-
+
vAttributes.add(new MBeanAttributeInfo("logger="+name,
"javax.management.ObjectName",
@@ -126,7 +125,7 @@
true, // this makes the object
// clickable
false));
-
+
} catch(Exception e) {
log.error("Couls not add loggerMBean for ["+name+"].");
}
@@ -134,8 +133,8 @@
}
public
- void addNotificationListener(NotificationListener listener,
- NotificationFilter filter,
+ void addNotificationListener(NotificationListener listener,
+ NotificationFilter filter,
java.lang.Object handback) {
nbs.addNotificationListener(listener, filter, handback);
}
@@ -145,7 +144,7 @@
return log;
}
- public
+ public
MBeanInfo getMBeanInfo() {
//cat.debug("getMBeanInfo called.");
@@ -165,44 +164,44 @@
return nbs.getNotificationInfo();
}
- public
- Object invoke(String operationName,
- Object params[],
- String signature[]) throws MBeanException,
+ public
+ Object invoke(String operationName,
+ Object params[],
+ String signature[]) throws MBeanException,
ReflectionException {
if (operationName == null) {
throw new RuntimeOperationsException(
- new IllegalArgumentException("Operation name cannot be null"),
+ new IllegalArgumentException("Operation name cannot be null"),
"Cannot invoke a null operation in " + dClassName);
}
// Check for a recognized operation name and call the corresponding operation
if(operationName.equals("addLoggerMBean")) {
return addLoggerMBean((String)params[0]);
- } else {
+ } else {
throw new ReflectionException(
- new NoSuchMethodException(operationName),
+ new NoSuchMethodException(operationName),
"Cannot find the operation " + operationName + " in " + dClassName);
}
}
-
- public
- Object getAttribute(String attributeName) throws AttributeNotFoundException,
- MBeanException,
+
+ public
+ Object getAttribute(String attributeName) throws AttributeNotFoundException,
+ MBeanException,
ReflectionException {
// Check attributeName is not null to avoid NullPointerException later on
if (attributeName == null) {
throw new RuntimeOperationsException(new IllegalArgumentException(
- "Attribute name cannot be null"),
+ "Attribute name cannot be null"),
"Cannot invoke a getter of " + dClassName + " with null attribute name");
}
log.debug("Called getAttribute with ["+attributeName+"].");
-
+
// Check for a recognized attributeName and call the corresponding getter
if (attributeName.equals(THRESHOLD)) {
return hierarchy.getThreshold();
@@ -222,7 +221,7 @@
// If attributeName has not been recognized throw an AttributeNotFoundException
- throw(new AttributeNotFoundException("Cannot find " + attributeName +
+ throw(new AttributeNotFoundException("Cannot find " + attributeName +
" attribute in " + dClassName));
}
@@ -253,21 +252,21 @@
}
public
- void removeNotificationListener(NotificationListener listener)
+ void removeNotificationListener(NotificationListener listener)
throws ListenerNotFoundException {
nbs.removeNotificationListener(listener);
}
-
- public
+
+ public
void setAttribute(Attribute attribute) throws AttributeNotFoundException,
InvalidAttributeValueException,
- MBeanException,
+ MBeanException,
ReflectionException {
-
+
// Check attribute is not null to avoid NullPointerException later on
if (attribute == null) {
throw new RuntimeOperationsException(
- new IllegalArgumentException("Attribute cannot be null"),
+ new IllegalArgumentException("Attribute cannot be null"),
"Cannot invoke a setter of "+dClassName+" with null attribute");
}
String name = attribute.getName();
@@ -275,17 +274,17 @@
if (name == null) {
throw new RuntimeOperationsException(
- new IllegalArgumentException("Attribute name cannot be null"),
+ new IllegalArgumentException("Attribute name cannot be null"),
"Cannot invoke the setter of "+dClassName+
" with null attribute name");
}
if(name.equals(THRESHOLD)) {
- Level l = OptionConverter.toLevel((String) value,
+ Level l = OptionConverter.toLevel((String) value,
hierarchy.getThreshold());
hierarchy.setThreshold(l);
}
-
-
- }
+
+
+ }
}
1.3 +40 -41 jakarta-log4j/src/java/org/apache/log4j/jmx/AppenderDynamicMBean.java
Index: AppenderDynamicMBean.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/jmx/AppenderDynamicMBean.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- AppenderDynamicMBean.java 24 Sep 2001 22:43:04 -0000 1.2
+++ AppenderDynamicMBean.java 24 Apr 2002 01:16:13 -0000 1.3
@@ -21,7 +21,6 @@
import javax.management.ObjectName;
import javax.management.MBeanInfo;
import javax.management.Attribute;
-import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.MBeanException;
@@ -45,7 +44,7 @@
private Hashtable dynamicProps = new Hashtable(5);
private MBeanOperationInfo[] dOperations = new MBeanOperationInfo[2];
- private String dDescription =
+ private String dDescription =
"This MBean acts as a management facade for log4j appenders.";
// This category instance is for logging.
@@ -59,7 +58,7 @@
buildDynamicMBeanInfo();
}
- private
+ private
void buildDynamicMBeanInfo() throws IntrospectionException {
Constructor[] constructors = this.getClass().getConstructors();
dConstructors[0] = new MBeanConstructorInfo(
@@ -69,7 +68,7 @@
BeanInfo bi = Introspector.getBeanInfo(appender.getClass());
PropertyDescriptor[] pd = bi.getPropertyDescriptors();
-
+
int size = pd.length;
for(int i = 0; i < size; i++) {
@@ -85,7 +84,7 @@
} else {
returnClassName = returnClass.getName();
}
-
+
dAttributes.add(new MBeanAttributeInfo(name,
returnClassName,
"Dynamic",
@@ -93,7 +92,7 @@
writeMethod != null,
false));
dynamicProps.put(name, new MethodUnion(readMethod, writeMethod));
- }
+ }
}
}
@@ -101,18 +100,18 @@
dOperations[0] = new MBeanOperationInfo("activateOptions",
"activateOptions(): add an appender",
- params,
- "void",
+ params,
+ "void",
MBeanOperationInfo.ACTION);
params = new MBeanParameterInfo[1];
- params[0] = new MBeanParameterInfo("layout class", "java.lang.String",
+ params[0] = new MBeanParameterInfo("layout class", "java.lang.String",
"layout class");
dOperations[1] = new MBeanOperationInfo("setLayout",
"setLayout(): add a layout",
- params,
- "void",
+ params,
+ "void",
MBeanOperationInfo.ACTION);
}
@@ -130,15 +129,15 @@
if(clazz.isAssignableFrom(Priority.class)) {
return true;
}
-
+
return false;
-
+
}
- public
+ public
MBeanInfo getMBeanInfo() {
cat.debug("getMBeanInfo called.");
@@ -153,12 +152,12 @@
new MBeanNotificationInfo[0]);
}
- public
+ public
Object invoke(String operationName, Object params[], String signature[])
throws MBeanException,
ReflectionException {
-
- if(operationName.equals("activateOptions") &&
+
+ if(operationName.equals("activateOptions") &&
appender instanceof OptionHandler) {
OptionHandler oh = (OptionHandler) appender;
oh.activateOptions();
@@ -185,14 +184,14 @@
LayoutDynamicMBean appenderMBean = new LayoutDynamicMBean(layout);
objectName = new ObjectName("log4j:appender="+name);
server.registerMBean(appenderMBean, objectName);
-
+
dAttributes.add(new MBeanAttributeInfo("appender="+name,
"javax.management.ObjectName",
"The "+name+" layout.",
true,
true,
false));
-
+
} catch(Exception e) {
cat.error("Could not add DynamicLayoutMBean for ["+name+"].", e);
}
@@ -202,20 +201,20 @@
Logger getLogger() {
return cat;
}
-
- public
- Object getAttribute(String attributeName) throws AttributeNotFoundException,
- MBeanException,
+
+ public
+ Object getAttribute(String attributeName) throws AttributeNotFoundException,
+ MBeanException,
ReflectionException {
// Check attributeName is not null to avoid NullPointerException later on
if (attributeName == null) {
throw new RuntimeOperationsException(new IllegalArgumentException(
- "Attribute name cannot be null"),
+ "Attribute name cannot be null"),
"Cannot invoke a getter of " + dClassName + " with null attribute name");
}
-
+
cat.debug("getAttribute called with ["+attributeName+"].");
if(attributeName.startsWith("appender="+appender.getName()+",layout")) {
try {
@@ -240,37 +239,37 @@
// If attributeName has not been recognized throw an AttributeNotFoundException
- throw(new AttributeNotFoundException("Cannot find " + attributeName +
+ throw(new AttributeNotFoundException("Cannot find " + attributeName +
" attribute in " + dClassName));
}
- public
+ public
void setAttribute(Attribute attribute) throws AttributeNotFoundException,
InvalidAttributeValueException,
- MBeanException,
+ MBeanException,
ReflectionException {
-
+
// Check attribute is not null to avoid NullPointerException later on
if (attribute == null) {
throw new RuntimeOperationsException(
- new IllegalArgumentException("Attribute cannot be null"),
- "Cannot invoke a setter of " + dClassName +
+ new IllegalArgumentException("Attribute cannot be null"),
+ "Cannot invoke a setter of " + dClassName +
" with null attribute");
}
String name = attribute.getName();
Object value = attribute.getValue();
-
+
if (name == null) {
throw new RuntimeOperationsException(
- new IllegalArgumentException("Attribute name cannot be null"),
+ new IllegalArgumentException("Attribute name cannot be null"),
"Cannot invoke the setter of "+dClassName+
" with null attribute name");
}
-
-
+
+
MethodUnion mu = (MethodUnion) dynamicProps.get(name);
if(mu != null && mu.writeMethod != null) {
@@ -278,27 +277,27 @@
Class[] params = mu.writeMethod.getParameterTypes();
if(params[0] == org.apache.log4j.Priority.class) {
- value = OptionConverter.toLevel((String) value,
+ value = OptionConverter.toLevel((String) value,
(Level) getAttribute(name));
}
o[0] = value;
try {
mu.writeMethod.invoke(appender, o);
-
+
} catch(Exception e) {
cat.error("FIXME", e);
}
} else if(name.endsWith(".layout")) {
-
+
} else {
throw(new AttributeNotFoundException("Attribute " + name +
- " not found in " +
+ " not found in " +
this.getClass().getName()));
}
- }
+ }
- public
+ public
ObjectName preRegister(MBeanServer server, ObjectName name) {
cat.debug("preRegister called. Server="+server+ ", name="+name);
this.server = server;
1.2 +9 -10 jakarta-log4j/src/java/org/apache/log4j/jmx/Agent.java
Index: Agent.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/jmx/Agent.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- Agent.java 24 Sep 2001 22:16:27 -0000 1.1
+++ Agent.java 24 Apr 2002 01:16:13 -0000 1.2
@@ -4,7 +4,6 @@
import javax.management.ObjectName;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
-import javax.management.MalformedObjectNameException;
import com.sun.jdmk.comm.HtmlAdaptorServer;
import org.apache.log4j.Category;
@@ -13,15 +12,15 @@
public class Agent {
static Category log = Category.getInstance(Agent.class);
-
- public Agent() {
+
+ public Agent() {
}
-
- public
+
+ public
void start() {
-
- MBeanServer server = MBeanServerFactory.createMBeanServer();
+
+ MBeanServer server = MBeanServerFactory.createMBeanServer();
HtmlAdaptorServer html = new HtmlAdaptorServer();
try {
@@ -30,11 +29,11 @@
log.info("Registering HierarchyDynamicMBean instance.");
HierarchyDynamicMBean hdm = new HierarchyDynamicMBean();
server.registerMBean(hdm, new ObjectName("log4j:hiearchy=default"));
-
+
} catch(Exception e) {
log.error("Problem while regitering MBeans instances.", e);
return;
}
- html.start();
- }
+ html.start();
+ }
}
1.3 +15 -16 jakarta-log4j/src/java/org/apache/log4j/jmx/AbstractDynamicMBean.java
Index: AbstractDynamicMBean.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/jmx/AbstractDynamicMBean.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- AbstractDynamicMBean.java 24 Sep 2001 22:43:04 -0000 1.2
+++ AbstractDynamicMBean.java 24 Apr 2002 01:16:13 -0000 1.3
@@ -16,11 +16,10 @@
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.ObjectName;
-import javax.management.NotificationBroadcasterSupport;
import org.apache.log4j.Logger;
-public abstract class AbstractDynamicMBean implements DynamicMBean,
+public abstract class AbstractDynamicMBean implements DynamicMBean,
MBeanRegistration {
String dClassName;
@@ -29,9 +28,9 @@
/**
* Enables the to get the values of several attributes of the Dynamic MBean.
*/
- public
+ public
AttributeList getAttributes(String[] attributeNames) {
-
+
// Check attributeNames is not null to avoid NullPointerException later on
if (attributeNames == null) {
throw new RuntimeOperationsException(
@@ -40,15 +39,15 @@
}
AttributeList resultList = new AttributeList();
-
+
// if attributeNames is empty, return an empty result list
if (attributeNames.length == 0)
return resultList;
-
+
// build the result attribute list
for (int i=0 ; i<attributeNames.length ; i++){
- try {
- Object value = getAttribute((String) attributeNames[i]);
+ try {
+ Object value = getAttribute((String) attributeNames[i]);
resultList.add(new Attribute(attributeNames[i],value));
} catch (Exception e) {
e.printStackTrace();
@@ -62,7 +61,7 @@
* list of attributes that have been set.
*/
public AttributeList setAttributes(AttributeList attributes) {
-
+
// Check attributes is not null to avoid NullPointerException later on
if (attributes == null) {
throw new RuntimeOperationsException(
@@ -70,18 +69,18 @@
"Cannot invoke a setter of " + dClassName);
}
AttributeList resultList = new AttributeList();
-
+
// if attributeNames is empty, nothing more to do
if (attributes.isEmpty())
return resultList;
-
+
// for each attribute, try to set it and add to the result list if successfull
for (Iterator i = attributes.iterator(); i.hasNext();) {
Attribute attr = (Attribute) i.next();
try {
setAttribute(attr);
String name = attr.getName();
- Object value = getAttribute(name);
+ Object value = getAttribute(name);
resultList.add(new Attribute(name,value));
} catch(Exception e) {
e.printStackTrace();
@@ -93,7 +92,7 @@
protected
abstract
Logger getLogger();
-
+
public
void postDeregister() {
getLogger().debug("postDeregister is called.");
@@ -104,13 +103,13 @@
}
-
- public
+
+ public
void preDeregister() {
getLogger().debug("preDeregister called.");
}
- public
+ public
ObjectName preRegister(MBeanServer server, ObjectName name) {
getLogger().debug("preRegister called. Server="+server+ ", name="+name);
this.server = server;
1.5 +10 -12 jakarta-log4j/src/java/org/apache/log4j/jdbc/JDBCAppender.java
Index: JDBCAppender.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/jdbc/JDBCAppender.java,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -r1.4 -r1.5
--- JDBCAppender.java 4 Apr 2002 14:46:02 -0000 1.4
+++ JDBCAppender.java 24 Apr 2002 01:16:13 -0000 1.5
@@ -3,9 +3,7 @@
import org.apache.log4j.*;
import org.apache.log4j.spi.*;
import org.apache.log4j.PatternLayout;
-import org.apache.log4j.helpers.OptionConverter;
-import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
@@ -17,28 +15,28 @@
/**
The JDBCAppender provides for sending log events to a database.
-
+
<p>Each append call adds to an <code>ArrayList</code> buffer. When
the buffer is filled each log event is placed in a sql statement
(configurable) and executed.
-
+
<b>BufferSize</b>, <b>db URL</b>, <b>User</b>, & <b>Password</b> are
configurable options in the standard log4j ways.
-
+
<p>The <code>setSql(String sql)</code> sets the SQL statement to be
used for logging -- this statement is sent to a
<code>PatternLayout</code> (either created automaticly by the
appender or added by the user). Therefore by default all the
conversion patterns in <code>PatternLayout</code> can be used
inside of the statement. (see the test cases for examples)
-
+
<p>Overriding the {@link #getLogStatement} method allows more
explicit control of the statement used for logging.
-
+
<p>For use as a base class:
-
+
<ul>
-
+
<li>Override <code>getConnection()</code> to pass any connection
you want. Typically this is used to enable application wide
connection pooling.
@@ -48,14 +46,14 @@
<code>closeConnection</code> to handle the connection you
generated. Typically this would return the connection to the
pool it came from.
-
+
<li>Override <code>getLogStatement(LoggingEvent event)</code> to
produce specialized or dynamic statements. The default uses the
sql option value.
</ul>
-
- @author: Kevin Steppe (<A HREF="mailto:[email protected]">[email protected]</A>)
+
+ @author: Kevin Steppe (<A HREF="mailto:[email protected]">[email protected]</A>)
*/
public class JDBCAppender extends org.apache.log4j.AppenderSkeleton
1.5 +1 -3 jakarta-log4j/src/java/org/apache/log4j/helpers/SyslogQuietWriter.java
Index: SyslogQuietWriter.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/helpers/SyslogQuietWriter.java,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -r1.4 -r1.5
--- SyslogQuietWriter.java 2 Sep 2001 20:05:39 -0000 1.4
+++ SyslogQuietWriter.java 24 Apr 2002 01:16:13 -0000 1.5
@@ -11,8 +11,6 @@
import java.io.Writer;
-import java.io.FilterWriter;
-import java.io.IOException;
import org.apache.log4j.spi.ErrorHandler;
/**
@@ -41,7 +39,7 @@
void setSyslogFacility(int syslogFacility) {
this.syslogFacility = syslogFacility;
}
-
+
public
void write(String string) {
super.write("<"+(syslogFacility | level)+">" + string);
1.17 +72 -75 jakarta-log4j/src/java/org/apache/log4j/helpers/PatternParser.java
Index: PatternParser.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/helpers/PatternParser.java,v
retrieving revision 1.16
retrieving revision 1.17
diff -u -r1.16 -r1.17
--- PatternParser.java 21 Jan 2002 23:07:11 -0000 1.16
+++ PatternParser.java 24 Apr 2002 01:16:13 -0000 1.17
@@ -11,18 +11,15 @@
import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.helpers.AbsoluteTimeDateFormat;
import org.apache.log4j.Layout;
-import org.apache.log4j.NDC;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.LocationInfo;
-import org.apache.log4j.or.ObjectRenderer;
-import org.apache.log4j.or.RendererMap;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
// Contributors: Nelson Minar <([email protected]>
-// Igor E. Poteryaev <[email protected]>
-// Reinhard Deschler <[email protected]>
+// Igor E. Poteryaev <[email protected]>
+// Reinhard Deschler <[email protected]>
/**
Most of the work of the {@link org.apache.log4j.PatternLayout} class
@@ -30,17 +27,17 @@
<p>It is this class that parses conversion patterns and creates
a chained list of {@link OptionConverter OptionConverters}.
-
+
@author <a href=mailto:"[email protected]">James P. Cakalic</a>
@author Ceki Gülcü
- @author Anders Kristensen
+ @author Anders Kristensen
@since 0.8.2
*/
public class PatternParser {
private static final char ESCAPE_CHAR = '%';
-
+
private static final int LITERAL_STATE = 0;
private static final int CONVERTER_STATE = 1;
private static final int MINUS_STATE = 2;
@@ -52,7 +49,7 @@
static final int METHOD_LOCATION_CONVERTER = 1001;
static final int CLASS_LOCATION_CONVERTER = 1002;
static final int LINE_LOCATION_CONVERTER = 1003;
- static final int FILE_LOCATION_CONVERTER = 1004;
+ static final int FILE_LOCATION_CONVERTER = 1004;
static final int RELATIVE_TIME_CONVERTER = 2000;
static final int THREAD_CONVERTER = 2001;
@@ -72,7 +69,7 @@
public
PatternParser(String pattern) {
this.pattern = pattern;
- patternLength = pattern.length();
+ patternLength = pattern.length();
state = LITERAL_STATE;
}
@@ -82,14 +79,14 @@
head = tail = pc;
} else {
tail.next = pc;
- tail = pc;
+ tail = pc;
}
}
protected
String extractOption() {
if((i < patternLength) && (pattern.charAt(i) == '{')) {
- int end = pattern.indexOf('}', i);
+ int end = pattern.indexOf('}', i);
if (end > i) {
String r = pattern.substring(i + 1, end);
i = end+1;
@@ -115,29 +112,29 @@
"Precision option (" + opt + ") isn't a positive integer.");
r = 0;
}
- }
+ }
catch (NumberFormatException e) {
LogLog.error("Category option \""+opt+"\" not a decimal integer.", e);
- }
+ }
}
- return r;
+ return r;
}
-
- public
+
+ public
PatternConverter parse() {
char c;
i = 0;
while(i < patternLength) {
c = pattern.charAt(i++);
switch(state) {
- case LITERAL_STATE:
+ case LITERAL_STATE:
// In literal state, the last char is always a literal.
if(i == patternLength) {
currentLiteral.append(c);
continue;
}
- if(c == ESCAPE_CHAR) {
- // peek at the next char.
+ if(c == ESCAPE_CHAR) {
+ // peek at the next char.
switch(pattern.charAt(i)) {
case ESCAPE_CHAR:
currentLiteral.append(c);
@@ -151,10 +148,10 @@
if(currentLiteral.length() != 0) {
addToList(new LiteralPatternConverter(
currentLiteral.toString()));
- //LogLog.debug("Parsed LITERAL converter: \""
+ //LogLog.debug("Parsed LITERAL converter: \""
// +currentLiteral+"\".");
}
- currentLiteral.setLength(0);
+ currentLiteral.setLength(0);
currentLiteral.append(c); // append %
state = CONVERTER_STATE;
formattingInfo.reset();
@@ -178,13 +175,13 @@
formattingInfo.min = c - '0';
state = MIN_STATE;
}
- else
- finalizeConverter(c);
+ else
+ finalizeConverter(c);
} // switch
break;
case MIN_STATE:
currentLiteral.append(c);
- if(c >= '0' && c <= '9')
+ if(c >= '0' && c <= '9')
formattingInfo.min = formattingInfo.min*10 + (c - '0');
else if(c == '.')
state = DOT_STATE;
@@ -206,7 +203,7 @@
break;
case MAX_STATE:
currentLiteral.append(c);
- if(c >= '0' && c <= '9')
+ if(c >= '0' && c <= '9')
formattingInfo.max = formattingInfo.max*10 + (c - '0');
else {
finalizeConverter(c);
@@ -228,16 +225,16 @@
switch(c) {
case 'c':
pc = new CategoryPatternConverter(formattingInfo,
- extractPrecisionOption());
+ extractPrecisionOption());
//LogLog.debug("CATEGORY converter.");
- //formattingInfo.dump();
+ //formattingInfo.dump();
currentLiteral.setLength(0);
- break;
+ break;
case 'C':
pc = new ClassNamePatternConverter(formattingInfo,
extractPrecisionOption());
//LogLog.debug("CLASS_NAME converter.");
- //formattingInfo.dump();
+ //formattingInfo.dump();
currentLiteral.setLength(0);
break;
case 'd':
@@ -246,9 +243,9 @@
String dOpt = extractOption();
if(dOpt != null)
dateFormatStr = dOpt;
-
+
if(dateFormatStr.equalsIgnoreCase(
- AbsoluteTimeDateFormat.ISO8601_DATE_FORMAT))
+ AbsoluteTimeDateFormat.ISO8601_DATE_FORMAT))
df = new ISO8601DateFormat();
else if(dateFormatStr.equalsIgnoreCase(
AbsoluteTimeDateFormat.ABS_TIME_DATE_FORMAT))
@@ -266,45 +263,45 @@
df = (DateFormat) OptionConverter.instantiateByClassName(
"org.apache.log4j.helpers.ISO8601DateFormat",
DateFormat.class, null);
- }
+ }
}
pc = new DatePatternConverter(formattingInfo, df);
//LogLog.debug("DATE converter {"+dateFormatStr+"}.");
- //formattingInfo.dump();
+ //formattingInfo.dump();
currentLiteral.setLength(0);
break;
case 'F':
pc = new LocationPatternConverter(formattingInfo,
FILE_LOCATION_CONVERTER);
//LogLog.debug("File name converter.");
- //formattingInfo.dump();
+ //formattingInfo.dump();
currentLiteral.setLength(0);
break;
case 'l':
pc = new LocationPatternConverter(formattingInfo,
FULL_LOCATION_CONVERTER);
//LogLog.debug("Location converter.");
- //formattingInfo.dump();
+ //formattingInfo.dump();
currentLiteral.setLength(0);
break;
case 'L':
pc = new LocationPatternConverter(formattingInfo,
LINE_LOCATION_CONVERTER);
//LogLog.debug("LINE NUMBER converter.");
- //formattingInfo.dump();
+ //formattingInfo.dump();
currentLiteral.setLength(0);
break;
case 'm':
pc = new BasicPatternConverter(formattingInfo, MESSAGE_CONVERTER);
//LogLog.debug("MESSAGE converter.");
- //formattingInfo.dump();
+ //formattingInfo.dump();
currentLiteral.setLength(0);
break;
case 'M':
pc = new LocationPatternConverter(formattingInfo,
METHOD_LOCATION_CONVERTER);
//LogLog.debug("METHOD converter.");
- //formattingInfo.dump();
+ //formattingInfo.dump();
currentLiteral.setLength(0);
break;
case 'p':
@@ -314,7 +311,7 @@
currentLiteral.setLength(0);
break;
case 'r':
- pc = new BasicPatternConverter(formattingInfo,
+ pc = new BasicPatternConverter(formattingInfo,
RELATIVE_TIME_CONVERTER);
//LogLog.debug("RELATIVE time converter.");
//formattingInfo.dump();
@@ -323,7 +320,7 @@
case 't':
pc = new BasicPatternConverter(formattingInfo, THREAD_CONVERTER);
//LogLog.debug("THREAD converter.");
- //formattingInfo.dump();
+ //formattingInfo.dump();
currentLiteral.setLength(0);
break;
/*case 'u':
@@ -332,17 +329,17 @@
if(cNext >= '0' && cNext <= '9') {
pc = new UserFieldPatternConverter(formattingInfo, cNext - '0');
LogLog.debug("USER converter ["+cNext+"].");
- formattingInfo.dump();
+ formattingInfo.dump();
currentLiteral.setLength(0);
i++;
}
- else
+ else
LogLog.error("Unexpected char" +cNext+" at position "+i);
}
break;*/
case 'x':
pc = new BasicPatternConverter(formattingInfo, NDC_CONVERTER);
- //LogLog.debug("NDC converter.");
+ //LogLog.debug("NDC converter.");
currentLiteral.setLength(0);
break;
case 'X':
@@ -356,7 +353,7 @@
pc = new LiteralPatternConverter(currentLiteral.toString());
currentLiteral.setLength(0);
}
-
+
addConverter(pc);
}
@@ -374,25 +371,25 @@
// ---------------------------------------------------------------------
// PatternConverters
// ---------------------------------------------------------------------
-
+
private static class BasicPatternConverter extends PatternConverter {
int type;
-
+
BasicPatternConverter(FormattingInfo formattingInfo, int type) {
- super(formattingInfo);
+ super(formattingInfo);
this.type = type;
}
public
String convert(LoggingEvent event) {
switch(type) {
- case RELATIVE_TIME_CONVERTER:
+ case RELATIVE_TIME_CONVERTER:
return (Long.toString(event.timeStamp - LoggingEvent.getStartTime()));
case THREAD_CONVERTER:
return event.getThreadName();
case LEVEL_CONVERTER:
return event.level.toString();
- case NDC_CONVERTER:
+ case NDC_CONVERTER:
return event.getNDC();
case MESSAGE_CONVERTER: {
return event.getRenderedMessage();
@@ -401,10 +398,10 @@
}
}
}
-
+
private static class LiteralPatternConverter extends PatternConverter {
private String literal;
-
+
LiteralPatternConverter(String value) {
literal = value;
}
@@ -414,8 +411,8 @@
void format(StringBuffer sbuf, LoggingEvent event) {
sbuf.append(literal);
}
-
- public
+
+ public
String convert(LoggingEvent event) {
return literal;
}
@@ -424,11 +421,11 @@
private static class DatePatternConverter extends PatternConverter {
private DateFormat df;
private Date date;
-
+
DatePatternConverter(FormattingInfo formattingInfo, DateFormat df) {
super(formattingInfo);
date = new Date();
- this.df = df;
+ this.df = df;
}
public
@@ -447,7 +444,7 @@
private static class MDCPatternConverter extends PatternConverter {
private String key;
-
+
MDCPatternConverter(FormattingInfo formattingInfo, String key) {
super(formattingInfo);
this.key = key;
@@ -459,7 +456,7 @@
if(val == null) {
return null;
} else {
- return val.toString();
+ return val.toString();
}
}
}
@@ -467,23 +464,23 @@
private class LocationPatternConverter extends PatternConverter {
int type;
-
+
LocationPatternConverter(FormattingInfo formattingInfo, int type) {
super(formattingInfo);
this.type = type;
}
-
+
public
String convert(LoggingEvent event) {
LocationInfo locationInfo = event.getLocationInformation();
switch(type) {
- case FULL_LOCATION_CONVERTER:
+ case FULL_LOCATION_CONVERTER:
return locationInfo.fullInfo;
- case METHOD_LOCATION_CONVERTER:
+ case METHOD_LOCATION_CONVERTER:
return locationInfo.getMethodName();
- case LINE_LOCATION_CONVERTER:
+ case LINE_LOCATION_CONVERTER:
return locationInfo.getLineNumber();
- case FILE_LOCATION_CONVERTER:
+ case FILE_LOCATION_CONVERTER:
return locationInfo.getFileName();
default: return null;
}
@@ -492,15 +489,15 @@
private static abstract class NamedPatternConverter extends PatternConverter {
int precision;
-
+
NamedPatternConverter(FormattingInfo formattingInfo, int precision) {
super(formattingInfo);
- this.precision = precision;
+ this.precision = precision;
}
abstract
String getFullyQualifiedName(LoggingEvent event);
-
+
public
String convert(LoggingEvent event) {
String n = getFullyQualifiedName(event);
@@ -511,38 +508,38 @@
// We substract 1 from 'len' when assigning to 'end' to avoid out of
// bounds exception in return r.substring(end+1, len). This can happen if
- // precision is 1 and the category name ends with a dot.
+ // precision is 1 and the category name ends with a dot.
int end = len -1 ;
- for(int i = precision; i > 0; i--) {
+ for(int i = precision; i > 0; i--) {
end = n.lastIndexOf('.', end-1);
if(end == -1)
return n;
}
return n.substring(end+1, len);
- }
+ }
}
}
-
+
private class ClassNamePatternConverter extends NamedPatternConverter {
ClassNamePatternConverter(FormattingInfo formattingInfo, int precision) {
super(formattingInfo, precision);
}
-
+
String getFullyQualifiedName(LoggingEvent event) {
return event.getLocationInformation().getClassName();
}
}
-
+
private class CategoryPatternConverter extends NamedPatternConverter {
CategoryPatternConverter(FormattingInfo formattingInfo, int precision) {
super(formattingInfo, precision);
}
-
+
String getFullyQualifiedName(LoggingEvent event) {
return event.categoryName;
}
- }
+ }
}
1.34 +42 -44 jakarta-log4j/src/java/org/apache/log4j/helpers/OptionConverter.java
Index: OptionConverter.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/helpers/OptionConverter.java,v
retrieving revision 1.33
retrieving revision 1.34
diff -u -r1.33 -r1.34
--- OptionConverter.java 22 Feb 2002 10:39:55 -0000 1.33
+++ OptionConverter.java 24 Apr 2002 01:16:13 -0000 1.34
@@ -10,8 +10,6 @@
import java.util.Properties;
import java.net.URL;
-import org.apache.log4j.Category;
-import org.apache.log4j.Hierarchy;
import org.apache.log4j.Level;
import org.apache.log4j.spi.Configurator;
import org.apache.log4j.spi.LoggerRepository;
@@ -27,19 +25,19 @@
@author Ceki Gülcü
@author Simon Kitching;
@author Anders Kristensen
-*/
+*/
public class OptionConverter {
static String DELIM_START = "${";
static char DELIM_STOP = '}';
static int DELIM_START_LEN = 2;
static int DELIM_STOP_LEN = 1;
-
+
static StringBuffer sbuf = new StringBuffer();
/** OptionConverter is a static class. */
private OptionConverter() {}
-
+
public
static
String[] concatanateArrays(String[] l, String[] r) {
@@ -51,14 +49,14 @@
return a;
}
-
+
public
static
String convertSpecialChars(String s) {
char c;
int len = s.length();
StringBuffer sbuf = new StringBuffer(len);
-
+
int i = 0;
while(i < len) {
c = s.charAt(i++);
@@ -68,12 +66,12 @@
else if(c == 'r') c = '\r';
else if(c == 't') c = '\t';
else if(c == 'f') c = '\f';
- else if(c == '\b') c = '\b';
- else if(c == '\"') c = '\"';
- else if(c == '\'') c = '\'';
- else if(c == '\\') c = '\\';
+ else if(c == '\b') c = '\b';
+ else if(c == '\"') c = '\"';
+ else if(c == '\'') c = '\'';
+ else if(c == '\\') c = '\\';
}
- sbuf.append(c);
+ sbuf.append(c);
}
return sbuf.toString();
}
@@ -94,13 +92,13 @@
String getSystemProperty(String key, String def) {
try {
return System.getProperty(key, def);
- } catch(Throwable e) { // MS-Java throws com.ms.security.SecurityExceptionEx
+ } catch(Throwable e) { // MS-Java throws com.ms.security.SecurityExceptionEx
LogLog.debug("Was not allowed to read system property \""+key+"\".");
return def;
}
}
-
+
public
static
Object instantiateByKey(Properties props, String key, Class superClass,
@@ -130,7 +128,7 @@
if(value == null)
return dEfault;
String trimmedVal = value.trim();
- if("true".equalsIgnoreCase(trimmedVal))
+ if("true".equalsIgnoreCase(trimmedVal))
return true;
if("false".equalsIgnoreCase(trimmedVal))
return false;
@@ -159,7 +157,7 @@
"level#classname", then the specified class' toLevel method
is called to process the specified level string; if no '#'
character is present, then the default {@link org.apache.log4j.Level}
- class is used to process the level value.
+ class is used to process the level value.
<p>As a special case, if the <code>value</code> parameter is
equal to the string "NULL", then the value <code>null</code> will
@@ -171,7 +169,7 @@
<p> Case of <code>value</code> is insignificant for the level level, but is
significant for the class name part, if present.
-
+
@since 1.1 */
public
static
@@ -193,13 +191,13 @@
String clazz = value.substring(hashIndex+1);
String levelName = value.substring(0, hashIndex);
-
+
// This is degenerate case but you never know.
if("NULL".equalsIgnoreCase(levelName)) {
return null;
}
- LogLog.debug("toLevel" + ":class=[" + clazz + "]"
+ LogLog.debug("toLevel" + ":class=[" + clazz + "]"
+ ":pri=[" + levelName + "]");
try {
@@ -238,18 +236,18 @@
}
return result;
}
-
+
public
static
long toFileSize(String value, long dEfault) {
if(value == null)
return dEfault;
-
+
String s = value.trim().toUpperCase();
long multiplier = 1;
int index;
-
- if((index = s.indexOf("KB")) != -1) {
+
+ if((index = s.indexOf("KB")) != -1) {
multiplier = 1024;
s = s.substring(0, index);
}
@@ -260,7 +258,7 @@
else if((index = s.indexOf("GB")) != -1) {
multiplier = 1024*1024*1024;
s = s.substring(0, index);
- }
+ }
if(s != null) {
try {
return Long.valueOf(s).longValue() * multiplier;
@@ -283,17 +281,17 @@
static
String findAndSubst(String key, Properties props) {
String value = props.getProperty(key);
- if(value == null)
- return null;
-
+ if(value == null)
+ return null;
+
try {
return substVars(value, props);
} catch(IllegalArgumentException e) {
LogLog.error("Bad option value ["+value+"].", e);
return value;
- }
+ }
}
-
+
/**
Instantiate an object given a class name. Check that the
<code>className</code> is a subclass of
@@ -314,7 +312,7 @@
if(!superClass.isAssignableFrom(classObj)) {
LogLog.error("A \""+className+"\" object is not assignable to a \""+
superClass.getName() + "\" variable.");
- return defaultValue;
+ return defaultValue;
}
return classObj.newInstance();
}
@@ -322,7 +320,7 @@
LogLog.error("Could not instantiate class [" + className + "].", e);
}
}
- return defaultValue;
+ return defaultValue;
}
@@ -331,13 +329,13 @@
values of keys found in the system propeties.
<p>The variable substitution delimeters are <b>${</b> and <b>}</b>.
-
+
<p>For example, if the System properties contains "key=value", then
the call
<pre>
String s = OptionConverter.substituteVars("Value of key is ${key}.");
</pre>
-
+
will set the variable <code>s</code> to "Value of key is value.".
<p>If no value could be found for the specified key, then the
@@ -350,7 +348,7 @@
<pre>
String s = OptionConverter.subsVars("Value of inexistentKey is [${inexistentKey}]");
</pre>
- will set <code>s</code> to "Value of inexistentKey is []"
+ will set <code>s</code> to "Value of inexistentKey is []"
<p>An {@link java.lang.IllegalArgumentException} is thrown if
<code>val</code> contains a start delimeter "${" which is not
@@ -369,7 +367,7 @@
int i = 0;
int j, k;
-
+
while(true) {
j=val.indexOf(DELIM_START, i);
if(j == -1) {
@@ -385,7 +383,7 @@
k = val.indexOf(DELIM_STOP, j);
if(k == -1) {
throw new IllegalArgumentException('"'+val+
- "\" has no closing brace. Opening brace at position " + j
+ "\" has no closing brace. Opening brace at position " + j
+ '.');
}
else {
@@ -398,9 +396,9 @@
replacement = props.getProperty(key);
}
- if(replacement != null)
+ if(replacement != null)
sbuf.append(replacement);
- i = k + DELIM_STOP_LEN;
+ i = k + DELIM_STOP_LEN;
}
}
}
@@ -408,7 +406,7 @@
/**
- Configure log4j given a URL.
+ Configure log4j given a URL.
<p>The url must point to a file or resource which will be interpreted by
a new instance of a log4j configurator.
@@ -427,20 +425,20 @@
@param hierarchy The {@link Hierarchy} to act on.
@since 1.1.4 */
-
+
static
public
void selectAndConfigure(URL url, String clazz, LoggerRepository hierarchy) {
Configurator configurator = null;
String filename = url.getFile();
-
+
if(clazz == null && filename != null && filename.endsWith(".xml")) {
clazz = "org.apache.log4j.xml.DOMConfigurator";
}
-
+
if(clazz != null) {
LogLog.debug("Preferred configurator class: " + clazz);
- configurator = (Configurator) instantiateByClassName(clazz,
+ configurator = (Configurator) instantiateByClassName(clazz,
Configurator.class,
null);
if(configurator == null) {
@@ -450,7 +448,7 @@
} else {
configurator = new PropertyConfigurator();
}
-
+
configurator.doConfigure(url, hierarchy);
}
}
1.6 +38 -40 jakarta-log4j/src/java/org/apache/log4j/helpers/ISO8601DateFormat.java
Index: ISO8601DateFormat.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/helpers/ISO8601DateFormat.java,v
retrieving revision 1.5
retrieving revision 1.6
diff -u -r1.5 -r1.6
--- ISO8601DateFormat.java 17 Feb 2002 21:50:58 -0000 1.5
+++ ISO8601DateFormat.java 24 Apr 2002 01:16:13 -0000 1.6
@@ -13,8 +13,6 @@
import java.util.Date;
import java.text.FieldPosition;
import java.text.ParsePosition;
-import java.text.DateFormat;
-import java.text.DateFormatSymbols;
// Contributors: Arndt Schoenewald <[email protected]>
@@ -26,9 +24,9 @@
href=http://www.cl.cam.ac.uk/~mgk25/iso-time.html>summary of the
International Standard Date and Time Notation</a> for more
information on this format.
-
+
@author Ceki Gülcü
- @author Andrew Vajoczki
+ @author Andrew Vajoczki
@since 0.7.5
*/
@@ -37,7 +35,7 @@
public
ISO8601DateFormat() {
}
-
+
public
ISO8601DateFormat(TimeZone timeZone) {
super(timeZone);
@@ -45,7 +43,7 @@
static private long lastTime;
static private char[] lastTimeString = new char[20];
-
+
/**
Appends a date in the format "YYYY-mm-dd HH:mm:ss,SSS"
to <code>sbuf</code>. For example: "1999-11-27 15:49:37,459".
@@ -63,78 +61,78 @@
// We reach this point at most once per second
// across all threads instead of each time format()
// is called. This saves considerable CPU time.
-
- calendar.setTime(date);
-
+
+ calendar.setTime(date);
+
int start = sbuf.length();
-
+
int year = calendar.get(Calendar.YEAR);
sbuf.append(year);
-
+
String month;
switch(calendar.get(Calendar.MONTH)) {
- case Calendar.JANUARY: month = "-01-"; break;
- case Calendar.FEBRUARY: month = "-02-"; break;
- case Calendar.MARCH: month = "-03-"; break;
- case Calendar.APRIL: month = "-04-"; break;
- case Calendar.MAY: month = "-05-"; break;
- case Calendar.JUNE: month = "-06-"; break;
- case Calendar.JULY: month = "-07-"; break;
- case Calendar.AUGUST: month = "-08-"; break;
- case Calendar.SEPTEMBER: month = "-09-"; break;
- case Calendar.OCTOBER: month = "-10-"; break;
- case Calendar.NOVEMBER: month = "-11-"; break;
+ case Calendar.JANUARY: month = "-01-"; break;
+ case Calendar.FEBRUARY: month = "-02-"; break;
+ case Calendar.MARCH: month = "-03-"; break;
+ case Calendar.APRIL: month = "-04-"; break;
+ case Calendar.MAY: month = "-05-"; break;
+ case Calendar.JUNE: month = "-06-"; break;
+ case Calendar.JULY: month = "-07-"; break;
+ case Calendar.AUGUST: month = "-08-"; break;
+ case Calendar.SEPTEMBER: month = "-09-"; break;
+ case Calendar.OCTOBER: month = "-10-"; break;
+ case Calendar.NOVEMBER: month = "-11-"; break;
case Calendar.DECEMBER: month = "-12-"; break;
default: month = "-NA-"; break;
}
sbuf.append(month);
-
+
int day = calendar.get(Calendar.DAY_OF_MONTH);
- if(day < 10)
+ if(day < 10)
sbuf.append('0');
sbuf.append(day);
-
- sbuf.append(' ');
-
+
+ sbuf.append(' ');
+
int hour = calendar.get(Calendar.HOUR_OF_DAY);
if(hour < 10) {
sbuf.append('0');
}
sbuf.append(hour);
sbuf.append(':');
-
+
int mins = calendar.get(Calendar.MINUTE);
if(mins < 10) {
sbuf.append('0');
}
sbuf.append(mins);
sbuf.append(':');
-
+
int secs = calendar.get(Calendar.SECOND);
if(secs < 10) {
sbuf.append('0');
}
sbuf.append(secs);
- sbuf.append(',');
-
+ sbuf.append(',');
+
// store the time string for next time to avoid recomputation
sbuf.getChars(start, sbuf.length(), lastTimeString, 0);
lastTime = now - millis;
- }
+ }
else {
sbuf.append(lastTimeString);
- }
-
-
+ }
+
+
if (millis < 100)
- sbuf.append('0');
+ sbuf.append('0');
if (millis < 10)
- sbuf.append('0');
-
+ sbuf.append('0');
+
sbuf.append(millis);
return sbuf;
- }
+ }
/**
This method does not do anything but return <code>null</code>.
@@ -142,6 +140,6 @@
public
Date parse(java.lang.String s, ParsePosition pos) {
return null;
- }
+ }
}
1.4 +9 -10 jakarta-log4j/src/java/org/apache/log4j/helpers/DateTimeDateFormat.java
Index: DateTimeDateFormat.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/helpers/DateTimeDateFormat.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- DateTimeDateFormat.java 5 Jul 2001 19:09:38 -0000 1.3
+++ DateTimeDateFormat.java 24 Apr 2002 01:16:13 -0000 1.4
@@ -12,13 +12,12 @@
import java.util.Date;
import java.text.FieldPosition;
import java.text.ParsePosition;
-import java.text.DateFormat;
import java.text.DateFormatSymbols;
/**
Formats a {@link Date} in the format "dd MMM YYYY HH:mm:ss,SSS" for example,
- "06 Nov 1994 15:49:37,459".
-
+ "06 Nov 1994 15:49:37,459".
+
@author Ceki Gülcü
@since 0.7.5
*/
@@ -31,13 +30,13 @@
super();
shortMonths = new DateFormatSymbols().getShortMonths();
}
-
+
public
DateTimeDateFormat(TimeZone timeZone) {
this();
setCalendar(Calendar.getInstance(timeZone));
}
-
+
/**
Appends to <code>sbuf</code> the date in the format "dd MMM YYYY
HH:mm:ss,SSS" for example, "06 Nov 1994 08:49:37,459".
@@ -48,15 +47,15 @@
StringBuffer format(Date date, StringBuffer sbuf,
FieldPosition fieldPosition) {
- calendar.setTime(date);
+ calendar.setTime(date);
int day = calendar.get(Calendar.DAY_OF_MONTH);
- if(day < 10)
+ if(day < 10)
sbuf.append('0');
sbuf.append(day);
- sbuf.append(' ');
+ sbuf.append(' ');
sbuf.append(shortMonths[calendar.get(Calendar.MONTH)]);
- sbuf.append(' ');
+ sbuf.append(' ');
int year = calendar.get(Calendar.YEAR);
sbuf.append(year);
@@ -71,5 +70,5 @@
public
Date parse(java.lang.String s, ParsePosition pos) {
return null;
- }
+ }
}
1.4 +2 -5 jakarta-log4j/src/java/org/apache/log4j/helpers/CountingQuietWriter.java
Index: CountingQuietWriter.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/helpers/CountingQuietWriter.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- CountingQuietWriter.java 5 Jul 2001 19:09:36 -0000 1.3
+++ CountingQuietWriter.java 24 Apr 2002 01:16:13 -0000 1.4
@@ -8,10 +8,7 @@
package org.apache.log4j.helpers;
-import java.io.File;
import java.io.Writer;
-import java.io.FileWriter;
-import java.io.FilterWriter;
import java.io.IOException;
import org.apache.log4j.spi.ErrorHandler;
@@ -32,7 +29,7 @@
CountingQuietWriter(Writer writer, ErrorHandler eh) {
super(writer, eh);
}
-
+
public
void write(String string) {
try {
@@ -53,5 +50,5 @@
void setCount(long count) {
this.count = count;
}
-
+
}
1.5 +7 -8 jakarta-log4j/src/java/org/apache/log4j/config/PropertyGetter.java
Index: PropertyGetter.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/config/PropertyGetter.java,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -r1.4 -r1.5
--- PropertyGetter.java 20 Jul 2001 15:57:51 -0000 1.4
+++ PropertyGetter.java 24 Apr 2002 01:16:13 -0000 1.5
@@ -12,31 +12,30 @@
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
-import org.apache.log4j.Appender;
import org.apache.log4j.Priority;
import org.apache.log4j.helpers.LogLog;
/**
Used for inferring configuration information for a log4j's component.
-
+
@author Anders Kristensen
*/
public class PropertyGetter {
protected static final Object[] NULL_ARG = new Object[] {};
protected Object obj;
protected PropertyDescriptor[] props;
-
+
public interface PropertyCallback {
void foundProperty(Object obj, String prefix, String name, Object value);
}
-
+
/**
Create a new PropertyGetter for the specified Object. This is done
in prepartion for invoking {@link
#getProperties(PropertyGetter.PropertyCallback, String)} one or
more times.
-
+
@param obj the object for which to set properties */
public
PropertyGetter(Object obj) throws IntrospectionException {
@@ -44,7 +43,7 @@
props = bi.getPropertyDescriptors();
this.obj = obj;
}
-
+
public
static
void getProperties(Object obj, PropertyCallback callback, String prefix) {
@@ -54,7 +53,7 @@
LogLog.error("Failed to introspect object " + obj, ex);
}
}
-
+
public
void getProperties(PropertyCallback callback, String prefix) {
for (int i = 0; i < props.length; i++) {
@@ -76,7 +75,7 @@
}
}
}
-
+
protected
boolean isHandledType(Class type) {
return String.class.isAssignableFrom(type) ||
1.21 +27 -30 jakarta-log4j/src/java/org/apache/log4j/WriterAppender.java
Index: WriterAppender.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/WriterAppender.java,v
retrieving revision 1.20
retrieving revision 1.21
diff -u -r1.20 -r1.21
--- WriterAppender.java 22 Feb 2002 18:36:28 -0000 1.20
+++ WriterAppender.java 24 Apr 2002 01:16:13 -0000 1.21
@@ -9,14 +9,11 @@
import java.io.IOException;
import java.io.Writer;
-import java.io.FileWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import org.apache.log4j.spi.ErrorHandler;
-import org.apache.log4j.spi.ErrorCode;
import org.apache.log4j.spi.LoggingEvent;
-import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.helpers.QuietWriter;
import org.apache.log4j.helpers.LogLog;
@@ -56,11 +53,11 @@
/**
This is the {@link QuietWriter quietWriter} where we will write
- to.
+ to.
*/
protected QuietWriter qw;
-
+
/**
This default constructor does nothing. */
public
@@ -75,7 +72,7 @@
WriterAppender(Layout layout, OutputStream os) {
this(layout, new OutputStreamWriter(os));
}
-
+
/**
Instantiate a WriterAppender and set the output destination to
<code>writer</code>.
@@ -93,7 +90,7 @@
<code>true</code>, the appender will flush at the end of each
write. This is the default behavior. If the option is set to
<code>false</code>, then the underlying stream can defer writing
- to physical medium to a later time.
+ to physical medium to a later time.
<p>Avoiding the flush operation at the end of each append results in
a performance gain of 10 to 20 percent. However, there is safety
@@ -119,13 +116,13 @@
Does nothing.
*/
public
- void activateOptions() {
+ void activateOptions() {
}
/**
This method is called by the {@link AppenderSkeleton#doAppend}
- method.
+ method.
<p>If the output stream exists and is writable then write a log
statement to the output stream. Otherwise, write a single warning
@@ -133,7 +130,7 @@
<p>The format of the output will depend on this appender's
layout.
-
+
*/
public
void append(LoggingEvent event) {
@@ -151,11 +148,11 @@
return;
}
subAppend(event);
- }
+ }
/**
This method determines if there is a sense in attempting to append.
-
+
<p>It checks whether there is a set output target and also if
there is a set layout. If these checks fail, then the boolean
value <code>false</code> is returned. */
@@ -167,11 +164,11 @@
}
if(this.qw == null) {
- errorHandler.error("No output stream or file set for the appender named ["+
+ errorHandler.error("No output stream or file set for the appender named ["+
name+"].");
return false;
}
-
+
if(this.layout == null) {
errorHandler.error("No layout set for the appender named ["+ name+"].");
return false;
@@ -183,7 +180,7 @@
/**
Close this appender instance. The underlying stream or writer is
also closed.
-
+
<p>Closed appenders cannot be reused.
@see #setWriter
@@ -200,7 +197,7 @@
/**
Close the underlying {@link java.io.Writer}.
*/
- protected
+ protected
void closeWriter() {
if(qw != null) {
try {
@@ -218,10 +215,10 @@
<code>encoding</code> property. If the encoding value is
specified incorrectly the writer will be opened using the default
system encoding (an error message will be printed to the loglog. */
- protected
+ protected
OutputStreamWriter createWriter(OutputStream os) {
OutputStreamWriter retval = null;
-
+
String enc = getEncoding();
if(enc != null) {
try {
@@ -237,16 +234,16 @@
return retval;
}
- public
+ public
String getEncoding() {
return encoding;
}
- public
+ public
void setEncoding(String value) {
encoding = value;
}
-
+
@@ -254,7 +251,7 @@
Set the {@link ErrorHandler} for this WriterAppender and also the
underlying {@link QuietWriter} if any. */
public
- synchronized
+ synchronized
void setErrorHandler(ErrorHandler eh) {
if(eh == null) {
LogLog.warn("You have tried to set a null error-handler.");
@@ -263,20 +260,20 @@
if(this.qw != null) {
this.qw.setErrorHandler(eh);
}
- }
+ }
}
/**
<p>Sets the Writer where the log output will go. The
specified Writer must be opened by the user and be
writable.
-
+
<p>The <code>java.io.Writer</code> will be closed when the
appender instance is closed.
-
+
<p><b>WARNING:</b> Logging to an unopened Writer will fail.
- <p>
+ <p>
@param Writer An already opened Writer. */
public
synchronized
@@ -309,10 +306,10 @@
}
}
}
-
+
if(this.immediateFlush) {
this.qw.flush();
- }
+ }
}
@@ -335,7 +332,7 @@
void reset() {
closeWriter();
this.qw = null;
- //this.tp = null;
+ //this.tp = null;
}
@@ -354,7 +351,7 @@
/**
Write a header as produced by the embedded layout's {@link
Layout#getHeader} method. */
- protected
+ protected
void writeHeader() {
if(layout != null) {
String h = layout.getHeader();
1.14 +23 -29 jakarta-log4j/src/java/org/apache/log4j/TTCCLayout.java
Index: TTCCLayout.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/TTCCLayout.java,v
retrieving revision 1.13
retrieving revision 1.14
diff -u -r1.13 -r1.14
--- TTCCLayout.java 3 Apr 2002 22:18:14 -0000 1.13
+++ TTCCLayout.java 24 Apr 2002 01:16:13 -0000 1.14
@@ -6,25 +6,19 @@
* the LICENSE.txt file.
*/
-// Contributors: Christopher Williams
+// Contributors: Christopher Williams
// Mathias Bogaert
-
+
package org.apache.log4j;
import org.apache.log4j.Level;
-import org.apache.log4j.helpers.OptionConverter;
-import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.helpers.DateLayout;
-import org.apache.log4j.helpers.RelativeTimeDateFormat;
-import org.apache.log4j.helpers.AbsoluteTimeDateFormat;
-import org.apache.log4j.helpers.DateTimeDateFormat;
-import org.apache.log4j.helpers.ISO8601DateFormat;
import org.apache.log4j.spi.LoggingEvent;
/**
TTCC layout format consists of time, thread, category and nested
diagnostic context information, hence the name.
-
+
<p>Each of the four fields can be individually enabled or
disabled. The time format depends on the <code>DateFormat</code>
used.
@@ -66,17 +60,17 @@
@author Ceki Gülcü
@author <A HREF="mailto:[email protected]">Heinz Richter</a>
-
+
*/
public class TTCCLayout extends DateLayout {
// Internal representation of options
- private boolean threadPrinting = true;
+ private boolean threadPrinting = true;
private boolean categoryPrefixing = true;
private boolean contextPrinting = true;
-
- protected final StringBuffer buf = new StringBuffer(256);
+
+ protected final StringBuffer buf = new StringBuffer(256);
/**
@@ -88,7 +82,7 @@
*/
public TTCCLayout() {
this.setDateFormat(RELATIVE_TIME_DATE_FORMAT, null);
- }
+ }
/**
@@ -102,7 +96,7 @@
public TTCCLayout(String dateFormatType) {
this.setDateFormat(dateFormatType);
}
-
+
/**
The <b>ThreadPrinting</b> option specifies whether the name of the
@@ -112,7 +106,7 @@
void setThreadPrinting(boolean threadPrinting) {
this.threadPrinting = threadPrinting;
}
-
+
/**
Returns value of the <b>ThreadPrinting</b> option.
*/
@@ -120,7 +114,7 @@
boolean getThreadPrinting() {
return threadPrinting;
}
-
+
/**
The <b>CategoryPrefixing</b> option specifies whether {@link Category}
name is part of log output or not. This is true by default.
@@ -129,7 +123,7 @@
void setCategoryPrefixing(boolean categoryPrefixing) {
this.categoryPrefixing = categoryPrefixing;
}
-
+
/**
Returns value of the <b>CategoryPrefixing</b> option.
*/
@@ -137,7 +131,7 @@
boolean getCategoryPrefixing() {
return categoryPrefixing;
}
-
+
/**
The <b>ContextPrinting</b> option specifies log output will include
the nested context information belonging to the current thread.
@@ -147,7 +141,7 @@
void setContextPrinting(boolean contextPrinting) {
this.contextPrinting = contextPrinting;
}
-
+
/**
Returns value of the <b>ContextPrinting</b> option.
*/
@@ -160,10 +154,10 @@
In addition to the level of the statement and message, the
returned byte array includes time, thread, category and {@link NDC}
information.
-
+
<p>Time, thread, category and diagnostic context are printed
depending on options.
-
+
@param category
@param level
@param message
@@ -176,7 +170,7 @@
buf.setLength(0);
dateFormat(buf, event);
-
+
if(this.threadPrinting) {
buf.append('[');
buf.append(event.getThreadName());
@@ -192,19 +186,19 @@
if(this.contextPrinting) {
String ndc = event.getNDC();
-
+
if(ndc != null) {
buf.append(ndc);
buf.append(' ');
}
- }
+ }
buf.append("- ");
buf.append(event.getRenderedMessage());
- buf.append(LINE_SEP);
+ buf.append(LINE_SEP);
return buf.toString();
}
-
- /**
+
+ /**
The TTCCLayout does not handle the throwable contained within
{@link LoggingEvent LoggingEvents}. Thus, it returns
<code>true</code>.
@@ -214,4 +208,4 @@
boolean ignoresThrowable() {
return true;
}
-}
+}
1.16 +24 -28 jakarta-log4j/src/java/org/apache/log4j/RollingFileAppender.java
Index: RollingFileAppender.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/RollingFileAppender.java,v
retrieving revision 1.15
retrieving revision 1.16
diff -u -r1.15 -r1.16
--- RollingFileAppender.java 14 Aug 2001 21:00:34 -0000 1.15
+++ RollingFileAppender.java 24 Apr 2002 01:16:13 -0000 1.16
@@ -12,35 +12,31 @@
import java.beans.*;
import java.io.IOException;
import java.io.Writer;
-import java.io.FileWriter;
import java.io.File;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
import org.apache.log4j.helpers.OptionConverter;
-import org.apache.log4j.helpers.QuietWriter;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.helpers.CountingQuietWriter;
import org.apache.log4j.spi.LoggingEvent;
/**
- RollingFileAppender extends FileAppender to backup the log files when
- they reach a certain size.
+ RollingFileAppender extends FileAppender to backup the log files when
+ they reach a certain size.
@author Heinz Richter
@author Ceki Gülcü
-
+
*/
public class RollingFileAppender extends FileAppender {
/**
- The default maximum file size is 10MB.
+ The default maximum file size is 10MB.
*/
- protected long maxFileSize = 10*1024*1024;
+ protected long maxFileSize = 10*1024*1024;
/**
There is one backup file by default.
*/
- protected int maxBackupIndex = 1;
+ protected int maxBackupIndex = 1;
/**
The default constructor simply calls its {@link
@@ -49,7 +45,7 @@
RollingFileAppender() {
super();
}
-
+
/**
Instantiate a RollingFileAppender and open the file designated by
<code>filename</code>. The opened filename will become the ouput
@@ -94,36 +90,36 @@
long getMaximumFileSize() {
return maxFileSize;
}
-
+
/**
Implements the usual roll over behaviour.
<p>If <code>MaxBackupIndex</code> is positive, then files
{<code>File.1</code>, ..., <code>File.MaxBackupIndex -1</code>}
- are renamed to {<code>File.2</code>, ...,
+ are renamed to {<code>File.2</code>, ...,
<code>File.MaxBackupIndex</code>}. Moreover, <code>File</code> is
renamed <code>File.1</code> and closed. A new <code>File</code> is
created to receive further log output.
<p>If <code>MaxBackupIndex</code> is equal to zero, then the
<code>File</code> is truncated with no backup files created.
-
+
*/
public // synchronization not necessary since doAppend is alreasy synched
void rollOver() {
- File target;
+ File target;
File file;
LogLog.debug("rolling over count=" + ((CountingQuietWriter) qw).getCount());
LogLog.debug("maxBackupIndex="+maxBackupIndex);
-
+
// If maxBackups <= 0, then there is no file renaming to be done.
if(maxBackupIndex > 0) {
// Delete the oldest file, to keep Windows happy.
- file = new File(fileName + '.' + maxBackupIndex);
+ file = new File(fileName + '.' + maxBackupIndex);
if (file.exists())
file.delete();
-
+
// Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2}
for (int i = maxBackupIndex - 1; i >= 1; i--) {
file = new File(fileName + "." + i);
@@ -137,13 +133,13 @@
// Rename fileName to fileName.1
target = new File(fileName + "." + 1);
- this.closeFile(); // keep windows happy.
+ this.closeFile(); // keep windows happy.
file = new File(fileName);
LogLog.debug("Renaming file " + file + " to " + target);
file.renameTo(target);
}
-
+
try {
// This will also close the file. This is OK since multiple
// close operations are safe.
@@ -156,7 +152,7 @@
public
synchronized
- void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize)
+ void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize)
throws IOException {
super.setFile(fileName, append, this.bufferedIO, this.bufferSize);
if(append) {
@@ -165,10 +161,10 @@
}
}
-
+
/**
Set the maximum number of backup files to keep around.
-
+
<p>The <b>MaxBackupIndex</b> option determines how many backup
files are kept before the oldest is erased. This option takes
a positive integer value. If set to zero, then there will be no
@@ -177,9 +173,9 @@
*/
public
void setMaxBackupIndex(int maxBackups) {
- this.maxBackupIndex = maxBackups;
+ this.maxBackupIndex = maxBackups;
}
-
+
/**
Set the maximum size that the output file is allowed to reach
before being rolled over to backup files.
@@ -201,7 +197,7 @@
/**
Set the maximum size that the output file is allowed to reach
before being rolled over to backup files.
-
+
<p>In configuration files, the <b>MaxFileSize</b> option takes an
long integer in the range 0 - 2^63. You can specify the value
with the suffixes "KB", "MB" or "GB" so that the integer is
@@ -221,7 +217,7 @@
/**
This method differentiates RollingFileAppender from its super
- class.
+ class.
@since 0.9.0
*/
@@ -229,7 +225,7 @@
void subAppend(LoggingEvent event) {
super.subAppend(event);
if((fileName != null) &&
- ((CountingQuietWriter) qw).getCount() >= maxFileSize)
+ ((CountingQuietWriter) qw).getCount() >= maxFileSize)
this.rollOver();
}
}
1.53 +67 -69 jakarta-log4j/src/java/org/apache/log4j/PropertyConfigurator.java
Index: PropertyConfigurator.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/PropertyConfigurator.java,v
retrieving revision 1.52
retrieving revision 1.53
diff -u -r1.52 -r1.53
--- PropertyConfigurator.java 17 Apr 2002 21:52:25 -0000 1.52
+++ PropertyConfigurator.java 24 Apr 2002 01:16:13 -0000 1.53
@@ -22,13 +22,11 @@
import org.apache.log4j.spi.LoggerFactory;
import org.apache.log4j.spi.LoggerRepository;
import org.apache.log4j.spi.RendererSupport;
-import org.apache.log4j.or.ObjectRenderer;
import org.apache.log4j.or.RendererMap;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.helpers.FileWatchdog;
-import java.util.NoSuchElementException;
import java.util.Enumeration;
import java.util.Properties;
import java.io.FileInputStream;
@@ -84,14 +82,14 @@
*/
protected Hashtable registry = new Hashtable(11);
protected LoggerFactory loggerFactory = new DefaultCategoryFactory();
-
+
static final String CATEGORY_PREFIX = "log4j.category.";
static final String LOGGER_PREFIX = "log4j.logger.";
static final String FACTORY_PREFIX = "log4j.factory";
static final String ADDITIVITY_PREFIX = "log4j.additivity.";
static final String ROOT_CATEGORY_PREFIX = "log4j.rootCategory";
static final String ROOT_LOGGER_PREFIX = "log4j.rootLogger";
- static final String APPENDER_PREFIX = "log4j.appender.";
+ static final String APPENDER_PREFIX = "log4j.appender.";
static final String RENDERER_PREFIX = "log4j.renderer.";
static final String THRESHOLD_PREFIX = "log4j.threshold";
@@ -100,7 +98,7 @@
public static final String LOGGER_FACTORY_KEY = "log4j.loggerFactory";
static final private String INTERNAL_ROOT_NAME = "root";
-
+
/**
Read configuration from a file. <b>The existing configuration is
not cleared nor reset.</b> If you require a different behavior,
@@ -113,7 +111,7 @@
elements are discussed below.
<h3>Repository-wide threshold</h3>
-
+
<p>The repository-wide threshold filters logging requests by level
regardless of logger. The syntax is:
@@ -127,7 +125,7 @@
level#classname. By default the repository-wide threshold is set
to the lowest possible value, namely the level <code>ALL</code>.
</p>
-
+
<h3>Appender configuration</h3>
@@ -138,11 +136,11 @@
log4j.appender.appenderName=fully.qualified.name.of.appender.class
# Set appender specific options.
- log4j.appender.appenderName.option1=value1
+ log4j.appender.appenderName.option1=value1
...
log4j.appender.appenderName.optionN=valueN
</pre>
-
+
For each named appender you can configure its {@link Layout}. The
syntax for configuring an appender's layout is:
<pre>
@@ -151,7 +149,7 @@
....
log4j.appender.appenderName.layout.optionN=valueN
</pre>
-
+
<h3>Configuring loggers</h3>
<p>The syntax for configuring the root logger is:
@@ -166,13 +164,13 @@
ERROR, WARN, INFO, DEBUG, ALL or a <em>custom level</em> value. A
custom level value can be specified in the form
<code>level#classname</code>.
-
+
<p>If a level value is specified, then the root level is set
to the corresponding level. If no level value is specified,
then the root level remains untouched.
<p>The root logger can be assigned multiple appenders.
-
+
<p>Each <i>appenderName</i> (separated by commas) will be added to
the root logger. The named appender is defined using the
appender syntax defined above.
@@ -194,16 +192,16 @@
hierarchy. However, if you set the level of a logger and
later decide that that logger should inherit its level, then
you should specify INHERITED as the value for the level value.
-
+
<p>Similar to the root logger syntax, each <i>appenderName</i>
(separated by commas) will be attached to the named logger.
-
+
<p>See the <a href="../../../../manual.html#additivity">appender
additivity rule</a> in the user manual for the meaning of the
<code>additivity</code> flag.
<h3>ObjectRenderers</h3>
-
+
You can customize the way message objects of a given type are
converted to String before being logged. This is done by
specifying an {@link org.apache.log4j.or.ObjectRenderer ObjectRenderer}
@@ -232,14 +230,14 @@
<pre>
- # Set options for appender named "A1".
+ # Set options for appender named "A1".
# Appender "A1" will be a SyslogAppender
log4j.appender.A1=org.apache.log4j.net.SyslogAppender
# The syslog daemon resides on www.abc.net
log4j.appender.A1.SyslogHost=www.abc.net
- # A1's layout is a PatternLayout, using the conversion pattern
+ # A1's layout is a PatternLayout, using the conversion pattern
# <b>%r %-5p %c{2} %M.%L %x - %m\n</b>. Thus, the log output will
# include # the relative time since the start of the application in
# milliseconds, followed by the level of the log request,
@@ -247,14 +245,14 @@
# followed by the callers method name, followed by the line number,
# the nested disgnostic context and finally the message itself.
# Refer to the documentation of {@link PatternLayout} for further information
- # on the syntax of the ConversionPattern key.
+ # on the syntax of the ConversionPattern key.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r %-5p %c{2} %M.%L %x - %m\n
# Set options for appender named "A2"
# A2 should be a RollingFileAppender, with maximum file size of 10 MB
# using at most one backup file. A2's layout is TTCC, using the
- # ISO8061 date format with context printing enabled.
+ # ISO8061 date format with context printing enabled.
log4j.appender.A2=org.apache.log4j.RollingFileAppender
log4j.appender.A2.MaxFileSize=10MB
log4j.appender.A2.MaxBackupIndex=1
@@ -275,7 +273,7 @@
# Output will go to A1.
log4j.logger.SECURITY.access=WARN
-
+
# The logger "class.of.the.day" inherits its level from the
# logger hierarchy. Output will go to the appender's of the root
# logger, A2 in this case.
@@ -284,11 +282,11 @@
<p>Refer to the <b>setOption</b> method in each Appender and
Layout for class specific options.
-
+
<p>Use the <code>#</code> or <code>!</code> characters at the
beginning of a line for comments.
-
- <p>
+
+ <p>
@param configFileName The name of the configuration file where the
configuration information is stored.
@@ -313,21 +311,21 @@
/**
*/
static
- public
+ public
void configure(String configFilename) {
- new PropertyConfigurator().doConfigure(configFilename,
+ new PropertyConfigurator().doConfigure(configFilename,
LogManager.getLoggerRepository());
}
/**
Read configuration options from url <code>configURL</code>.
-
+
@since 0.8.2
*/
public
static
void configure(java.net.URL configURL) {
- new PropertyConfigurator().doConfigure(configURL,
+ new PropertyConfigurator().doConfigure(configURL,
LogManager.getLoggerRepository());
}
@@ -340,15 +338,15 @@
static
public
void configure(Properties properties) {
- new PropertyConfigurator().doConfigure(properties,
+ new PropertyConfigurator().doConfigure(properties,
LogManager.getLoggerRepository());
}
/**
Like {@link #configureAndWatch(String, long)} except that the
default delay as defined by {@link FileWatchdog#DEFAULT_DELAY} is
- used.
-
+ used.
+
@param configFilename A file in key=value format.
*/
@@ -365,7 +363,7 @@
check if <code>configFilename</code> has been created or
modified. The period is determined by the <code>delay</code>
argument. If a change or file creation is detected, then
- <code>configFilename</code> is read to configure log4j.
+ <code>configFilename</code> is read to configure log4j.
@param configFilename A file in key=value format.
@param delay The delay in milliseconds to wait between each check.
@@ -393,15 +391,15 @@
if(value != null)
LogLog.warn("[log4j.configDebug] is deprecated. Use [log4j.debug] instead.");
}
-
+
if(value != null) {
LogLog.setInternalDebugging(OptionConverter.toBoolean(value, true));
}
- String thresholdStr = OptionConverter.findAndSubst(THRESHOLD_PREFIX,
- properties);
+ String thresholdStr = OptionConverter.findAndSubst(THRESHOLD_PREFIX,
+ properties);
if(thresholdStr != null) {
- hierarchy.setThreshold(OptionConverter.toLevel(thresholdStr,
+ hierarchy.setThreshold(OptionConverter.toLevel(thresholdStr,
(Level) Level.ALL));
LogLog.debug("Hierarchy threshold set to ["+hierarchy.getThreshold()+"].");
}
@@ -410,7 +408,7 @@
configureLoggerFactory(properties);
parseCatsAndRenderers(properties, hierarchy);
- LogLog.debug("Finished configuring.");
+ LogLog.debug("Finished configuring.");
// We don't want to hold references to appenders preventing their
// garbage collection.
registry.clear();
@@ -427,7 +425,7 @@
props.load(configURL.openStream());
}
catch (java.io.IOException e) {
- LogLog.error("Could not read configuration file from URL [" + configURL
+ LogLog.error("Could not read configuration file from URL [" + configURL
+ "].", e);
LogLog.error("Ignoring configuration file [" + configURL +"].");
return;
@@ -452,12 +450,12 @@
*/
protected void configureLoggerFactory(Properties props) {
String factoryClassName = OptionConverter.findAndSubst(LOGGER_FACTORY_KEY,
- props);
+ props);
if(factoryClassName != null) {
LogLog.debug("Setting category factory to ["+factoryClassName+"].");
- loggerFactory = (LoggerFactory)
+ loggerFactory = (LoggerFactory)
OptionConverter.instantiateByClassName(factoryClassName,
- LoggerFactory.class,
+ LoggerFactory.class,
loggerFactory);
PropertySetter.setProperties(loggerFactory, props, FACTORY_PREFIX + ".");
}
@@ -467,7 +465,7 @@
void configureOptionHandler(OptionHandler oh, String prefix,
Properties props) {
String[] options = oh.getOptionStrings();
- if(options == null)
+ if(options == null)
return;
String value;
@@ -484,25 +482,25 @@
oh.activateOptions();
}
*/
-
-
+
+
void configureRootCategory(Properties props, LoggerRepository hierarchy) {
String effectiveFrefix = ROOT_LOGGER_PREFIX;
String value = OptionConverter.findAndSubst(ROOT_LOGGER_PREFIX, props);
-
+
if(value == null) {
value = OptionConverter.findAndSubst(ROOT_CATEGORY_PREFIX, props);
effectiveFrefix = ROOT_CATEGORY_PREFIX;
}
- if(value == null)
+ if(value == null)
LogLog.debug("Could not find root logger information. Is this OK?");
else {
Logger root = hierarchy.getRootLogger();
synchronized(root) {
parseCategory(props, root, effectiveFrefix, INTERNAL_ROOT_NAME, value);
}
- }
+ }
}
@@ -512,12 +510,12 @@
protected
void parseCatsAndRenderers(Properties props, LoggerRepository hierarchy) {
Enumeration enum = props.propertyNames();
- while(enum.hasMoreElements()) {
+ while(enum.hasMoreElements()) {
String key = (String) enum.nextElement();
if(key.startsWith(CATEGORY_PREFIX) || key.startsWith(LOGGER_PREFIX)) {
String loggerName = null;
if(key.startsWith(CATEGORY_PREFIX)) {
- loggerName = key.substring(CATEGORY_PREFIX.length());
+ loggerName = key.substring(CATEGORY_PREFIX.length());
} else if(key.startsWith(LOGGER_PREFIX)) {
loggerName = key.substring(LOGGER_PREFIX.length());
}
@@ -528,33 +526,33 @@
parseAdditivityForLogger(props, logger, loggerName);
}
} else if(key.startsWith(RENDERER_PREFIX)) {
- String renderedClass = key.substring(RENDERER_PREFIX.length());
+ String renderedClass = key.substring(RENDERER_PREFIX.length());
String renderingClass = OptionConverter.findAndSubst(key, props);
if(hierarchy instanceof RendererSupport) {
RendererMap.addRenderer((RendererSupport) hierarchy, renderedClass,
renderingClass);
}
- }
+ }
}
- }
+ }
/**
Parse the additivity option for a non-root category.
*/
void parseAdditivityForLogger(Properties props, Logger cat,
String loggerName) {
- String value = OptionConverter.findAndSubst(ADDITIVITY_PREFIX + loggerName,
+ String value = OptionConverter.findAndSubst(ADDITIVITY_PREFIX + loggerName,
props);
LogLog.debug("Handling "+ADDITIVITY_PREFIX + loggerName+"=["+value+"]");
- // touch additivity only if necessary
+ // touch additivity only if necessary
if((value != null) && (!value.equals(""))) {
boolean additivity = OptionConverter.toBoolean(value, true);
LogLog.debug("Setting additivity for \""+loggerName+"\" to "+
- additivity);
+ additivity);
cat.setAdditivity(additivity);
}
}
-
+
/**
This method must work for the root category as well.
*/
@@ -564,16 +562,16 @@
LogLog.debug("Parsing for [" +loggerName +"] with value=[" + value+"].");
// We must skip over ',' but not white space
StringTokenizer st = new StringTokenizer(value, ",");
-
+
// If value is not in the form ", appender.." or "", then we should set
// the level of the loggeregory.
-
+
if(!(value.startsWith(",") || value.equals(""))) {
// just to be on the safe side...
if(!st.hasMoreTokens())
return;
-
+
String levelStr = st.nextToken();
LogLog.debug("Level token is [" + levelStr + "].");
@@ -591,8 +589,8 @@
// Begin by removing all existing appenders.
logger.removeAllAppenders();
-
- Appender appender;
+
+ Appender appender;
String appenderName;
while(st.hasMoreTokens()) {
appenderName = st.nextToken().trim();
@@ -602,8 +600,8 @@
appender = parseAppender(props, appenderName);
if(appender != null) {
logger.addAppender(appender);
- }
- }
+ }
+ }
}
Appender parseAppender(Properties props, String appenderName) {
@@ -614,7 +612,7 @@
}
// Appender was not previously initialized.
String prefix = APPENDER_PREFIX + appenderName;
- String layoutPrefix = prefix + ".layout";
+ String layoutPrefix = prefix + ".layout";
appender = (Appender) OptionConverter.instantiateByKey(props, prefix,
org.apache.log4j.Appender.class,
@@ -628,16 +626,16 @@
if(appender instanceof OptionHandler) {
if(appender.requiresLayout()) {
- Layout layout = (Layout) OptionConverter.instantiateByKey(props,
+ Layout layout = (Layout) OptionConverter.instantiateByKey(props,
layoutPrefix,
- Layout.class,
+ Layout.class,
null);
if(layout != null) {
appender.setLayout(layout);
LogLog.debug("Parsing layout options for \"" + appenderName +"\".");
//configureOptionHandler(layout, layoutPrefix + ".", props);
PropertySetter.setProperties(layout, props, layoutPrefix + ".");
- LogLog.debug("End of parsing for \"" + appenderName +"\".");
+ LogLog.debug("End of parsing for \"" + appenderName +"\".");
}
}
//configureOptionHandler((OptionHandler) appender, prefix + ".", props);
@@ -648,11 +646,11 @@
return appender;
}
-
+
void registryPut(Appender appender) {
registry.put(appender.getName(), appender);
}
-
+
Appender registryGet(String name) {
return (Appender) registry.get(name);
}
@@ -669,7 +667,7 @@
<code>filename</code> to reconfigure log4j. */
public
void doOnChange() {
- new PropertyConfigurator().doConfigure(filename,
+ new PropertyConfigurator().doConfigure(filename,
LogManager.getLoggerRepository());
}
}
1.14 +49 -58 jakarta-log4j/src/java/org/apache/log4j/PatternLayout.java
Index: PatternLayout.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/PatternLayout.java,v
retrieving revision 1.13
retrieving revision 1.14
diff -u -r1.13 -r1.14
--- PatternLayout.java 9 Aug 2001 20:16:31 -0000 1.13
+++ PatternLayout.java 24 Apr 2002 01:16:13 -0000 1.14
@@ -15,22 +15,13 @@
import org.apache.log4j.NDC;
import org.apache.log4j.helpers.PatternParser;
import org.apache.log4j.helpers.PatternConverter;
-import org.apache.log4j.helpers.OptionConverter;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.TimeZone;
-import java.util.Vector;
-import java.text.FieldPosition;
// Contributors: Nelson Minar <[email protected]>
// Anders Kristensen <[email protected]>
/**
-
+
A flexible layout configurable with pattern string.
<p>The goal of this class is to {@link #format format} a {@link
@@ -44,7 +35,7 @@
<p><i>You are free to insert any literal text within the conversion
pattern.</i>
-
+
<p>Each conversion specifier starts with a percent sign (%) and is
followed by optional <em>format modifiers</em> and a <em>conversion
character</em>. The conversion character specifies the type of
@@ -58,12 +49,12 @@
<pre>
Category root = Category.getRoot();
root.debug("Message 1");
- root.warn("Message 2");
+ root.warn("Message 2");
</pre>
would yield the output
<pre>
DEBUG [main]: Message 1
- WARN [main]: Message 2
+ WARN [main]: Message 2
</pre>
<p>Note that there is no explicit separator between text and
@@ -72,9 +63,9 @@
character. In the example above the conversion specifier
<b>%-5p</b> means the priority of the logging event should be left
justified to a width of five characters.
-
+
The recognized conversion characters are
-
+
<p>
<table border="1" CELLPADDING="8">
<th>Conversion Character</th>
@@ -109,7 +100,7 @@
<p>If a precision specifier is given, then only the corresponding
number of right most components of the class name will be
printed. By default the class name is output in fully qualified form.
-
+
<p>For example, for the class name "org.apache.xyz.SomeClass", the
pattern <b>%C{1}</b> will output "SomeClass".
@@ -119,7 +110,7 @@
</td>
</tr>
-
+
<tr> <td align=center><b>d</b></td> <td>Used to output the date of
the logging event. The date conversion specifier may be
followed by a <em>date format specifier</em> enclosed between
@@ -127,7 +118,7 @@
<b>%d{dd MMM yyyy HH:mm:ss,SSS}</b>. If no
date format specifier is given then ISO8601 format is
assumed.
-
+
<p>The date format specifier admits the same syntax as the
time pattern string of the {@link
java.text.SimpleDateFormat}. Although part of the standard
@@ -161,12 +152,12 @@
is not an issue.
</tr>
-
+
<tr>
<td align=center><b>l</b></td>
<td>Used to output location information of the caller which generated
- the logging event.
+ the logging event.
<p>The location information depends on the JVM implementation but
usually consists of the fully qualified name of the calling
@@ -176,7 +167,7 @@
<p>The location information can be very useful. However, it's
generation is <em>extremely</em> slow. It's use should be avoided
unless execution speed is not an issue.
-
+
</td>
</tr>
@@ -192,11 +183,11 @@
</tr>
-
+
<tr>
<td align=center><b>m</b></td>
- <td>Used to output the application supplied message associated with
- the logging event.</td>
+ <td>Used to output the application supplied message associated with
+ the logging event.</td>
</tr>
<tr>
@@ -213,47 +204,47 @@
<tr>
<td align=center><b>n</b></td>
-
+
<td>Outputs the platform dependent line separator character or
- characters.
+ characters.
<p>This conversion character offers practically the same
performance as using non-portable line separator strings such as
"\n", or "\r\n". Thus, it is the preferred way of specifying a
line separator.
-
+
</tr>
-
+
<tr>
<td align=center><b>p</b></td>
<td>Used to output the priority of the logging event.</td>
</tr>
-
+
<tr>
<td align=center><b>r</b></td>
<td>Used to output the number of milliseconds elapsed since the start
of the application until the creation of the logging event.</td>
- </tr>
-
+ </tr>
+
<tr>
<td align=center><b>t</b></td>
<td>Used to output the name of the thread that generated the
logging event.</td>
-
+
</tr>
-
+
<tr>
<td align=center><b>x</b></td>
<td>Used to output the NDC (nested diagnostic context) associated
with the thread that generated the logging event.
- </td>
+ </td>
</tr>
<tr>
@@ -261,9 +252,9 @@
<td align=center><b>%</b></td>
<td>The sequence %% outputs a single percent sign.
- </td>
+ </td>
</tr>
-
+
</table>
<p>By default the relevant information is output as is. However,
@@ -318,7 +309,7 @@
<tr> <td align=center>%-20c</td> <td align=center>true</td> <td
align=center>20</td> <td align=center>none</td> <td>Right pad with
spaces if the category name is less than 20 characters long.
-
+
<tr>
<td align=center>%.30c</td>
<td align=center>NA</td>
@@ -336,7 +327,7 @@
<td>Left pad with spaces if the category name is shorter than 20
characters. However, if category name is longer than 30 characters,
- then truncate from the beginning.
+ then truncate from the beginning.
<tr>
<td align=center>%-20.30c</td>
@@ -346,15 +337,15 @@
<td>Right pad with spaces if the category name is shorter than 20
characters. However, if category name is longer than 30 characters,
- then truncate from the beginning.
-
+ then truncate from the beginning.
+
</table>
<p>Below are some examples of conversion patterns.
<dl>
- <p><dt><b>%r [%t] %-5p %c %x - %m\n</b>
+ <p><dt><b>%r [%t] %-5p %c %x - %m\n</b>
<p><dd>This is essentially the TTCC layout.
<p><dt><b>%-6r [%15.15t] %-5p %30.30c %x - %m\n</b>
@@ -364,13 +355,13 @@
less than 15 characters and truncated if longer and the category
name is left padded if shorter than 30 characters and truncated if
longer.
-
+
</dl>
-
+
<p>The above text is largely inspired from Peter A. Darnell and
Philip E. Margolis' highly recommended book "C -- a Software
Engineering Approach", ISBN 0-387-97389-3.
-
+
@author <a href="mailto:[email protected]">James P. Cakalic</a>
@author Ceki Gülcü
@@ -385,27 +376,27 @@
public final static String DEFAULT_CONVERSION_PATTERN ="%m%n";
/** A conversion pattern equivalent to the TTCCCLayout.
- Current value is <b>%r [%t] %p %c %x - %m%n</b>. */
+ Current value is <b>%r [%t] %p %c %x - %m%n</b>. */
public final static String TTCC_CONVERSION_PATTERN
= "%r [%t] %p %c %x - %m%n";
-
+
protected final int BUF_SIZE = 256;
protected final int MAX_CAPACITY = 1024;
-
+
// output buffer appended to when format() is invoked
private StringBuffer sbuf = new StringBuffer(BUF_SIZE);
-
+
private String pattern;
-
+
private PatternConverter head;
private String timezone;
-
+
/**
Constructs a PatternLayout using the DEFAULT_LAYOUT_PATTERN.
-
+
The default pattern just produces the application supplied message.
*/
public PatternLayout() {
@@ -417,10 +408,10 @@
*/
public PatternLayout(String pattern) {
this.pattern = pattern;
- head = createPatternParser((pattern == null) ? DEFAULT_CONVERSION_PATTERN :
+ head = createPatternParser((pattern == null) ? DEFAULT_CONVERSION_PATTERN :
pattern).parse();
}
-
+
/**
Set the <b>ConversionPattern</b> option. This is the string which
controls formatting and consists of a mix of literal content and
@@ -431,7 +422,7 @@
pattern = conversionPattern;
head = createPatternParser(conversionPattern).parse();
}
-
+
/**
Returns the value of the <b>ConversionPattern</b> option.
*/
@@ -439,15 +430,15 @@
String getConversionPattern() {
return pattern;
}
-
+
/**
- Does not do anything as options become effective
+ Does not do anything as options become effective
*/
public
void activateOptions() {
// nothing to do.
}
-
+
/**
The PatternLayout does not handle the throwable contained within
{@link LoggingEvent LoggingEvents}. Thus, it returns
@@ -481,7 +472,7 @@
} else {
sbuf.setLength(0);
}
-
+
PatternConverter c = head;
while(c != null) {
1.14 +17 -35 jakarta-log4j/src/java/org/apache/log4j/Logger.java
Index: Logger.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/Logger.java,v
retrieving revision 1.13
retrieving revision 1.14
diff -u -r1.13 -r1.14
--- Logger.java 11 Feb 2002 16:14:33 -0000 1.13
+++ Logger.java 24 Apr 2002 01:16:13 -0000 1.14
@@ -7,25 +7,7 @@
package org.apache.log4j;
-import org.apache.log4j.spi.RootCategory;
-import org.apache.log4j.spi.AppenderAttachable;
import org.apache.log4j.spi.LoggerFactory;
-import org.apache.log4j.spi.LoggingEvent;
-import org.apache.log4j.helpers.LogLog;
-import org.apache.log4j.helpers.NullEnumeration;
-import org.apache.log4j.helpers.OptionConverter;
-import org.apache.log4j.helpers.AppenderAttachableImpl;
-import org.apache.log4j.helpers.Loader;
-import org.apache.log4j.or.RendererMap;
-import org.apache.log4j.or.ObjectRenderer;
-
-import java.util.Enumeration;
-import java.util.Vector;
-import java.util.MissingResourceException;
-import java.text.MessageFormat;
-import java.util.ResourceBundle;
-import java.net.URL;
-import java.net.MalformedURLException;
/**
@@ -36,17 +18,17 @@
public class Logger extends Category {
/**
- The fully qualified name of the Level class. See also the
+ The fully qualified name of the Level class. See also the
getFQCN method. */
private static final String FQCN = Level.class.getName();
- protected
+ protected
Logger(String name) {
super(name);
}
- /**
+ /**
Log a message object with the {@link Level#FINE FINE} level which
is just an alias for the {@link Level#DEBUG DEBUG} level.
@@ -63,33 +45,33 @@
method will print the name of the <code>Throwable</code> but no
stack trace. To print a stack trace use the {@link #debug(Object,
Throwable)} form instead.
-
+
@param message the message object to log. */
//public
//void fine(Object message) {
- // if(repository.isDisabled(Level.DEBUG_INT))
- // return;
+ // if(repository.isDisabled(Level.DEBUG_INT))
+ // return;
// if(Level.DEBUG.isGreaterOrEqual(this.getChainedLevel())) {
// forcedLog(FQCN, Level.DEBUG, message, null);
// }
//}
-
- /**
+
+ /**
Log a message object with the <code>FINE</code> level including
the stack trace of the {@link Throwable} <code>t</code> passed as
parameter.
-
+
<p>See {@link #fine(Object)} form for more detailed information.
-
+
@param message the message object to log.
- @param t the exception to log, including its stack trace. */
+ @param t the exception to log, including its stack trace. */
//public
//void fine(Object message, Throwable t) {
- // if(repository.isDisabled(Level.DEBUG_INT))
+ // if(repository.isDisabled(Level.DEBUG_INT))
// return;
// if(Level.DEBUG.isGreaterOrEqual(this.getChainedLevel()))
- // forcedLog(FQCN, Level.FINE, message, t);
+ // forcedLog(FQCN, Level.FINE, message, t);
//}
/**
@@ -115,7 +97,7 @@
Retrieve the root logger.
*/
public
- static
+ static
Logger getRootLogger() {
return LogManager.getRootLogger();
}
@@ -125,9 +107,9 @@
instantiated depends on the type returned by the {@link
LoggerFactory#makeNewLoggerInstance} method of the
<code>factory</code> parameter.
-
+
<p>This method is intended to be used by sub-classes.
-
+
@param name The name of the logger to retrieve.
@param factory A {@link LoggerFactory} implementation that will
@@ -138,6 +120,6 @@
static
Logger getLogger(String name, LoggerFactory factory) {
return LogManager.getLogger(name, factory);
- }
+ }
}
1.39 +51 -53 jakarta-log4j/src/java/org/apache/log4j/Hierarchy.java
Index: Hierarchy.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/Hierarchy.java,v
retrieving revision 1.38
retrieving revision 1.39
diff -u -r1.38 -r1.39
--- Hierarchy.java 11 Feb 2002 16:14:33 -0000 1.38
+++ Hierarchy.java 24 Apr 2002 01:16:14 -0000 1.39
@@ -6,7 +6,7 @@
* distribution in the LICENSE.txt file. */
// WARNING This class MUST not have references to the Category or
-// WARNING RootCategory classes in its static initiliazation neither
+// WARNING RootCategory classes in its static initiliazation neither
// WARNING directly nor indirectly.
// Contributors:
@@ -14,7 +14,7 @@
// Mario Schomburg - IBM Global Services/Germany
// Anders Kristensen
// Igor Poteryaev
-
+
package org.apache.log4j;
@@ -22,7 +22,6 @@
import java.util.Enumeration;
import java.util.Vector;
-import org.apache.log4j.spi.RootCategory;
import org.apache.log4j.spi.LoggerFactory;
import org.apache.log4j.spi.HierarchyEventListener;
import org.apache.log4j.spi.LoggerRepository;
@@ -31,7 +30,6 @@
import org.apache.log4j.or.RendererMap;
import org.apache.log4j.or.ObjectRenderer;
import org.apache.log4j.helpers.LogLog;
-import org.apache.log4j.helpers.OptionConverter;
/**
This class is specialized in retrieving loggers by name and also
@@ -51,7 +49,7 @@
to the provision node. Other descendants of the same ancestor add
themselves to the previously created provision node.
- @author Ceki Gülcü
+ @author Ceki Gülcü
*/
public class Hierarchy implements LoggerRepository, RendererSupport {
@@ -67,7 +65,7 @@
Level threshold;
boolean emittedNoAppenderWarning = false;
- boolean emittedNoResourceBundleWarning = false;
+ boolean emittedNoResourceBundleWarning = false;
/**
Create a new logger hierarchy.
@@ -88,14 +86,14 @@
}
/**
- Add an object renderer for a specific class.
+ Add an object renderer for a specific class.
*/
public
void addRenderer(Class classToRender, ObjectRenderer or) {
rendererMap.put(classToRender, or);
}
-
- public
+
+ public
void addHierarchyEventListener(HierarchyEventListener listener) {
if(listeners.contains(listener)) {
LogLog.warn("Ignoring attempt to add an existent listener.");
@@ -108,7 +106,7 @@
This call will clear all logger definitions from the internal
hashtable. Invoking this method will irrevocably mess up the
logger hierarchy.
-
+
<p>You should <em>really</em> know what you are doing before
invoking this method.
@@ -119,7 +117,7 @@
ht.clear();
}
- public
+ public
void emitNoAppenderWarning(Category cat) {
// No appenders in hierarchy, warn user only once.
if(!this.emittedNoAppenderWarning) {
@@ -133,12 +131,12 @@
/**
Check if the named logger exists in the hierarchy. If so return
its reference, otherwise returns <code>null</code>.
-
+
@param name The name of the logger to search for.
-
+
*/
public
- Logger exists(String name) {
+ Logger exists(String name) {
Object o = ht.get(new CategoryKey(name));
if(o instanceof Logger) {
return (Logger) o;
@@ -150,7 +148,7 @@
/**
The string form of {@link #setThreshold(Level)}.
*/
- public
+ public
void setThreshold(String levelStr) {
Level l = (Level) Level.toLevel(levelStr, null);
if(l != null) {
@@ -167,7 +165,7 @@
@param l The minimum level for which logging requests are sent to
their appenders. */
- public
+ public
void setThreshold(Level l) {
if(l != null) {
thresholdInt = l.level;
@@ -184,7 +182,7 @@
listener = (HierarchyEventListener) listeners.elementAt(i);
listener.addAppenderEvent(logger, appender);
}
- }
+ }
}
void fireRemoveAppenderEvent(Category logger, Appender appender) {
@@ -195,7 +193,7 @@
listener = (HierarchyEventListener) listeners.elementAt(i);
listener.removeAppenderEvent(logger, appender);
}
- }
+ }
}
/**
@@ -221,12 +219,12 @@
/**
Return a new logger instance named as the first parameter using
- the default factory.
-
+ the default factory.
+
<p>If a logger of that name already exists, then it will be
returned. Otherwise, a new logger will be instantiated and
then linked with its existing ancestors as well as children.
-
+
@param name The name of the logger to retrieve.
*/
@@ -238,12 +236,12 @@
/**
Return a new logger instance named as the first parameter using
<code>factory</code>.
-
+
<p>If a logger of that name already exists, then it will be
returned. Otherwise, a new logger will be instantiated by the
<code>factory</code> parameter and linked with its existing
ancestors as well as children.
-
+
@param name The name of the logger to retrieve.
@param factory The factory that will make the new logger instance.
@@ -251,18 +249,18 @@
public
Logger getLogger(String name, LoggerFactory factory) {
//System.out.println("getInstance("+name+") called.");
- CategoryKey key = new CategoryKey(name);
+ CategoryKey key = new CategoryKey(name);
// Synchronize to prevent write conflicts. Read conflicts (in
// getChainedLevel method) are possible only if variable
// assignments are non-atomic.
Logger logger;
-
+
synchronized(ht) {
Object o = ht.get(key);
if(o == null) {
logger = factory.makeNewLoggerInstance(name);
logger.setHierarchy(this);
- ht.put(key, logger);
+ ht.put(key, logger);
updateParents(logger);
return logger;
} else if(o instanceof Logger) {
@@ -270,10 +268,10 @@
} else if (o instanceof ProvisionNode) {
//System.out.println("("+name+") ht.get(this) returned ProvisionNode");
logger = factory.makeNewLoggerInstance(name);
- logger.setHierarchy(this);
+ logger.setHierarchy(this);
ht.put(key, logger);
updateChildren((ProvisionNode) o, logger);
- updateParents(logger);
+ updateParents(logger);
return logger;
}
else {
@@ -295,7 +293,7 @@
// ht are Logger objects as there might be some ProvisionNodes
// as well.
Vector v = new Vector(ht.size());
-
+
Enumeration elems = ht.elements();
while(elems.hasMoreElements()) {
Object o = elems.nextElement();
@@ -326,7 +324,7 @@
/**
Get the root of this hierarchy.
-
+
@since 0.9.0
*/
public
@@ -340,7 +338,7 @@
<code>false</code> otherwise. See also the {@link
#setThreshold(Level) threshold} emthod. */
public
- boolean isDisabled(int level) {
+ boolean isDisabled(int level) {
return thresholdInt > level;
}
@@ -372,12 +370,12 @@
getRootLogger().setLevel((Level) Level.DEBUG);
root.setResourceBundle(null);
setThreshold(Level.ALL);
-
+
// the synchronization is needed to prevent JDK 1.2.x hashtable
// surprises
- synchronized(ht) {
- shutdown(); // nested locks are OK
-
+ synchronized(ht) {
+ shutdown(); // nested locks are OK
+
Enumeration cats = getCurrentLoggers();
while(cats.hasMoreElements()) {
Logger c = (Logger) cats.nextElement();
@@ -391,12 +389,12 @@
/**
Does mothing.
-
+
@deprecated Deprecated with no replacement.
*/
public
void setDisableOverride(String override) {
- LogLog.warn("The Hiearchy.setDisableOverride method has been deprecated.");
+ LogLog.warn("The Hiearchy.setDisableOverride method has been deprecated.");
}
@@ -413,7 +411,7 @@
/**
Shutting down a hierarchy will <em>safely</em> close and remove
all appenders in all categories including the root logger.
-
+
<p>Some appenders such as {@link org.apache.log4j.net.SocketAppender}
and {@link AsyncAppender} need to be closed before the
application exists. Otherwise, pending logging events might be
@@ -423,12 +421,12 @@
appenders before closing regular appenders. This is allows
configurations where a regular appender is attached to a logger
and again to a nested appender.
-
+
@since 1.0 */
- public
+ public
void shutdown() {
- Logger root = getRootLogger();
+ Logger root = getRootLogger();
// begin by closing nested appenders
root.closeNestedAppenders();
@@ -446,7 +444,7 @@
while(cats.hasMoreElements()) {
Logger c = (Logger) cats.nextElement();
c.removeAllAppenders();
- }
+ }
}
}
@@ -466,7 +464,7 @@
parent field with this entry. We also break from the loop
because updating our parent's parent is our parent's
responsibility.
-
+
3) There entry is of type ProvisionNode for this potential parent.
We add 'cat' to the list of children for this potential parent.
@@ -477,11 +475,11 @@
String name = cat.name;
int length = name.length();
boolean parentFound = false;
-
+
//System.out.println("UpdateParents called for " + name);
-
- // if name = "w.x.y.z", loop thourgh "w.x.y", "w.x" and "w", but not "w.x.y.z"
- for(int i = name.lastIndexOf('.', length-1); i >= 0;
+
+ // if name = "w.x.y.z", loop thourgh "w.x.y", "w.x" and "w", but not "w.x.y.z"
+ for(int i = name.lastIndexOf('.', length-1); i >= 0;
i = name.lastIndexOf('.', i-1)) {
String substr = name.substring(0, i);
@@ -501,17 +499,17 @@
} else if(o instanceof ProvisionNode) {
((ProvisionNode) o).addElement(cat);
} else {
- Exception e = new IllegalStateException("unexpected object type " +
+ Exception e = new IllegalStateException("unexpected object type " +
o.getClass() + " in ht.");
- e.printStackTrace();
+ e.printStackTrace();
}
}
// If we could not find any existing parents, then link with root.
- if(!parentFound)
+ if(!parentFound)
cat.parent = root;
}
- /**
+ /**
We update the links for all the children that placed themselves
in the provision node 'pn'. The second argument 'cat' is a
reference for the newly created Logger, parent of all the
@@ -540,10 +538,10 @@
// make cat.parent point to l.parent and l.parent to cat.
if(!l.parent.name.startsWith(logger.name)) {
logger.parent = l.parent;
- l.parent = logger;
+ l.parent = logger;
}
}
- }
+ }
}
1.26 +23 -27 jakarta-log4j/src/java/org/apache/log4j/HTMLLayout.java
Index: HTMLLayout.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/HTMLLayout.java,v
retrieving revision 1.25
retrieving revision 1.26
diff -u -r1.25 -r1.26
--- HTMLLayout.java 21 Jan 2002 23:07:11 -0000 1.25
+++ HTMLLayout.java 24 Apr 2002 01:16:14 -0000 1.26
@@ -9,15 +9,11 @@
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.LocationInfo;
-import org.apache.log4j.helpers.OptionConverter;
-import java.io.StringWriter;
-import java.io.PrintWriter;
-import java.io.Writer;
/**
This layout outputs events in a HTML table.
- @author Ceki Gülcü
+ @author Ceki Gülcü
*/
public class HTMLLayout extends Layout {
@@ -32,10 +28,10 @@
/**
A string constant used in naming the option for setting the the
location information flag. Current value of this string
- constant is <b>LocationInfo</b>.
+ constant is <b>LocationInfo</b>.
<p>Note that all option keys are case sensitive.
-
+
@deprecated Options are now handled using the JavaBeans paradigm.
This constant is not longer needed and will be removed in the
<em>near</em> term.
@@ -46,7 +42,7 @@
/**
A string constant used in naming the option for setting the the
HTML document title. Current value of this string
- constant is <b>Title</b>.
+ constant is <b>Title</b>.
*/
public static final String TITLE_OPTION = "Title";
@@ -60,7 +56,7 @@
default, it is set to false which means there will be no location
information output by this layout. If the the option is set to
true, then the file name and line number of the statement
- at the origin of the log statement will be output.
+ at the origin of the log statement will be output.
<p>If you are embedding this layout within an {@link
org.apache.log4j.net.SMTPAppender} then make sure to set the
@@ -70,7 +66,7 @@
void setLocationInfo(boolean flag) {
locationInfo = flag;
}
-
+
/**
Returns the current value of the <b>LocationInfo</b> option.
*/
@@ -82,7 +78,7 @@
/**
The <b>Title</b> option takes a String value. This option sets the
document title of the generated HTML document.
-
+
<p>Defaults to 'Log4J Log Messages'.
*/
public
@@ -97,7 +93,7 @@
String getTitle() {
return title;
}
-
+
/**
Returns the content type output by this layout, i.e "text/html".
*/
@@ -112,18 +108,18 @@
public
void activateOptions() {
}
-
- public
+
+ public
String format(LoggingEvent event) {
-
+
if(sbuf.capacity() > MAX_CAPACITY) {
sbuf = new StringBuffer(BUF_SIZE);
} else {
sbuf.setLength(0);
}
-
+
sbuf.append(Layout.LINE_SEP + "<tr>" + Layout.LINE_SEP);
-
+
sbuf.append("<td>");
sbuf.append(event.timeStamp - event.getStartTime());
sbuf.append("</td>" + Layout.LINE_SEP);
@@ -135,15 +131,15 @@
sbuf.append("<td title=\"Level\">");
if (event.level.equals(Level.DEBUG)) {
sbuf.append("<font color=\"#339933\">");
- sbuf.append(event.level);
+ sbuf.append(event.level);
sbuf.append("</font>");
}
else if(event.level.isGreaterOrEqual(Level.WARN)) {
sbuf.append("<font color=\"#993300\"><strong>");
- sbuf.append(event.level);
+ sbuf.append(event.level);
sbuf.append("</strong></font>");
} else {
- sbuf.append(event.level);
+ sbuf.append(event.level);
}
sbuf.append("</td>" + Layout.LINE_SEP);
@@ -171,7 +167,7 @@
sbuf.append("</td></tr>" + Layout.LINE_SEP);
}
- String[] s = event.getThrowableStrRep();
+ String[] s = event.getThrowableStrRep();
if(s != null) {
sbuf.append("<tr><td bgcolor=\"#993300\" style=\"color:White; font-size : xx-small;\" colspan=\"6\">");
appendThrowableAsHTML(s, sbuf);
@@ -184,7 +180,7 @@
void appendThrowableAsHTML(String[] s, StringBuffer sbuf) {
if(s != null) {
int len = s.length;
- if(len == 0)
+ if(len == 0)
return;
sbuf.append(escapeHTMLTags(s[0]));
sbuf.append(Layout.LINE_SEP);
@@ -242,7 +238,7 @@
sbuf.append("</body></html>");
return sbuf.toString();
}
-
+
/**
The HTML layout handles the throwable contained in logging
events. Hence, this method return <code>false</code>. */
@@ -263,17 +259,17 @@
private String escapeHTMLTags(String input) {
//Check if the string is null or zero length -- if so, return
//what was sent in.
-
+
if( input == null || input.length() == 0 ) {
return input;
}
-
+
//Use a StringBuffer in lieu of String concatenation -- it is
//much more efficient this way.
-
+
StringBuffer buf = new StringBuffer(input.length() + 6);
char ch = ' ';
-
+
int len = input.length();
for(int i=0; i < len; i++) {
ch = input.charAt(i);
1.33 +33 -39 jakarta-log4j/src/java/org/apache/log4j/FileAppender.java
Index: FileAppender.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/FileAppender.java,v
retrieving revision 1.32
retrieving revision 1.33
diff -u -r1.32 -r1.33
--- FileAppender.java 18 Nov 2001 12:57:26 -0000 1.32
+++ FileAppender.java 24 Apr 2002 01:16:14 -0000 1.33
@@ -9,16 +9,10 @@
import java.io.IOException;
import java.io.Writer;
-import java.io.FileWriter;
import java.io.FileOutputStream;
-import java.io.OutputStream;
import java.io.BufferedWriter;
-import java.io.OutputStreamWriter;
-import org.apache.log4j.spi.ErrorHandler;
import org.apache.log4j.spi.ErrorCode;
-import org.apache.log4j.spi.LoggingEvent;
-import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.helpers.QuietWriter;
import org.apache.log4j.helpers.LogLog;
@@ -26,12 +20,12 @@
// Ben Sandee
/**
- FileAppender appends log events to a file.
-
+ FileAppender appends log events to a file.
+
<p>Support for <code>java.io.Writer</code> and console appending
has been deprecated and then removed. See the replacement
solutions: {@link WriterAppender} and {@link ConsoleAppender}.
-
+
@author Ceki Gülcü */
public class FileAppender extends WriterAppender {
@@ -42,7 +36,7 @@
not truncate it.
<p>This option is meaningful only if the FileAppender opens the
- file.
+ file.
*/
protected boolean fileAppend = true;
@@ -60,7 +54,7 @@
/**
- The default constructor does not do anything.
+ The default constructor does not do anything.
*/
public
FileAppender() {
@@ -76,11 +70,11 @@
<code>filename</code> will be truncated before being opened.
<p>If the <code>bufferedIO</code> parameter is <code>true</code>,
- then buffered IO will be used to write to the output file.
-
+ then buffered IO will be used to write to the output file.
+
*/
public
- FileAppender(Layout layout, String filename, boolean append, boolean bufferedIO,
+ FileAppender(Layout layout, String filename, boolean append, boolean bufferedIO,
int bufferSize) throws IOException {
this.layout = layout;
this.setFile(filename, append, bufferedIO, bufferSize);
@@ -96,7 +90,7 @@
<code>filename</code> will be truncated before being opened.
*/
public
- FileAppender(Layout layout, String filename, boolean append)
+ FileAppender(Layout layout, String filename, boolean append)
throws IOException {
this.layout = layout;
this.setFile(filename, append, false, bufferSize);
@@ -115,29 +109,29 @@
/**
The <b>File</b> property takes a string value which should be the
- name of the file to append to.
+ name of the file to append to.
<p><font color="#DD0044"><b>Note that the special values
"System.out" or "System.err" are no longer honored.</b></font>
-
+
<p>Note: Actual opening of the file is made when {@link
#activateOptions} is called, not when the options are set. */
public void setFile(String file) {
- // Trim spaces from both ends. The users probably does not want
+ // Trim spaces from both ends. The users probably does not want
// trailing spaces in file names.
String val = file.trim();
- fileName = val;
+ fileName = val;
}
- /**
- Returns the value of the <b>Append</b> option.
+ /**
+ Returns the value of the <b>Append</b> option.
*/
public
boolean getAppend() {
return fileAppend;
}
-
+
/** Returns the value of the <b>File</b> option. */
public
String getFile() {
@@ -186,7 +180,7 @@
/**
Get the value of the <b>BufferedIO</b> option.
-
+
<p>BufferedIO will significatnly increase performance on heavily
loaded systems.
@@ -195,16 +189,16 @@
boolean getBufferedIO() {
return this.bufferedIO;
}
-
-
+
+
/**
- Get the size of the IO buffer.
+ Get the size of the IO buffer.
*/
public
int getBufferSize() {
return this.bufferSize;
}
-
+
/**
@@ -221,7 +215,7 @@
void setAppend(boolean flag) {
fileAppend = flag;
}
-
+
/**
The <b>BufferedIO</b> option takes a boolean value. It is set to
<code>false</code> by default. If true, then <code>File</code>
@@ -239,8 +233,8 @@
immediateFlush = false;
}
}
-
-
+
+
/**
Set the size of the IO buffer.
*/
@@ -248,31 +242,31 @@
void setBufferSize(int bufferSize) {
this.bufferSize = bufferSize;
}
-
+
/**
<p>Sets and <i>opens</i> the file where the log output will
- go. The specified file must be writable.
+ go. The specified file must be writable.
<p>If there was already an opened file, then the previous file
- is closed first.
+ is closed first.
@param fileName The path to the log file.
@param append If true will append to fileName. Otherwise will
truncate fileName. */
public
synchronized
- void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize)
+ void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize)
throws IOException {
LogLog.debug("setFile called: "+fileName+", "+append);
-
+
// It does not make sense to have immediate flush and bufferedIO.
if(bufferedIO) {
setImmediateFlush(false);
}
- reset();
+ reset();
Writer fw = createWriter(new FileOutputStream(fileName, append));
if(bufferedIO) {
fw = new BufferedWriter(fw);
@@ -289,7 +283,7 @@
/**
Sets the quiet writer being used.
-
+
This method is overriden by {@link RollingFileAppender}.
*/
protected
@@ -305,7 +299,7 @@
void reset() {
closeFile();
this.fileName = null;
- super.reset();
- }
+ super.reset();
+ }
}
1.19 +51 -59 jakarta-log4j/src/java/org/apache/log4j/DailyRollingFileAppender.java
Index: DailyRollingFileAppender.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/DailyRollingFileAppender.java,v
retrieving revision 1.18
retrieving revision 1.19
diff -u -r1.18 -r1.19
--- DailyRollingFileAppender.java 18 Feb 2002 21:43:31 -0000 1.18
+++ DailyRollingFileAppender.java 24 Apr 2002 01:16:14 -0000 1.19
@@ -10,22 +10,14 @@
package org.apache.log4j;
import java.io.IOException;
-import java.io.Writer;
-import java.io.FileWriter;
import java.io.File;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Calendar;
-import org.apache.log4j.helpers.OptionConverter;
-import org.apache.log4j.helpers.QuietWriter;
-import org.apache.log4j.helpers.CountingQuietWriter;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;
-import org.apache.log4j.spi.ErrorCode;
/**
DailyRollingFileAppender extends {@link FileAppender} so that the
@@ -44,19 +36,19 @@
<code>/foo/bar.log.2001-02-16</code> and logging for 2001-02-17
will continue in <code>/foo/bar.log</code> until it rolls over
the next day.
-
+
<p>Is is possible to specify monthly, weekly, half-daily, daily,
hourly, or minutely rollover schedules.
<p><table border="1" cellpadding="2">
<tr>
- <th>DatePattern</th>
+ <th>DatePattern</th>
<th>Rollover schedule</th>
<th>Example</th>
<tr>
<td><code>'.'yyyy-MM</code>
- <td>Rollover at the beginning of each month</td>
+ <td>Rollover at the beginning of each month</td>
<td>Assuming the first day of the week is Sunday, at Sunday 00:00,
March 25th, 2001, <code>/foo/bar.log</code> will be copied to
@@ -66,40 +58,40 @@
<tr>
<td><code>'.'yyyy-ww</code>
-
+
<td>Rollover at the first day of each week. The first day of the
week depends on the locale.</td>
-
+
<td>At midnight, on March 31st, 2001, <code>/foo/bar.log</code>
will be copied to <code>/foo/bar.log.2001-08</code>. Logging for
the 9th week of 2001 will be output to <code>/foo/bar.log</code>
until it is rolled over the next week.
<tr>
- <td><code>'.'yyyy-MM-dd</code>
-
+ <td><code>'.'yyyy-MM-dd</code>
+
<td>Rollover at midnight each day.</td>
-
+
<td>At midnight, on March 9th, 2001, <code>/foo/bar.log</code> will
be copied to <code>/foo/bar.log.2001-03-08</code>. Logging for the
9th day of March will be output to <code>/foo/bar.log</code> until
it is rolled over the next day.
<tr>
- <td><code>'.'yyyy-MM-dd-a</code>
-
+ <td><code>'.'yyyy-MM-dd-a</code>
+
<td>Rollover at midnight and midday of each day.</td>
-
+
<td>At noon, on March 9th, 2001, <code>/foo/bar.log</code> will be
copied to <code>/foo/bar.log.2001-03-09-AM</code>. Logging for the
afternoon of the 9th will be output to <code>/foo/bar.log</code>
until it is rolled over the next morning, i.e at midnight 00:00.
<tr>
- <td><code>'.'yyyy-MM-dd-HH</code>
-
+ <td><code>'.'yyyy-MM-dd-HH</code>
+
<td>Rollover at the top of every hour.</td>
-
+
<td>At approximately 11:00,000, on March 9th, 2001,
<code>/foo/bar.log</code> will be copied to
<code>/foo/bar.log.2001-03-09-10</code>. Logging for the 11th hour
@@ -108,16 +100,16 @@
<tr>
- <td><code>'.'yyyy-MM-dd-HH-mm</code>
-
+ <td><code>'.'yyyy-MM-dd-HH-mm</code>
+
<td>Rollover at the beginning of every minute.</td>
-
+
<td>At approximately 11:23,000, on March 9th, 2001,
<code>/foo/bar.log</code> will be copied to
<code>/foo/bar.log.2001-03-09-10-22</code>. Logging for the minute
of 11:23 (9th of March) will be output to
<code>/foo/bar.log</code> until it is rolled over the next minute.
-
+
</table>
<p>Do not use the colon ":" character in anywhere in the
@@ -144,7 +136,7 @@
/**
The date pattern. By default, the pattern is set to
- "'.'yyyy-MM-dd" meaning daily rollover.
+ "'.'yyyy-MM-dd" meaning daily rollover.
*/
private String datePattern = "'.'yyyy-MM-dd";
@@ -178,7 +170,7 @@
become the ouput destination for this appender.
*/
- public DailyRollingFileAppender (Layout layout, String filename,
+ public DailyRollingFileAppender (Layout layout, String filename,
String datePattern) throws IOException {
super(layout, filename, true);
this.datePattern = datePattern;
@@ -194,7 +186,7 @@
void setDatePattern(String pattern) {
datePattern = pattern;
}
-
+
/** Returns the value of the <b>DatePattern</b> option. */
public
String getDatePattern() {
@@ -218,7 +210,7 @@
name+"].");
}
}
-
+
void printPeriodicity(int type) {
switch(type) {
case TOP_OF_MINUTE:
@@ -243,13 +235,13 @@
case TOP_OF_MONTH:
LogLog.debug("Appender ["+name
+"] to be rolled at start of every month.");
- break;
+ break;
default:
LogLog.warn("Unknown periodicity for appender ["+name+"].");
}
}
-
-
+
+
// This method computes the roll over period by looping over the
// periods, starting with the shortest, and stopping when the r0 is
// different from from r1, where r0 is the epoch formatted according
@@ -259,9 +251,9 @@
int computeCheckPeriod() {
RollingCalendar rollingCalendar = new RollingCalendar();
// set sate to 1970-01-01 00:00:00 GMT
- Date epoch = new Date(0);
+ Date epoch = new Date(0);
if(datePattern != null) {
- for(int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) {
+ for(int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern);
String r0 = simpleDateFormat.format(epoch);
rollingCalendar.setType(i);
@@ -278,7 +270,7 @@
/**
Rollover the current file to a new file.
- */
+ */
void rollOver() throws IOException {
/* Compute filename, but only if datePattern is specified */
@@ -293,16 +285,16 @@
}
// close current file, and rename it to datedFilename
- this.closeFile();
-
- File target = new File(scheduledFilename);
+ this.closeFile();
+
+ File target = new File(scheduledFilename);
if (target.exists()) {
target.delete();
}
File file = new File(fileName);
- file.renameTo(target);
- LogLog.debug(fileName +" -> "+ scheduledFilename);
+ file.renameTo(target);
+ LogLog.debug(fileName +" -> "+ scheduledFilename);
try {
// This will also close the file. This is OK since multiple
@@ -312,7 +304,7 @@
catch(IOException e) {
errorHandler.error("setFile("+fileName+", false) call failed.");
}
- scheduledFilename = datedFilename;
+ scheduledFilename = datedFilename;
}
/**
@@ -325,14 +317,14 @@
*/
- protected
+ protected
void subAppend(LoggingEvent event) {
long n = System.currentTimeMillis();
if (n >= nextCheck) {
now.setTime(n);
nextCheck = rc.getNextCheckMillis(now);
- try {
- rollOver();
+ try {
+ rollOver();
}
catch(IOException ioe) {
LogLog.error("rollOver() failed.", ioe);
@@ -340,13 +332,13 @@
}
super.subAppend(event);
}
-}
+}
/**
RollingCalendar is a helper class to
DailyRollingFileAppender. Using this class, it is easy to compute
and access the next Millis().
-
+
It subclasses the standard {@link GregorianCalendar}-object, to
allow access to the protected function getTimeInMillis(), which it
then exports.
@@ -354,7 +346,7 @@
@author <a HREF="mailto:[email protected]">Eirik Lygre</a> */
class RollingCalendar extends GregorianCalendar {
-
+
int type = DailyRollingFileAppender.TOP_OF_TROUBLE;
void setType(int type) {
@@ -366,7 +358,7 @@
return getNextCheckDate(now).getTime();
}
- public
+ public
Date getNextCheckDate(Date now) {
this.setTime(now);
@@ -374,16 +366,16 @@
case DailyRollingFileAppender.TOP_OF_MINUTE:
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
- this.add(Calendar.MINUTE, 1);
+ this.add(Calendar.MINUTE, 1);
break;
case DailyRollingFileAppender.TOP_OF_HOUR:
- this.set(Calendar.MINUTE, 0);
+ this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
- this.add(Calendar.HOUR_OF_DAY, 1);
+ this.add(Calendar.HOUR_OF_DAY, 1);
break;
case DailyRollingFileAppender.HALF_DAY:
- this.set(Calendar.MINUTE, 0);
+ this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
int hour = get(Calendar.HOUR_OF_DAY);
@@ -391,15 +383,15 @@
this.set(Calendar.HOUR_OF_DAY, 12);
} else {
this.set(Calendar.HOUR_OF_DAY, 0);
- this.add(Calendar.DAY_OF_MONTH, 1);
+ this.add(Calendar.DAY_OF_MONTH, 1);
}
break;
case DailyRollingFileAppender.TOP_OF_DAY:
- this.set(Calendar.HOUR_OF_DAY, 0);
- this.set(Calendar.MINUTE, 0);
+ this.set(Calendar.HOUR_OF_DAY, 0);
+ this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
- this.add(Calendar.DATE, 1);
+ this.add(Calendar.DATE, 1);
break;
case DailyRollingFileAppender.TOP_OF_WEEK:
this.set(Calendar.DAY_OF_WEEK, getFirstDayOfWeek());
@@ -413,11 +405,11 @@
this.set(Calendar.HOUR_OF_DAY, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
- this.add(Calendar.MONTH, 1);
+ this.add(Calendar.MONTH, 1);
break;
default:
throw new IllegalStateException("Unknown periodicity type.");
- }
+ }
return getTime();
}
}
1.12 +13 -14 jakarta-log4j/src/java/org/apache/log4j/ConsoleAppender.java
Index: ConsoleAppender.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/ConsoleAppender.java,v
retrieving revision 1.11
retrieving revision 1.12
diff -u -r1.11 -r1.12
--- ConsoleAppender.java 20 Jul 2001 17:12:01 -0000 1.11
+++ ConsoleAppender.java 24 Apr 2002 01:16:14 -0000 1.12
@@ -9,7 +9,6 @@
import java.io.OutputStreamWriter;
import org.apache.log4j.helpers.LogLog;
-import org.apache.log4j.helpers.OptionConverter;
/**
ConsoleAppender appends log events to <code>System.out</code> or
@@ -28,7 +27,7 @@
/**
The default constructor does nothing.
*/
- public ConsoleAppender() {
+ public ConsoleAppender() {
}
public ConsoleAppender(Layout layout) {
@@ -37,9 +36,9 @@
public ConsoleAppender(Layout layout, String target) {
this.layout = layout;
-
+
if (SYSTEM_OUT.equals(target)) {
- setWriter(new OutputStreamWriter(System.out));
+ setWriter(new OutputStreamWriter(System.out));
} else if (SYSTEM_ERR.equalsIgnoreCase(target)) {
setWriter(new OutputStreamWriter(System.err));
} else {
@@ -50,37 +49,37 @@
/**
Sets the value of the <b>Target</b> option. Recognized values are
"System.out" and "System.err". Any other value will be ignored.
- */
+ */
public
void setTarget(String value) {
String v = value.trim();
-
+
if (SYSTEM_OUT.equalsIgnoreCase(v)) {
target = SYSTEM_OUT;
} else if (SYSTEM_ERR.equalsIgnoreCase(v)) {
target = SYSTEM_ERR;
} else {
targetWarn(value);
- }
+ }
}
-
- /**
+
+ /**
Returns the current value of the <b>Target</b> property. The default
- value of the option is "System.out".
+ value of the option is "System.out".
- See also {@link #setTarget}.
+ See also {@link #setTarget}.
*/
public
String getTarget() {
return target;
}
-
+
void targetWarn(String val) {
LogLog.warn("["+val+"] should be System.out or System.err.");
LogLog.warn("Using System.out (default).");
}
-
+
public
void activateOptions() {
if(target.equals(SYSTEM_OUT)) {
@@ -94,7 +93,7 @@
Override the parent method to do nothing.
*/
protected
- final
+ final
void closeWriter() {
}
}
1.65 +137 -146 jakarta-log4j/src/java/org/apache/log4j/Category.java
Index: Category.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/Category.java,v
retrieving revision 1.64
retrieving revision 1.65
diff -u -r1.64 -r1.65
--- Category.java 30 Mar 2002 10:33:29 -0000 1.64
+++ Category.java 24 Apr 2002 01:16:14 -0000 1.65
@@ -17,27 +17,18 @@
// Calvin Chan <[email protected]>
// Aaron Greenhouse <[email protected]>
// Beat Meier <[email protected]>
-// Colin Sampaleanu <[email protected]>
+// Colin Sampaleanu <[email protected]>
package org.apache.log4j;
-import org.apache.log4j.spi.RootCategory;
import org.apache.log4j.spi.AppenderAttachable;
-import org.apache.log4j.spi.LoggerFactory;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.LoggerRepository;
-import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.helpers.NullEnumeration;
-import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.helpers.AppenderAttachableImpl;
-import org.apache.log4j.helpers.Loader;
-import org.apache.log4j.or.RendererMap;
-import org.apache.log4j.or.ObjectRenderer;
import java.util.Enumeration;
-import java.util.Vector;
import java.util.MissingResourceException;
-import java.text.MessageFormat;
import java.util.ResourceBundle;
@@ -46,7 +37,7 @@
replaced by the {@link Logger} <em>subclass</em>.</b></font> It
will be kept around to preserve backward compatibility until mid
2003.
-
+
<p><code>Logger</code> is a subclass of Category, i.e. it extends
Category. In other words, a logger <em>is</em> a category. Thus,
all operations that can be performed on a category can be performed
@@ -54,7 +45,7 @@
it will instead produce a Logger object. However, methods that
previously accepted category objects still continue to accept
category objects.
-
+
<p>For example, the following are all legal and will work as expected.
<pre>
@@ -66,13 +57,13 @@
</pre>
<p>The first form is deprecated and should be avoided.
-
+
<p><b>There is absolutely no need for new client code to use or
refer to the <code>Category</code> class.</b> Whenever possible,
please avoid referring to it or using it.
<p>See the <a href="../../../../manual.html">short manual</a> for an
- introduction on this class.
+ introduction on this class.
@author Ceki Gülcü
@author Anders Kristensen */
@@ -81,9 +72,9 @@
/**
The hierarchy where categories are attached to by default.
*/
- //static
- //public
- //final Hierarchy defaultHierarchy = new Hierarchy(new
+ //static
+ //public
+ //final Hierarchy defaultHierarchy = new Hierarchy(new
// RootCategory(Level.DEBUG));
@@ -92,7 +83,7 @@
/**
The name of this category.
*/
- protected String name;
+ protected String name;
/**
The assigned level of this category. The
@@ -106,12 +97,12 @@
volatile protected Category parent;
/**
- The fully qualified name of the Category class. See also the
+ The fully qualified name of the Category class. See also the
getFQCN method. */
private static final String FQCN = Category.class.getName();
-
+
protected ResourceBundle resourceBundle;
-
+
// Categories need to know what Hierarchy they are in
protected LoggerRepository repository;
@@ -126,7 +117,7 @@
have their additivity flag set to <code>false</code> too. See
the user manual for more details. */
protected boolean additive = true;
-
+
/**
This constructor created a new <code>Category</code> instance and
sets its name.
@@ -134,9 +125,9 @@
<p>It is intended to be used by sub-classes only. You should not
create categories directly.
- @param name The name of the category.
+ @param name The name of the category.
*/
- protected
+ protected
Category(String name) {
this.name = name;
}
@@ -148,8 +139,8 @@
<p>If <code>newAppender</code> is already in the list of
appenders, then it won't be added again.
*/
- synchronized
- public
+ synchronized
+ public
void addAppender(Appender newAppender) {
if(aai == null) {
aai = new AppenderAttachableImpl();
@@ -166,7 +157,7 @@
<code>assertLog</code> because <code>assert</code> is a language
reserved word in JDK 1.4.
- @param assertion
+ @param assertion
@param msg The message to print if <code>assertion</code> is
false.
@@ -176,7 +167,7 @@
if(!assertion)
this.error(msg);
}
-
+
/**
Call the appenders in the hierrachy starting at
@@ -186,7 +177,7 @@
<p>This method calls all the appenders inherited from the
hierarchy circumventing any evaluation of whether to log or not
to log the particular log request.
-
+
@param LoggingEvent the event to log. */
public
void callAppenders(LoggingEvent event) {
@@ -203,7 +194,7 @@
}
}
}
-
+
if(writes == 0) {
repository.emitNoAppenderWarning(this);
}
@@ -211,7 +202,7 @@
/**
Close all attached appenders implementing the AppenderAttachable
- interface.
+ interface.
@since 1.0
*/
synchronized
@@ -227,7 +218,7 @@
}
}
- /**
+ /**
Log a message object with the {@link Level#DEBUG DEBUG} level.
<p>This method first checks if this category is <code>DEBUG</code>
@@ -243,33 +234,33 @@
method will print the name of the <code>Throwable</code> but no
stack trace. To print a stack trace use the {@link #debug(Object,
Throwable)} form instead.
-
+
@param message the message object to log. */
public
void debug(Object message) {
- if(repository.isDisabled(Level.DEBUG_INT))
- return;
+ if(repository.isDisabled(Level.DEBUG_INT))
+ return;
if(Level.DEBUG.isGreaterOrEqual(this.getEffectiveLevel())) {
forcedLog(FQCN, Level.DEBUG, message, null);
}
}
-
- /**
+
+ /**
Log a message object with the <code>DEBUG</code> level including
the stack trace of the {@link Throwable} <code>t</code> passed as
parameter.
-
+
<p>See {@link #debug(Object)} form for more detailed information.
-
+
@param message the message object to log.
- @param t the exception to log, including its stack trace. */
+ @param t the exception to log, including its stack trace. */
public
void debug(Object message, Throwable t) {
- if(repository.isDisabled(Level.DEBUG_INT))
+ if(repository.isDisabled(Level.DEBUG_INT))
return;
if(Level.DEBUG.isGreaterOrEqual(this.getEffectiveLevel()))
- forcedLog(FQCN, Level.DEBUG, message, t);
+ forcedLog(FQCN, Level.DEBUG, message, t);
}
//public
@@ -280,8 +271,8 @@
// System.out.println("---------------------------");
//
//}
-
- /**
+
+ /**
Log a message object with the {@link Level#ERROR ERROR} Level.
<p>This method first checks if this category is <code>ERROR</code>
@@ -297,7 +288,7 @@
method will print the name of the <code>Throwable</code> but no
stack trace. To print a stack trace use the {@link #error(Object,
Throwable)} form instead.
-
+
@param message the message object to log */
public
void error(Object message) {
@@ -307,22 +298,22 @@
forcedLog(FQCN, Level.ERROR, message, null);
}
- /**
+ /**
Log a message object with the <code>ERROR</code> level including
the stack trace of the {@link Throwable} <code>t</code> passed as
parameter.
-
+
<p>See {@link #error(Object)} form for more detailed information.
-
+
@param message the message object to log.
- @param t the exception to log, including its stack trace. */
+ @param t the exception to log, including its stack trace. */
public
void error(Object message, Throwable t) {
if(repository.isDisabled(Level.ERROR_INT))
return;
if(Level.ERROR.isGreaterOrEqual(this.getEffectiveLevel()))
forcedLog(FQCN, Level.ERROR, message, t);
-
+
}
@@ -336,11 +327,11 @@
@version 0.8.5 */
public
static
- Logger exists(String name) {
+ Logger exists(String name) {
return LogManager.exists(name);
}
- /**
+ /**
Log a message object with the {@link Level#FATAL FATAL} Level.
<p>This method first checks if this category is <code>FATAL</code>
@@ -355,30 +346,30 @@
<p><b>WARNING</b> Note that passing a {@link Throwable} to this
method will print the name of the Throwable but no stack trace. To
print a stack trace use the {@link #fatal(Object, Throwable)} form
- instead.
-
+ instead.
+
@param message the message object to log */
public
void fatal(Object message) {
- if(repository.isDisabled(Level.FATAL_INT))
- return;
+ if(repository.isDisabled(Level.FATAL_INT))
+ return;
if(Level.FATAL.isGreaterOrEqual(this.getEffectiveLevel()))
forcedLog(FQCN, Level.FATAL, message, null);
}
-
- /**
+
+ /**
Log a message object with the <code>FATAL</code> level including
the stack trace of the {@link Throwable} <code>t</code> passed as
parameter.
-
+
<p>See {@link #fatal(Object)} for more detailed information.
-
+
@param message the message object to log.
@param t the exception to log, including its stack trace. */
public
void fatal(Object message, Throwable t) {
if(repository.isDisabled(Level.FATAL_INT))
- return;
+ return;
if(Level.FATAL.isGreaterOrEqual(this.getEffectiveLevel()))
forcedLog(FQCN, Level.FATAL, message, t);
}
@@ -394,7 +385,7 @@
/**
- Get the additivity flag for this Category instance.
+ Get the additivity flag for this Category instance.
*/
public
boolean getAdditivity() {
@@ -405,14 +396,14 @@
Get the appenders contained in this category as an {@link
Enumeration}. If no appenders can be found, then a {@link NullEnumeration}
is returned.
-
+
@return Enumeration An enumeration of the appenders in this category. */
synchronized
public
Enumeration getAllAppenders() {
if(aai == null)
return NullEnumeration.getInstance();
- else
+ else
return aai.getAllAppenders();
}
@@ -429,32 +420,32 @@
return aai.getAppender(name);
}
-
+
/**
Starting from this category, search the category hierarchy for a
non-null level and return it. Otherwise, return the level of the
root category.
-
+
<p>The Category class is designed so that this method executes as
quickly as possible.
*/
- public
+ public
Level getEffectiveLevel() {
for(Category c = this; c != null; c=c.parent) {
- if(c.level != null)
+ if(c.level != null)
return c.level;
}
return null; // If reached will cause an NullPointerException.
}
/**
-
+
@deprecated Has been replaced by the {@link #getEffectiveLevel}
method. */
- public
+ public
Priority getChainedPriority() {
for(Category c = this; c != null; c=c.parent) {
- if(c.level != null)
+ if(c.level != null)
return c.level;
}
return null; // If reached will cause an NullPointerException.
@@ -466,7 +457,7 @@
hierarchy as an {@link java.util.Enumeration Enumeration}.
<p>The root category is <em>not</em> included in the returned
- {@link Enumeration}.
+ {@link Enumeration}.
@deprecated Please use {@link LogManager#getCurrentLoggers()} instead.
*/
@@ -480,12 +471,12 @@
/**
Return the default Hierarchy instance.
- @deprecated Please use {@link LogManager#getLoggerRepository()} instead.
+ @deprecated Please use {@link LogManager#getLoggerRepository()} instead.
@since 1.0
*/
- public
- static
+ public
+ static
LoggerRepository getDefaultHierarchy() {
return LogManager.getLoggerRepository();
}
@@ -497,7 +488,7 @@
@deprecated Please use {@link #getLoggerRepository} instead.
@since 1.1 */
- public
+ public
LoggerRepository getHierarchy() {
return repository;
}
@@ -507,17 +498,17 @@
<code>Category</code> is attached.
@since 1.2 */
- public
+ public
LoggerRepository getLoggerRepository() {
return repository;
}
-
+
/**
Retrieve a category with named as the <code>name</code>
parameter. If the named category already exists, then the
existing instance will be reutrned. Otherwise, a new instance is
- created.
+ created.
By default, categories do not have a set level but inherit
it from the hierarchy. This is one of the central features of
@@ -532,7 +523,7 @@
Category getInstance(String name) {
nooptimize++;
return LogManager.getLogger(name);
- }
+ }
/**
Shorthand for <code>getInstance(clazz.getName())</code>.
@@ -549,9 +540,9 @@
Category getInstance(Class clazz) {
nooptimize++;
return LogManager.getLogger(clazz);
- }
+ }
+
-
/**
Return the category name. */
public
@@ -560,11 +551,11 @@
return name;
}
-
+
/**
Returns the parent of this category. Note that the parent of a
given category may change during the lifetime of the category.
-
+
<p>The root category will return <code>null</code>.
@since 1.2
@@ -575,10 +566,10 @@
return this.parent;
}
-
+
/**
- Returns the assigned {@link Level}, if any, for this Category.
-
+ Returns the assigned {@link Level}, if any, for this Category.
+
@return Level - the assigned Level, can be <code>null</code>.
*/
final
@@ -604,9 +595,9 @@
name is "root".
<p>Nevertheless, calling {@link #getInstance
- Category.getInstance("root")} does not retrieve the root category
+ Category.getInstance("root")} does not retrieve the root category
but a category just under root named "root".
-
+
<b>Deprecated</b> Use {@link Logger#getRootLogger()} instead.
*/
final
@@ -630,10 +621,10 @@
public
ResourceBundle getResourceBundle() {
for(Category c = this; c != null; c=c.parent) {
- if(c.resourceBundle != null)
+ if(c.resourceBundle != null)
return c.resourceBundle;
}
- // It might be the case that there is no resource bundle
+ // It might be the case that there is no resource bundle
return null;
}
@@ -667,8 +658,8 @@
}
}
}
-
- /**
+
+ /**
Log a message object with the {@link Level#INFO INFO} Level.
<p>This method first checks if this category is <code>INFO</code>
@@ -683,30 +674,30 @@
<p><b>WARNING</b> Note that passing a {@link Throwable} to this
method will print the name of the Throwable but no stack trace. To
print a stack trace use the {@link #info(Object, Throwable)} form
- instead.
-
+ instead.
+
@param message the message object to log */
public
void info(Object message) {
- if(repository.isDisabled(Level.INFO_INT))
- return;
+ if(repository.isDisabled(Level.INFO_INT))
+ return;
if(Level.INFO.isGreaterOrEqual(this.getEffectiveLevel()))
forcedLog(FQCN, Level.INFO, message, null);
}
-
- /**
+
+ /**
Log a message object with the <code>INFO</code> level including
the stack trace of the {@link Throwable} <code>t</code> passed as
parameter.
-
+
<p>See {@link #info(Object)} for more detailed information.
-
+
@param message the message object to log.
@param t the exception to log, including its stack trace. */
public
void info(Object message, Throwable t) {
if(repository.isDisabled(Level.INFO_INT))
- return;
+ return;
if(Level.INFO.isGreaterOrEqual(this.getEffectiveLevel()))
forcedLog(FQCN, Level.INFO, message, t);
}
@@ -714,9 +705,9 @@
/**
Is the appender passed as parameter attached to this category?
*/
- public
+ public
boolean isAttached(Appender appender) {
- if(appender == null || aai == null)
+ if(appender == null || aai == null)
return false;
else {
return aai.isAttached(appender);
@@ -726,25 +717,25 @@
/**
* Check whether this category is enabled for the <code>DEBUG</code>
* Level.
- *
+ *
* <p> This function is intended to lessen the computational cost of
* disabled log debug statements.
- *
+ *
* <p> For some <code>cat</code> Category object, when you write,
* <pre>
* cat.debug("This is entry number: " + i );
* </pre>
- *
+ *
* <p>You incur the cost constructing the message, concatenatiion in
* this case, regardless of whether the message is logged or not.
- *
+ *
* <p>If you are worried about speed, then you should write
* <pre>
- * if(cat.isDebugEnabled()) {
+ * if(cat.isDebugEnabled()) {
* cat.debug("This is entry number: " + i );
* }
* </pre>
- *
+ *
* <p>This way you will not incur the cost of parameter
* construction if debugging is disabled for <code>cat</code>. On
* the other hand, if the <code>cat</code> is debug enabled, you
@@ -753,28 +744,28 @@
* the <code>debug</code>. This is an insignificant overhead
* since evaluating a category takes about 1%% of the time it
* takes to actually log.
- *
+ *
* @return boolean - <code>true</code> if this category is debug
* enabled, <code>false</code> otherwise.
* */
public
boolean isDebugEnabled() {
if(repository.isDisabled( Level.DEBUG_INT))
- return false;
+ return false;
return Level.DEBUG.isGreaterOrEqual(this.getEffectiveLevel());
}
-
+
/**
Check whether this category is enabled for a given {@link
Level} passed as parameter.
See also {@link #isDebugEnabled}.
-
+
@return boolean True if this category is enabled for <code>level</code>.
*/
public
boolean isEnabledFor(Priority level) {
- if(repository.isDisabled(level.level))
+ if(repository.isDisabled(level.level))
return false;
return level.isGreaterOrEqual(this.getEffectiveLevel());
}
@@ -789,7 +780,7 @@
public
boolean isInfoEnabled() {
if(repository.isDisabled(Level.INFO_INT))
- return false;
+ return false;
return Level.INFO.isGreaterOrEqual(this.getEffectiveLevel());
}
@@ -798,7 +789,7 @@
Log a localized message. The user supplied parameter
<code>key</code> is replaced by its localized version from the
resource bundle.
-
+
@see #setResourceBundle
@since 0.8.4 */
@@ -820,28 +811,28 @@
/**
Log a localized and parameterized message. First, the user
supplied <code>key</code> is searched in the resource
- bundle. Next, the resulting pattern is formatted using
+ bundle. Next, the resulting pattern is formatted using
{@link MessageFormat#format(String,Object[])} method with the user
supplied object array <code>params</code>.
-
+
@since 0.8.4
*/
public
void l7dlog(Priority priority, String key, Object[] params, Throwable t) {
if(repository.isDisabled(priority.level)) {
return;
- }
+ }
if(priority.isGreaterOrEqual(this.getEffectiveLevel())) {
String pattern = getResourceBundleString(key);
String msg;
- if(pattern == null)
+ if(pattern == null)
msg = key;
- else
+ else
msg = java.text.MessageFormat.format(pattern, params);
forcedLog(FQCN, priority, msg, t);
}
}
-
+
/**
This generic form is intended to be used by wrappers.
*/
@@ -850,12 +841,12 @@
if(repository.isDisabled(priority.level)) {
return;
}
- if(priority.isGreaterOrEqual(this.getEffectiveLevel()))
+ if(priority.isGreaterOrEqual(this.getEffectiveLevel()))
forcedLog(FQCN, priority, message, t);
}
-
+
/**
- This generic form is intended to be used by wrappers.
+ This generic form is intended to be used by wrappers.
*/
public
void log(Priority priority, Object message) {
@@ -867,10 +858,10 @@
}
/**
-
+
This is the most generic printing method. It is intended to be
invoked by <b>wrapper</b> classes.
-
+
@param callerFQCN The wrapper class' fully qualified class name.
@param level The level of the logging request.
@param message The message of the logging request.
@@ -909,7 +900,7 @@
synchronized
public
void removeAppender(Appender appender) {
- if(appender == null || aai == null)
+ if(appender == null || aai == null)
return;
aai.removeAppender(appender);
}
@@ -925,7 +916,7 @@
if(name == null || aai == null) return;
aai.removeAppender(name);
}
-
+
/**
Set the additivity flag for this Category instance.
@since 0.8.1
@@ -948,7 +939,7 @@
<code>Level.DEBUG</code>, <code>Level.INFO</code>,
<code>Level.WARN</code>, <code>Level.ERROR</code>,
<code>Level.FATAL</code> as a parameter, you need to case them as
- Level.
+ Level.
<p>As in <pre> logger.setLevel((Level) Level.DEBUG); </pre>
@@ -959,7 +950,7 @@
this.level = level;
}
-
+
/**
Set the level of this Category.
@@ -989,7 +980,7 @@
Calling this method will <em>safely</em> close and remove all
appenders in all the categories including root contained in the
default hierachy.
-
+
<p>Some appenders such as {@link org.apache.log4j.net.SocketAppender}
and {@link AsyncAppender} need to be closed before the
application exists. Otherwise, pending logging events might be
@@ -998,7 +989,7 @@
<p>The <code>shutdown</code> method is careful to close nested
appenders before closing regular appenders. This is allows
configurations where a regular appender is attached to a category
- and again to a nested appender.
+ and again to a nested appender.
@deprecated Please use {@link LogManager#shutdown()} instead.
@@ -1010,8 +1001,8 @@
LogManager.shutdown();
}
-
- /**
+
+ /**
Log a message object with the {@link Level#WARN WARN} Level.
<p>This method first checks if this category is <code>WARN</code>
@@ -1027,30 +1018,30 @@
method will print the name of the Throwable but no stack trace. To
print a stack trace use the {@link #warn(Object, Throwable)} form
instead. <p>
-
+
@param message the message object to log. */
public
void warn(Object message) {
- if(repository.isDisabled( Level.WARN_INT))
- return;
+ if(repository.isDisabled( Level.WARN_INT))
+ return;
if(Level.WARN.isGreaterOrEqual(this.getEffectiveLevel()))
- forcedLog(FQCN, Level.WARN, message, null);
+ forcedLog(FQCN, Level.WARN, message, null);
}
-
- /**
+
+ /**
Log a message with the <code>WARN</code> level including the
stack trace of the {@link Throwable} <code>t</code> passed as
parameter.
-
+
<p>See {@link #warn(Object)} for more detailed information.
-
+
@param message the message object to log.
@param t the exception to log, including its stack trace. */
public
void warn(Object message, Throwable t) {
- if(repository.isDisabled(Level.WARN_INT))
- return;
+ if(repository.isDisabled(Level.WARN_INT))
+ return;
if(Level.WARN.isGreaterOrEqual(this.getEffectiveLevel()))
forcedLog(FQCN, Level.WARN, message, t);
}
1.22 +1 -9 jakarta-log4j/src/java/org/apache/log4j/BasicConfigurator.java
Index: BasicConfigurator.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/BasicConfigurator.java,v
retrieving revision 1.21
retrieving revision 1.22
diff -u -r1.21 -r1.22
--- BasicConfigurator.java 11 Feb 2002 16:14:33 -0000 1.21
+++ BasicConfigurator.java 24 Apr 2002 01:16:14 -0000 1.22
@@ -11,14 +11,6 @@
package org.apache.log4j;
-import org.apache.log4j.helpers.LogLog;
-import org.apache.log4j.helpers.Loader;
-import org.apache.log4j.helpers.OptionConverter;
-import org.apache.log4j.spi.LoggerRepository;
-import org.apache.log4j.spi.RendererSupport;
-import org.apache.log4j.or.ObjectRenderer;
-import org.apache.log4j.or.RendererMap;
-import java.util.Enumeration;
/**
Use this class to quickly configure the package.
@@ -61,7 +53,7 @@
Reset the default hierarchy to its defaut. It is equivalent to
calling
<code>Category.getDefaultHierarchy().resetConfiguration()</code>.
-
+
See {@link Hierarchy#resetConfiguration()} for more details. */
public
static
1.26 +30 -31 jakarta-log4j/src/java/org/apache/log4j/AsyncAppender.java
Index: AsyncAppender.java
===================================================================
RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/AsyncAppender.java,v
retrieving revision 1.25
retrieving revision 1.26
diff -u -r1.25 -r1.26
--- AsyncAppender.java 22 Jan 2002 23:01:37 -0000 1.25
+++ AsyncAppender.java 24 Apr 2002 01:16:14 -0000 1.26
@@ -13,7 +13,6 @@
import org.apache.log4j.Category;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.helpers.BoundedFIFO;
-import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.spi.AppenderAttachable;
import org.apache.log4j.helpers.AppenderAttachableImpl;
import org.apache.log4j.helpers.LogLog;
@@ -22,13 +21,13 @@
/**
The AsyncAppender lets users log events asynchronously. It uses a
bounded buffer to store logging events.
-
+
<p>The AsyncAppender will collect the events sent to it and then
dispatch them to all the appenders that are attached to it. You can
attach multiple appenders to an AsyncAppender.
<p>The AsyncAppender uses a separate thread to serve the events in
- its bounded buffer.
+ its bounded buffer.
<p>Refer to the results in {@link org.apache.log4j.performance.Logging}
for the impact of using this appender.
@@ -40,16 +39,16 @@
and <a href="xml/examples/doc-files/sample5.xml">sample5.xml</a>.
-
+
@author Ceki Gülcü
@since 0.9.1 */
-public class AsyncAppender extends AppenderSkeleton
+public class AsyncAppender extends AppenderSkeleton
implements AppenderAttachable {
-
+
/**
A string constant used in naming the option for setting the
location information flag. Current value of this string
- constant is <b>LocationInfo</b>.
+ constant is <b>LocationInfo</b>.
<p>Note that all option keys are case sensitive.
@@ -63,7 +62,7 @@
/**
A string constant used in naming the option for setting the size of the
internal buffer where logging events are stored until they are written.
- Current value of this string constant is <b>BufferSize</b>.
+ Current value of this string constant is <b>BufferSize</b>.
<p>Note that all option keys are case sensitive.
@@ -94,14 +93,14 @@
dispatcher = new Dispatcher(bf, this);
dispatcher.start();
}
-
- public
+
+ public
void addAppender(Appender newAppender) {
synchronized(aai) {
aai.addAppender(newAppender);
}
- }
+ }
public
void append(LoggingEvent event) {
@@ -113,7 +112,7 @@
event.getMDCCopy();
if(locationInfo) {
- event.getLocationInformation();
+ event.getLocationInformation();
}
synchronized(bf) {
while(bf.isFull()) {
@@ -129,8 +128,8 @@
}
}
}
-
- //cat.debug("About to put new event in buffer.");
+
+ //cat.debug("About to put new event in buffer.");
bf.put(event);
if(bf.wasEmpty()) {
//cat.debug("Notifying dispatcher to process events.");
@@ -142,16 +141,16 @@
/**
Close this <code>AsyncAppender</code> by interrupting the
dispatcher thread which will process all pending events before
- exiting.
+ exiting.
*/
- public
+ public
void close() {
synchronized(this) {
if(closed) // avoid multiple close, otherwise one gets NullPointerException
- return;
+ return;
closed = true;
}
-
+
// The following cannot be synchronized on "this" because the
// dispatcher synchronizes with "this" in its while loop. If we
// did synchronize we would systematically get deadlocks when
@@ -192,16 +191,16 @@
/**
Is the appender passed as parameter attached to this category?
*/
- public
+ public
boolean isAttached(Appender appender) {
return aai.isAttached(appender);
}
-
+
/**
The <code>AsyncAppender</code> does not require a layout. Hence,
this method always returns <code>false</code>. */
- public
+ public
boolean requiresLayout() {
return false;
}
@@ -212,7 +211,7 @@
aai.removeAllAppenders();
}
}
-
+
public
void removeAppender(Appender appender) {
@@ -243,8 +242,8 @@
void setLocationInfo(boolean flag) {
locationInfo = flag;
}
-
-
+
+
/**
The <b>BufferSize</b> option takes a non-negative integer
value. This integer value determines the maximum size of the
@@ -255,13 +254,13 @@
AsyncAppender, it is safe to set a buffer size smaller than the
{@link #DEFAULT_BUFFER_SIZE default buffer size} because
configurators guarantee that an appender cannot be used before
- being completely configured.
+ being completely configured.
*/
public
void setBufferSize(int size) {
bf.resize(size);
}
-
+
/**
Returns the current value of the <b>BufferSize</b> option.
*/
@@ -296,7 +295,7 @@
void close() {
synchronized(bf) {
- interrupted = true;
+ interrupted = true;
// We have a waiting dispacther if and only if bf.length is
// zero. In that case, we need to give it a death kiss.
if(bf.length() == 0) {
@@ -312,7 +311,7 @@
buffer to process. After having processed an event, we release
the monitor (variable bf) so that new events can be placed in the
buffer, instead of keeping the monitor and processing the remaining
- events in the buffer.
+ events in the buffer.
<p>Other approaches might yield better results.
@@ -323,12 +322,12 @@
//Category cat = Category.getInstance(Dispatcher.class.getName());
LoggingEvent event;
-
+
while(true) {
synchronized(bf) {
if(bf.length() == 0) {
// Exit loop if interrupted but only if the the buffer is empty.
- if(interrupted) {
+ if(interrupted) {
//cat.info("Exiting.");
return;
}
@@ -346,7 +345,7 @@
bf.notify();
}
} // synchronized
-
+
// The synchronization on parent is necessary to protect against
// operations on the aai object of the parent
synchronized(container.aai) {