apache-log4j1.2-1.2.17.orig/0000755000175000017500000000000012126647423013773 5ustar tonytonyapache-log4j1.2-1.2.17.orig/build.xml0000644000175000017500000007767111751454714015640 0ustar tonytony These are the targets supported by this ANT build scpript: build - compile all project files, if a certain library is missing, then the compilation of its dependents are skipped. javadoc - build project javadoc files jar - build log4j-core and log4j jar files dist - will create a complete distribution in dist/ Setting the env variable NO_JAVADOC will build the distribution without running the javadoc target. release - will create a complete distribution in dist/ using stricter settings for public distribution.
clirr-core-${clirr.version}.jar not in maven repo. Run mvn clirr:check to download. bcel-${bcel.version}.jar not in maven repo. Run mvn clirr:check to download. log4j-${reference.version}.jar not in maven repo. Run mvn clirr:check to download.
apache-log4j1.2-1.2.17.orig/NOTICE0000644000175000017500000000024111751454714014676 0ustar tonytonyApache log4j Copyright 2010 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/). apache-log4j1.2-1.2.17.orig/examples/0000755000175000017500000000000012126647422015610 5ustar tonytonyapache-log4j1.2-1.2.17.orig/examples/package.html0000644000175000017500000000346511751454714020104 0ustar tonytony

Example usage of log4j including source code.

Note that class files for the example code is not included in any of the distributed log4j jar files. You will have to add the directory /dir-where-you-unpacked-log4j/classes to your classpath before trying out the examples.

This package's shows how log4j can be used to output log statements.


Last modified: Fri May 5 10:20:04 MDT 2000 apache-log4j1.2-1.2.17.orig/examples/sort3.properties0000644000175000017500000000347011751454714021007 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # An example log4j configuration file that directs its logging output # to a SocketAppender. The SocketAppender is configuted to send its # output to a server running on the localhost port number 12345. # To test this example, you must start a log4j server with the command # # # java org.apache.log4j.net.SocketServer 12345 configurationFile directory/ # # # For the general syntax of property based configuration files see # the documenation of org.apache.log4j.PropertyConfigurator. # The root logger uses the appender called A1. log4j.rootLogger=DEBUG, A1 # A1 is set to be a SocketAppender sending its output to the server running on the local host, port 12345. log4j.appender.A1=org.apache.log4j.net.SocketAppender log4j.appender.A1.Port=12345 log4j.appender.A1.RemoteHost=localhost # In this example, we are not interested in INNER loop or SWAP # messages. You might try to set INNER and SWAP to DEBUG for more # verbose output. log4j.logger.org.apache.log4j.examples.SortAlgo.INNER=INFO log4j.logger.org.apache.log4j.examples.SortAlgo.SWAP=INFO apache-log4j1.2-1.2.17.orig/examples/factor.html0000644000175000017500000001311111751454714017754 0ustar tonytony

Log4j output of two near-simultaneous requests

Here is the logged output when two clients ask to factor two integers near-simultanesouly. The client on the host 128.178.50.84 asks to factor the prime number 359. The client on the host 9.4.2.196 asks to factor the number 347 (also a prime).

The NDC is placed between parantheses in bold. The NDC information consists of the client's host and the number to factor. Since the two requests have distinct NDCs, their output can be easily separated.

0      INFO  [main] () - NumberCruncherServer bound and ready to serve.
276493 INFO  [RMI TCP Connection(7)-128.178.50.84] (128.178.50.84 359) - Beginning to factor.
276495 DEBUG [RMI TCP Connection(7)-128.178.50.84] (128.178.50.84 359) - Trying to see if 2 is a factor.
276699 DEBUG [RMI TCP Connection(7)-128.178.50.84] (128.178.50.84 359) - Trying to see if 3 is a factor.
276908 DEBUG [RMI TCP Connection(7)-128.178.50.84] (128.178.50.84 359) - Trying to see if 4 is a factor.
276983 INFO  [RMI TCP Connection(8)-9.4.2.196] (9.4.2.196 347) - Beginning to factor.
276984 DEBUG [RMI TCP Connection(8)-9.4.2.196] (9.4.2.196 347) - Trying to see if 2 is a factor.
277115 DEBUG [RMI TCP Connection(7)-128.178.50.84] (128.178.50.84 359) - Trying to see if 5 is a factor.
277188 DEBUG [RMI TCP Connection(8)-9.4.2.196] (9.4.2.196 347) - Trying to see if 3 is a factor.
277318 DEBUG [RMI TCP Connection(7)-128.178.50.84] (128.178.50.84 359) - Trying to see if 6 is a factor.
277398 DEBUG [RMI TCP Connection(8)-9.4.2.196] (9.4.2.196 347) - Trying to see if 4 is a factor.
277520 DEBUG [RMI TCP Connection(7)-128.178.50.84] (128.178.50.84 359) - Trying to see if 7 is a factor.
277605 DEBUG [RMI TCP Connection(8)-9.4.2.196] (9.4.2.196 347) - Trying to see if 5 is a factor.
277728 DEBUG [RMI TCP Connection(7)-128.178.50.84] (128.178.50.84 359) - Trying to see if 8 is a factor.
277808 DEBUG [RMI TCP Connection(8)-9.4.2.196] (9.4.2.196 347) - Trying to see if 6 is a factor.
277931 DEBUG [RMI TCP Connection(7)-128.178.50.84] (128.178.50.84 359) - Trying to see if 9 is a factor.
278019 DEBUG [RMI TCP Connection(8)-9.4.2.196] (9.4.2.196 347) - Trying to see if 7 is a factor.
278138 DEBUG [RMI TCP Connection(7)-128.178.50.84] (128.178.50.84 359) - Trying to see if 10 is a factor.
278228 DEBUG [RMI TCP Connection(8)-9.4.2.196] (9.4.2.196 347) - Trying to see if 8 is a factor.
278348 DEBUG [RMI TCP Connection(7)-128.178.50.84] (128.178.50.84 359) - Trying to see if 11 is a factor.
278438 DEBUG [RMI TCP Connection(8)-9.4.2.196] (9.4.2.196 347) - Trying to see if 9 is a factor.
278559 DEBUG [RMI TCP Connection(7)-128.178.50.84] (128.178.50.84 359) - Trying to see if 12 is a factor.
278648 DEBUG [RMI TCP Connection(8)-9.4.2.196] (9.4.2.196 347) - Trying to see if 10 is a factor.
278768 DEBUG [RMI TCP Connection(7)-128.178.50.84] (128.178.50.84 359) - Trying to see if 13 is a factor.
278858 DEBUG [RMI TCP Connection(8)-9.4.2.196] (9.4.2.196 347) - Trying to see if 11 is a factor.
278970 DEBUG [RMI TCP Connection(7)-128.178.50.84] (128.178.50.84 359) - Trying to see if 14 is a factor.
279068 DEBUG [RMI TCP Connection(8)-9.4.2.196] (9.4.2.196 347) - Trying to see if 12 is a factor.
279178 DEBUG [RMI TCP Connection(7)-128.178.50.84] (128.178.50.84 359) - Trying to see if 15 is a factor.
279270 DEBUG [RMI TCP Connection(8)-9.4.2.196] (9.4.2.196 347) - Trying to see if 13 is a factor.
279387 DEBUG [RMI TCP Connection(7)-128.178.50.84] (128.178.50.84 359) - Trying to see if 16 is a factor.
279478 DEBUG [RMI TCP Connection(8)-9.4.2.196] (9.4.2.196 347) - Trying to see if 14 is a factor.
279598 DEBUG [RMI TCP Connection(7)-128.178.50.84] (128.178.50.84 359) - Trying to see if 17 is a factor.
279688 DEBUG [RMI TCP Connection(8)-9.4.2.196] (9.4.2.196 347) - Trying to see if 15 is a factor.
279808 DEBUG [RMI TCP Connection(7)-128.178.50.84] (128.178.50.84 359) - Trying to see if 18 is a factor.
279898 DEBUG [RMI TCP Connection(8)-9.4.2.196] (9.4.2.196 347) - Trying to see if 16 is a factor.
280018 INFO  [RMI TCP Connection(7)-128.178.50.84] (128.178.50.84 359) - Found factor 359
280108 DEBUG [RMI TCP Connection(8)-9.4.2.196] (9.4.2.196 347) - Trying to see if 17 is a factor.
280318 DEBUG [RMI TCP Connection(8)-9.4.2.196] (9.4.2.196 347) - Trying to see if 18 is a factor.
280520 INFO  [RMI TCP Connection(8)-9.4.2.196] (9.4.2.196 347) - Found factor 347

Last modified: Fri May 5 10:36:05 MDT 2000 apache-log4j1.2-1.2.17.orig/examples/SortAlgo.java0000644000175000017500000000547011751454714020216 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples; import org.apache.log4j.Logger; import org.apache.log4j.NDC; /** Example code for log4j to viewed in conjunction with the {@link examples.Sort Sort} class.

SortAlgo uses the bubble sort algorithm to sort an integer array. See also its source code. @author Ceki Gülcü */ public class SortAlgo { final static String className = SortAlgo.class.getName(); final static Logger LOG = Logger.getLogger(className); final static Logger OUTER = Logger.getLogger(className + ".OUTER"); final static Logger INNER = Logger.getLogger(className + ".INNER"); final static Logger DUMP = Logger.getLogger(className + ".DUMP"); final static Logger SWAP = Logger.getLogger(className + ".SWAP"); int[] intArray; SortAlgo(int[] intArray) { this.intArray = intArray; } void bubbleSort() { LOG.info( "Entered the sort method."); for(int i = intArray.length -1; i >= 0 ; i--) { NDC.push("i=" + i); OUTER.debug("in outer loop."); for(int j = 0; j < i; j++) { NDC.push("j=" + j); // It is poor practice to ship code with log staments in tight loops. // We do it anyway in this example. INNER.debug( "in inner loop."); if(intArray[j] > intArray[j+1]) swap(j, j+1); NDC.pop(); } NDC.pop(); } } void dump() { if(! (this.intArray instanceof int[])) { DUMP.error("Tried to dump an uninitialized array."); return; } DUMP.info("Dump of integer array:"); for(int i = 0; i < this.intArray.length; i++) { DUMP.info("Element [" + i + "]=" + this.intArray[i]); } } void swap(int l, int r) { // It is poor practice to ship code with log staments in tight // loops or code called potentially millions of times. SWAP.debug( "Swapping intArray["+l+"]=" + intArray[l] + " and intArray["+r+"]=" + intArray[r]); int temp = this.intArray[l]; this.intArray[l] = this.intArray[r]; this.intArray[r] = temp; } } apache-log4j1.2-1.2.17.orig/examples/sort4.properties0000644000175000017500000000366211751454714021013 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Attach appender A1 to root. Set root level to Level.DEBUG. log4j.rootLogger=DEBUG, A1 # A1 is set to be a FileAppender sending its output to # System.out. However, only error messages and above will be printed # in A1 because A1's threshold is set to Level.ERROR. # The fact that the root level is set to Prority.DEBUG only influences # log requests made to the root logger. It has no influence on the # *appenders* attached to root. log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.Threshold=ERROR log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%p [%t] %c{2} (%M:%L) - %m%n # Set the level of the logger named "org.apache.log4j.examples" to # Level.INFO, attach appender A2. log4j.logger.org.apache.log4j.examples=INFO, A2 # Appender A2 writes to the file "test" in user's home. log4j.appender.A2=org.apache.log4j.FileAppender log4j.appender.A2.File=${user.home}/test # Truncate 'test' if it aleady exists. log4j.appender.A2.Append=false # Appender A2 uses the PatternLayout. log4j.appender.A2.layout=org.apache.log4j.PatternLayout log4j.appender.A2.layout.ConversionPattern=%5r %-5p [%t] %c{2} - %m%n apache-log4j1.2-1.2.17.orig/examples/Sort.java0000644000175000017500000000623711751454714017415 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.Logger; /** Example code for log4j to viewed in conjunction with the {@link examples.SortAlgo SortAlgo} class.

This program expects a configuration file name as its first argument, and the size of the array to sort as the second and last argument. See its source code for more details.

Play around with different values in the configuration file and watch the changing behavior.

Example configuration files can be found in sort1.properties, sort2.properties, sort3.properties and sort4.properties are supplied with the package.

If you are also interested in logging performance, then have look at the {@link org.apache.log4j.performance.Logging} class. @author Ceki Gülcü */ public class Sort { static Logger logger = Logger.getLogger(Sort.class.getName()); public static void main(String[] args) { if(args.length != 2) { usage("Incorrect number of parameters."); } int arraySize = -1; try { arraySize = Integer.valueOf(args[1]).intValue(); if(arraySize <= 0) usage("Negative array size."); } catch(java.lang.NumberFormatException e) { usage("Could not number format ["+args[1]+"]."); } PropertyConfigurator.configure(args[0]); int[] intArray = new int[arraySize]; logger.info("Populating an array of " + arraySize + " elements in" + " reverse order."); for(int i = arraySize -1 ; i >= 0; i--) { intArray[i] = arraySize - i - 1; } SortAlgo sa1 = new SortAlgo(intArray); sa1.bubbleSort(); sa1.dump(); // We intentionally initilize sa2 with null. SortAlgo sa2 = new SortAlgo(null); logger.info("The next log statement should be an error message."); sa2.dump(); logger.info("Exiting main method."); } static void usage(String errMsg) { System.err.println(errMsg); System.err.println("\nUsage: java org.apache.examples.Sort " + "configFile ARRAY_SIZE\n"+ "where configFile is a configuration file\n"+ " ARRAY_SIZE is a positive integer.\n"); System.exit(1); } } apache-log4j1.2-1.2.17.orig/examples/MyPatternLayout.java0000644000175000017500000000376111751454714021606 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples; import org.apache.log4j.*; import org.apache.log4j.helpers.PatternParser; /** Example showing how to extend PatternLayout to recognize additional conversion characters.

In this case MyPatternLayout recognizes %# conversion pattern. It outputs the value of an internal counter which is also incremented at each call.

See source code for more details. @see MyPatternParser @see org.apache.log4j.PatternLayout @author Anders Kristensen */ public class MyPatternLayout extends PatternLayout { public MyPatternLayout() { this(DEFAULT_CONVERSION_PATTERN); } public MyPatternLayout(String pattern) { super(pattern); } public PatternParser createPatternParser(String pattern) { return new MyPatternParser( pattern == null ? DEFAULT_CONVERSION_PATTERN : pattern); } public static void main(String[] args) { Layout layout = new MyPatternLayout("[counter=%.10#] - %m%n"); Logger logger = Logger.getLogger("some.cat"); logger.addAppender(new ConsoleAppender(layout, ConsoleAppender.SYSTEM_OUT)); logger.debug("Hello, log"); logger.info("Hello again..."); } } apache-log4j1.2-1.2.17.orig/examples/sort1.properties0000644000175000017500000000346511751454714021011 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # An example log4j configuration file that outputs to System.out. The # output information consists of relative time, log level, thread # name, logger name, nested diagnostic context and the message in that # order. # For the general syntax of property based configuration files see the # documenation of org.apache.log4j.PropertyConfigurator. log4j.rootLogger=DEBUG, A1 # A1 is set to be a ConsoleAppender which outputs to System.out. log4j.appender.A1=org.apache.log4j.ConsoleAppender # A1 uses PatternLayout. log4j.appender.A1.layout=org.apache.log4j.PatternLayout # The conversion pattern uses format specifiers. You might want to # change the pattern an watch the output format change. log4j.appender.A1.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n # In this example, we are not really interested in INNER loop or SWAP # messages. See the effects of uncommenting and changing the levels of # the following loggers. # log4j.logger.org.apache.log4j.examples.SortAlgo.INNER=WARN # log4j.logger.org.apache.log4j.examples.SortAlgo.SWAP=WARN apache-log4j1.2-1.2.17.orig/examples/mycat.bad0000644000175000017500000000256111751454714017404 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # The usual stuff. Note that A1 is configured in root not in "some.cat" log4j.rootLogger=DEBUG, A1 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%5p [%t] %c - %m%n # Set the priority of "some.cat" to TRACE (defined in # examples.customLevel.XLevel). This will actually have the side # effect of instanciating a logger object having the name "some.cat" # this will cause a ClassCastException if the logger object is cast # as a MyLogger object. log4j.logger.some.cat=TRACE#examples.customLevel.XLevel apache-log4j1.2-1.2.17.orig/examples/Trivial.java0000644000175000017500000000512411751454714020072 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples; import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.NDC; /** View the source code of this a trivial usage example. Running java examples.Trivial should output something similar to:

      0    INFO  [main] examples.Trivial (Client #45890) - Awake awake. Put on thy strength.
      15   DEBUG [main] examples.Trivial (Client #45890 DB) - Now king David was old.
      278  INFO  [main] examples.Trivial$InnerTrivial (Client #45890) - Entered foo.
      293  INFO  [main] examples.Trivial (Client #45890) - Exiting Trivial.   
   

The increasing numbers at the beginning of each line are the times elapsed since the start of the program. The string between the parentheses is the nested diagnostic context.

See {@link Sort} and {@link SortAlgo} for sligtly more elaborate examples.

Note thent class files for the example code is not included in any of the distributed log4j jar files. You will have to add the directory /dir-where-you-unpacked-log4j/classes to your classpath before trying out the examples. */ public class Trivial { static Logger logger = Logger.getLogger(Trivial.class); public static void main(String[] args) { BasicConfigurator.configure(); NDC.push("Client #45890"); logger.info("Awake awake. Put on thy strength."); Trivial.foo(); InnerTrivial.foo(); logger.info("Exiting Trivial."); } static void foo() { NDC.push("DB"); logger.debug("Now king David was old."); NDC.pop(); } static class InnerTrivial { static Logger logger = Logger.getLogger(InnerTrivial.class); static void foo() { logger.info("Entered foo."); } } } apache-log4j1.2-1.2.17.orig/examples/NumberCruncherServer.java0000644000175000017500000001307311751454714022573 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples; import java.rmi.server.UnicastRemoteObject; import java.rmi.RemoteException; import java.rmi.Naming; import java.util.Vector; import org.apache.log4j.Logger; import org.apache.log4j.NDC; import org.apache.log4j.PropertyConfigurator; /** A simple {@link NumberCruncher} implementation that logs its progress when factoring numbers. The purpose of the whole exercise is to show the use of nested diagnostic contexts in order to distinguish the log output from different client requests.

   Usage: java org.apache.log4j.examples.NumberCruncherServer configFile
          where configFile is a log4j configuration file.
   
We supply a simple config file factor.lcf for directing log output to the file factor.log.

Try it yourself by starting a NumberCruncherServer and make queries from multiple {@link NumberCruncherClient NumberCruncherClients} to factor numbers.

Sample output shows the log output when two clients connect to the server near simultaneously.

See source code of NumberCruncherServer for more details.

Note that class files for the example code is not included in any of the distributed log4j jar files. You will have to add the directory /dir-where-you-unpacked-log4j/classes to your classpath before trying out the examples. */ public class NumberCruncherServer extends UnicastRemoteObject implements NumberCruncher { private static final long serialVersionUID = 2626753561969426769L; static Logger logger = Logger.getLogger(NumberCruncherServer.class); public NumberCruncherServer() throws RemoteException { } public int[] factor(int number) throws RemoteException { // The client's host is an important source of information. try { NDC.push(getClientHost()); } catch(java.rmi.server.ServerNotActiveException e) { // we are being called from same VM NDC.push("localhost"); } // The information contained within the request is another source of // distinctive information. It might reveal the users name, date of request, // request ID etc. In servlet type environments, much information is // contained in cookies. NDC.push(String.valueOf(number)); logger.info("Beginning to factor."); if(number <= 0) { throw new IllegalArgumentException(number+" is not a positive integer."); } else if(number == 1) return new int[] {1}; Vector factors = new Vector(); int n = number; for(int i = 2; (i <= n) && (i*i <= number); i++) { // It is bad practice to place log requests within tight loops. // It is done here to show interleaved log output from // different requests. logger.debug("Trying to see if " + i + " is a factor."); if((n % i) == 0) { logger.info("Found factor "+i); factors.addElement(new Integer(i)); do { n /= i; } while((n % i) == 0); } // Placing artificial delays in tight-loops will also lead to sub-optimal // resuts. :-) delay(100); } if(n != 1) { logger.info("Found factor "+n); factors.addElement(new Integer(n)); } int len = factors.size(); int[] result = new int[len]; for(int i = 0; i < len; i++) { result[i] = ((Integer) factors.elementAt(i)).intValue(); } // Before leaving a thread we call NDC.remove. This deletes the reference // to the thread in the internal hash table. Version 0.8.5 introduces a // a lazy removal mechanism in case you forget to call remove when // exiting a thread. See the java documentation in NDC.remove for further // details. NDC.remove(); return result; } static void usage(String msg) { System.err.println(msg); System.err.println( "Usage: java org.apache.log4j.examples.NumberCruncherServer configFile\n" + " where configFile is a log4j configuration file."); System.exit(1); } public static void delay(int millis) { try{Thread.sleep(millis);} catch(InterruptedException e) {} } public static void main(String[] args) { if(args.length != 1) usage("Wrong number of arguments."); NumberCruncherServer ncs; PropertyConfigurator.configure(args[0]); try { ncs = new NumberCruncherServer(); Naming.rebind("Factor", ncs); logger.info("NumberCruncherServer bound and ready to serve."); } catch(Exception e) { logger.error("Could not bind NumberCruncherServer.", e); return; } NumberCruncherClient.loop(ncs); } } apache-log4j1.2-1.2.17.orig/examples/subclass/0000755000175000017500000000000012126647422017427 5ustar tonytonyapache-log4j1.2-1.2.17.orig/examples/subclass/MyLoggerTest.java0000644000175000017500000000553011751454714022665 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples.subclass; import org.apache.log4j.*; import org.apache.log4j.xml.DOMConfigurator; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.helpers.LogLog; /** A simple example showing logger subclassing.

The example should make it clear that subclasses follow the hierarchy. You should also try running this example with a bad and good configuration file samples.

See source code for more details. */ public class MyLoggerTest { /** When called wihtout arguments, this program will just print

       DEBUG [main] some.cat - Hello world.
     
and exit. However, it can be called with a configuration file in XML or properties format. */ static public void main(String[] args) { if(args.length == 0) { // Note that the appender is added to root but that the log // request is made to an instance of MyLogger. The output still // goes to System.out. Logger root = Logger.getRootLogger(); Layout layout = new PatternLayout("%p [%t] %c (%F:%L) - %m%n"); root.addAppender(new ConsoleAppender(layout, ConsoleAppender.SYSTEM_OUT)); } else if(args.length == 1) { if(args[0].endsWith("xml")) { DOMConfigurator.configure(args[0]); } else { PropertyConfigurator.configure(args[0]); } } else { usage("Incorrect number of parameters."); } try { MyLogger c = (MyLogger) MyLogger.getLogger("some.cat"); c.trace("Hello"); c.debug("Hello"); } catch(ClassCastException e) { LogLog.error("Did you forget to set the factory in the config file?", e); } } static void usage(String errMsg) { System.err.println(errMsg); System.err.println("\nUsage: "+MyLogger.class.getName() + "[configFile]\n" + " where *configFile* is an optional configuration file, "+ "either in properties or XML format."); System.exit(1); } } apache-log4j1.2-1.2.17.orig/examples/subclass/MyLogger.java0000644000175000017500000000425611751454714022031 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples.subclass; import org.apache.log4j.*; import examples.customLevel.XLevel; /** A simple example showing logger subclassing.

See source code for more details.

See {@link MyLoggerTest} for a usage example. */ public class MyLogger extends Logger { // It's usually a good idea to add a dot suffix to the fully // qualified class name. This makes caller localization to work // properly even from classes that have almost the same fully // qualified class name as MyLogger, e.g. MyLoggerTest. static String FQCN = MyLogger.class.getName() + "."; // It's enough to instantiate a factory once and for all. private static MyLoggerFactory myFactory = new MyLoggerFactory(); /** Just calls the parent constuctor. */ public MyLogger(String name) { super(name); } /** Overrides the standard debug method by appending " world" at the end of each message. */ public void debug(Object message) { super.log(FQCN, Level.DEBUG, message + " world.", null); } /** This method overrides {@link Logger#getLogger} by supplying its own factory type as a parameter. */ public static Logger getLogger(String name) { return Logger.getLogger(name, myFactory); } public void trace(Object message) { super.log(FQCN, XLevel.TRACE, message, null); } } apache-log4j1.2-1.2.17.orig/examples/subclass/MyLoggerFactory.java0000644000175000017500000000256411751454714023361 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples.subclass; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggerFactory; /** A factory that makes new {@link MyLogger} objects. See source code for more details. @author Ceki Gülcü */ public class MyLoggerFactory implements LoggerFactory { /** The constructor should be public as it will be called by configurators in different packages. */ public MyLoggerFactory() { } public Logger makeNewLoggerInstance(String name) { return new MyLogger(name); } } apache-log4j1.2-1.2.17.orig/examples/customLevel/0000755000175000017500000000000012126647422020112 5ustar tonytonyapache-log4j1.2-1.2.17.orig/examples/customLevel/XLevel.java0000644000175000017500000000460211751454714022161 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples.customLevel; import org.apache.log4j.Level; /** This class introduces a new level level called TRACE. TRACE has lower level than DEBUG. */ public class XLevel extends Level { private static final long serialVersionUID = 2626753561969426769L; static public final int TRACE_INT = Level.DEBUG_INT - 1; static public final int LETHAL_INT = Level.FATAL_INT + 1; private static String TRACE_STR = "TRACE"; private static String LETHAL_STR = "LETHAL"; public static final XLevel TRACE = new XLevel(TRACE_INT, TRACE_STR, 7); public static final XLevel LETHAL = new XLevel(LETHAL_INT, LETHAL_STR, 0); protected XLevel(int level, String strLevel, int syslogEquiv) { super(level, strLevel, syslogEquiv); } /** Convert the string passed as argument to a level. If the conversion fails, then this method returns {@link #TRACE}. */ public static Level toLevel(String sArg) { return (Level) toLevel(sArg, XLevel.TRACE); } public static Level toLevel(String sArg, Level defaultValue) { if(sArg == null) { return defaultValue; } String stringVal = sArg.toUpperCase(); if(stringVal.equals(TRACE_STR)) { return XLevel.TRACE; } else if(stringVal.equals(LETHAL_STR)) { return XLevel.LETHAL; } return Level.toLevel(sArg, (Level) defaultValue); } public static Level toLevel(int i) throws IllegalArgumentException { switch(i) { case TRACE_INT: return XLevel.TRACE; case LETHAL_INT: return XLevel.LETHAL; } return Level.toLevel(i); } } apache-log4j1.2-1.2.17.orig/examples/lf5/0000755000175000017500000000000012126647422016276 5ustar tonytonyapache-log4j1.2-1.2.17.orig/examples/lf5/InitUsingMultipleAppenders/0000755000175000017500000000000012126647422023565 5ustar tonytonyapache-log4j1.2-1.2.17.orig/examples/lf5/InitUsingMultipleAppenders/example.properties0000644000175000017500000000420411751454714027341 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # For the general syntax of property based configuration files see the # documenation of org.apache.log4j.PropertyConfigurator. # The root category uses two appenders called A1 and R. Since no priority is # specified, the root category assumes the default priority for root # which is DEBUG in log4j. The root category is the only category that # has a default priority. All other categories need not be assigned a # priority in which case they inherit their priority from the # hierarchy. log4j.rootCategory=, A1, R # A1 is set to be a LF5Appender which outputs to a swing # logging console. log4j.appender.A1=org.apache.log4j.lf5.LF5Appender # R is the RollingFileAppender that outputs to a rolling log # file called rolling_log_file.log. log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.File=rolling_log_file.log # Define a pattern layout for the file. # For more information on conversion characters (i.e. d,p,t,c,l,m,n) # please see the PatternLayout class of the Log4j API. log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=[slf5s.start]%d{DATE}[slf5s.DATE]%n%p[slf5s.PRIORITY]%n%x[slf5s.NDC]%n%t[slf5s.THREAD]%n%c[slf5s.CATEGORY]%n%l[slf5s.LOCATION]%n%m[slf5s.MESSAGE]%n%n # Set the max size of the file and the number of backup files log4j.appender.R.MaxFileSize=100KB log4j.appender.R.MaxBackupIndex=1apache-log4j1.2-1.2.17.orig/examples/lf5/InitUsingMultipleAppenders/InitUsingMultipleAppenders.java0000644000175000017500000001372311751454714031730 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples.lf5.InitUsingMultipleAppenders; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import java.io.IOException; import java.net.URL; /** * This example shows how to use LogFactor5 with other Log4J appenders * (In this case the RollingFileAppender). * * The following lines can be added to the log4j.properties file or a * standard Java properties file. * * # Two appenders are registered with the root of the Category tree. * * log4j.rootCategory=, A1, R * * # A1 is set to be a LF5Appender which outputs to a swing * # logging console. * * log4j.appender.A1=org.apache.log4j.lf5.LF5Appender * * # R is the RollingFileAppender that outputs to a rolling log * # file called rolling_log_file.log. * * log4j.appender.R=org.apache.log4j.RollingFileAppender * log4j.appender.R.File=rolling_log_file.log * * log4j.appender.R.layout=org.apache.log4j.PatternLayout * log4j.appender.R.layout.ConversionPattern=Date - %d{DATE}%nPriority * - %p%nThread - %t%nCategory - %c%nLocation - %l%nMessage - %m%n%n * log4j.appender.R.MaxFileSize=100KB * log4j.appender.R.MaxBackupIndex=1 * * To make this example work, either run the InitUsingMultipleAppenders.bat * file located in the examples folder or run it at the command line. If you * are running the example at the command line, you must ensure that the * example.properties file is in your classpath. * * @author Brent Sprecher * @author Brad Marlborough */ // Contributed by ThoughtWorks Inc. public class InitUsingMultipleAppenders { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- private static Logger logger = Logger.getLogger(InitUsingMultipleAppenders.class); //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public static void main(String argv[]) { // Use a PropertyConfigurator to initialize from a property file. String resource = "/examples/lf5/InitUsingMultipleAppenders/example.properties"; URL configFileResource = InitUsingMultipleAppenders.class.getResource(resource); PropertyConfigurator.configure(configFileResource); // Add a bunch of logging statements ... logger.debug("Hello, my name is Homer Simpson."); logger.debug("Hello, my name is Lisa Simpson."); logger.debug("Hello, my name is Marge Simpson."); logger.debug("Hello, my name is Bart Simpson."); logger.debug("Hello, my name is Maggie Simpson."); logger.info("We are the Simpsons!"); logger.info("Mmmmmm .... Chocolate."); logger.info("Homer likes chocolate"); logger.info("Doh!"); logger.info("We are the Simpsons!"); logger.warn("Bart: I am through with working! Working is for chumps!" + "Homer: Son, I'm proud of you. I was twice your age before " + "I figured that out."); logger.warn("Mmm...forbidden donut."); logger.warn("D'oh! A deer! A female deer!"); logger.warn("Truly, yours is a butt that won't quit." + "- Bart, writing as Woodrow to Ms. Krabappel."); logger.error("Dear Baby, Welcome to Dumpsville. Population: you."); logger.error("Dear Baby, Welcome to Dumpsville. Population: you.", new IOException("Dumpsville, USA")); logger.error("Mr. Hutz, are you aware you're not wearing pants?"); logger.error("Mr. Hutz, are you aware you're not wearing pants?", new IllegalStateException("Error !!")); logger.fatal("Eep."); logger.fatal("Mmm...forbidden donut.", new SecurityException("Fatal Exception")); logger.fatal("D'oh! A deer! A female deer!"); logger.fatal("Mmmmmm .... Chocolate.", new SecurityException("Fatal Exception")); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/examples/lf5/InitUsingDefaultConfigurator/0000755000175000017500000000000012126647422024077 5ustar tonytony././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootapache-log4j1.2-1.2.17.orig/examples/lf5/InitUsingDefaultConfigurator/InitUsingDefaultConfigurator.javaapache-log4j1.2-1.2.17.orig/examples/lf5/InitUsingDefaultConfigurator/InitUsingDefaultConfigurator.j0000644000175000017500000001164011751454714032060 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples.lf5.InitUsingDefaultConfigurator; import org.apache.log4j.Logger; import org.apache.log4j.NDC; import org.apache.log4j.lf5.DefaultLF5Configurator; import java.io.IOException; /** * This class is a simple example of how to configure the LogFactor5 * logging window using the DefaultLF5Configurator. * * The DefaultLF5Configurator uses a default configuration file stored * in the log4j.jar in order to provide a default configuration for * the LF5Appender. * * @author Brent Sprecher */ // Contributed by ThoughtWorks Inc. public class InitUsingDefaultConfigurator { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- private static Logger logger = Logger.getLogger(InitUsingDefaultConfigurator.class); //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public static void main(String[] args) throws IOException { // Configure the LF5Appender using the DefaultLF5Configurator. This // will add the LF5Appender to the root of the Category tree. DefaultLF5Configurator.configure(); // Add an NDC to demonstrate how NDC information is output. NDC.push("#23856"); // Log some information. for (int i = 0; i < 10; i++) { logger.debug("Hello, my name is Homer Simpson."); logger.info("Mmmmmm .... Chocolate."); logger.warn("Mmm...forbidden donut."); } // Clean up NDC NDC.pop(); NDC.remove(); NDC.push("Another NDC"); // Log some information. logger.fatal("Hello, my name is Bart Simpson."); logger.error("Hi diddly ho good neighbour."); // Clean up NDC NDC.pop(); NDC.remove(); // Call methods on both classes. InitUsingDefaultConfigurator.foo(); InnerInitUsingDefaultConfigurator.foo(); logger.info("Exiting InitUsingDefaultConfigurator."); } public static void foo() { logger.debug("Entered foo in InitUsingDefaultConfigurator class"); NDC.push("#123456"); logger.debug("Hello, my name is Marge Simpson."); logger.info("D'oh!! A deer! A female deer."); // Clean up NDC NDC.pop(); NDC.remove(); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- public static class InnerInitUsingDefaultConfigurator { static Logger logger = Logger.getLogger(InnerInitUsingDefaultConfigurator.class.getName()); static void foo() throws IOException { // Configure the LF5Appender again. You can call // DefaultLF5Configurator.configure() as often as you want // without unexpected behavior. DefaultLF5Configurator.configure(); logger.info("Entered foo in InnerInitUsingDefaultConfigurator class."); } } } apache-log4j1.2-1.2.17.orig/examples/lf5/InitUsingLog4JProperties/0000755000175000017500000000000012126647422023124 5ustar tonytonyapache-log4j1.2-1.2.17.orig/examples/lf5/InitUsingLog4JProperties/log4j.properties0000644000175000017500000000267311751454714026274 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # For the general syntax of property based configuration files see the # documenation of org.apache.log4j.PropertyConfigurator. # The root category uses the appender called A1. Since no priority is # specified, the root category assumes the default priority for root # which is DEBUG in log4j. The root category is the only category that # has a default priority. All other categories need not be assigned a # priority in which case they inherit their priority from the # hierarchy. log4j.rootCategory=, A1 # A1 is set to be a LF5Appender which outputs to a swing # logging console. log4j.appender.A1=org.apache.log4j.lf5.LF5Appender log4j.appender.A1.MaxNumberOfRecords=1000 apache-log4j1.2-1.2.17.orig/examples/lf5/InitUsingLog4JProperties/InitUsingLog4JProperties.java0000644000175000017500000001214211751454714030620 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples.lf5.InitUsingLog4JProperties; import org.apache.log4j.Logger; import java.io.IOException; /** * This class is a simple example of how to use the LogFactor5 logging * window. * * The LF5Appender is the primary class that enables logging to the * LogFactor5 logging window. The simplest method of using this Appender * is to add the following line to your log4j.properties file: * * log4j.appender.A1=org.apache.log4j.lf5.LF5Appender * * The log4j.properties file MUST be in you system classpath. If this file * is in your system classpath, a static initializer in the Category class * will load the file during class initialization. The LF5Appender will be * added to the root category of the Category tree. * * Create a log4j.properties file and add this line to it, or add this line * to your existing log4j.properties file. Run the example at the command line * and explore the results! * * @author Brent Sprecher */ // Contributed by ThoughtWorks Inc. public class InitUsingLog4JProperties { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- private static Logger logger = Logger.getLogger(InitUsingLog4JProperties.class); //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public static void main(String argv[]) { // Add a bunch of logging statements ... logger.debug("Hello, my name is Homer Simpson."); logger.debug("Hello, my name is Lisa Simpson."); logger.debug("Hello, my name is Marge Simpson."); logger.debug("Hello, my name is Bart Simpson."); logger.debug("Hello, my name is Maggie Simpson."); logger.info("We are the Simpsons!"); logger.info("Mmmmmm .... Chocolate."); logger.info("Homer likes chocolate"); logger.info("Doh!"); logger.info("We are the Simpsons!"); logger.warn("Bart: I am through with working! Working is for chumps!" + "Homer: Son, I'm proud of you. I was twice your age before " + "I figured that out."); logger.warn("Mmm...forbidden donut."); logger.warn("D'oh! A deer! A female deer!"); logger.warn("Truly, yours is a butt that won't quit." + "- Bart, writing as Woodrow to Ms. Krabappel."); logger.error("Dear Baby, Welcome to Dumpsville. Population: you."); logger.error("Dear Baby, Welcome to Dumpsville. Population: you.", new IOException("Dumpsville, USA")); logger.error("Mr. Hutz, are you aware you're not wearing pants?"); logger.error("Mr. Hutz, are you aware you're not wearing pants?", new IllegalStateException("Error !!")); logger.fatal("Eep."); logger.fatal("Mmm...forbidden donut.", new SecurityException("Fatal Exception")); logger.fatal("D'oh! A deer! A female deer!"); logger.fatal("Mmmmmm .... Chocolate.", new SecurityException("Fatal Exception")); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/examples/lf5/UsingSocketAppenders/0000755000175000017500000000000012126647422022376 5ustar tonytonyapache-log4j1.2-1.2.17.orig/examples/lf5/UsingSocketAppenders/socketclient.properties0000644000175000017500000000272611751454714027215 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # For the general syntax of property based configuration files see the # documenation of org.apache.log4j.PropertyConfigurator. # The root category uses the appender called A1. Since no priority is # specified, the root category assumes the default priority for root # which is DEBUG in log4j. The root category is the only category that # has a default priority. All other categories need not be assigned a # priority in which case they inherit their priority from the # hierarchy. log4j.rootCategory=, A1 # A1 is set to be a LF5Appender which outputs to a swing # logging console. log4j.appender.A1=org.apache.log4j.net.SocketAppender log4j.appender.A1.RemoteHost=localhost log4j.appender.A1.Port=8887 apache-log4j1.2-1.2.17.orig/examples/lf5/UsingSocketAppenders/UsingSocketAppenders.java0000644000175000017500000001351511751454714027351 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples.lf5.UsingSocketAppenders; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import java.io.IOException; import java.net.URL; /** * This is another simple example of how to use the LogFactor5 * logging console. * * The LF5Appender is the primary class that enables logging to the * LogFactor5 logging window. If the following line is added to a properties * file, the LF5Appender will be appended to the root category when * the properties file is loaded: * * log4j.appender.A1=org.apache.log4j.lf5.LF5Appender * * To make this example work, you must ensure that the example.properties file * is in your classpath.You can then run the example at the command line. * * @author Brent Sprecher */ // Contributed by ThoughtWorks Inc. public class UsingSocketAppenders { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- private static Logger logger1 = Logger.getLogger(UsingSocketAppenders.class); private static Logger logger2 = Logger.getLogger("TestClass.Subclass"); private static Logger logger3 = Logger.getLogger("TestClass.Subclass.Subclass"); //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public static void main(String argv[]) { // Use a PropertyConfigurator to initialize from a property file. String resource = "/examples/lf5/UsingSocketAppenders/socketclient.properties"; URL configFileResource = UsingSocketAppenders.class.getResource(resource); PropertyConfigurator.configure(configFileResource); // Add a bunch of logging statements ... logger1.debug("Hello, my name is Homer Simpson."); logger1.debug("Hello, my name is Lisa Simpson."); logger2.debug("Hello, my name is Marge Simpson."); logger2.debug("Hello, my name is Bart Simpson."); logger3.debug("Hello, my name is Maggie Simpson."); logger2.info("We are the Simpsons!"); logger2.info("Mmmmmm .... Chocolate."); logger3.info("Homer likes chocolate"); logger3.info("Doh!"); logger3.info("We are the Simpsons!"); logger1.warn("Bart: I am through with working! Working is for chumps!" + "Homer: Son, I'm proud of you. I was twice your age before " + "I figured that out."); logger1.warn("Mmm...forbidden donut."); logger1.warn("D'oh! A deer! A female deer!"); logger1.warn("Truly, yours is a butt that won't quit." + "- Bart, writing as Woodrow to Ms. Krabappel."); logger2.error("Dear Baby, Welcome to Dumpsville. Population: you."); logger2.error("Dear Baby, Welcome to Dumpsville. Population: you.", new IOException("Dumpsville, USA")); logger3.error("Mr. Hutz, are you aware you're not wearing pants?"); logger3.error("Mr. Hutz, are you aware you're not wearing pants?", new IllegalStateException("Error !!")); logger3.fatal("Eep."); logger3.fatal("Mmm...forbidden donut.", new SecurityException("Fatal Exception ... ")); logger3.fatal("D'oh! A deer! A female deer!"); logger2.fatal("Mmmmmm .... Chocolate.", new SecurityException("Fatal Exception")); // Put the main thread is put to sleep for 5 seconds to allow the // SocketServer to process all incoming messages before the Socket is // closed. This is done to overcome some basic limitations with the // way the SocketServer and SocketAppender classes manage sockets. try { Thread.sleep(5000); } catch (InterruptedException ie) { } } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/examples/lf5/UsingSocketAppenders/socketserver.properties0000644000175000017500000000301311751454714027233 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # For the general syntax of property based configuration files see the # documenation of org.apache.log4j.PropertyConfigurator. # The root category uses the appender called A1. Since no priority is # specified, the root category assumes the default priority for root # which is DEBUG in log4j. The root category is the only category that # has a default priority. All other categories need not be assigned a # priority in which case they inherit their priority from the # hierarchy. #log4j.rootCategory=DEBUG, A1 log4j.rootCategory=, A1 # A1 is set to be a LF5Appender which outputs to a swing # logging console. #log4j.category.org.apache.log4j.net.SocketNode=DEBUG log4j.appender.A1=org.apache.log4j.lf5.LF5Appender log4j.appender.A1.MaxNumberOfRecords=700apache-log4j1.2-1.2.17.orig/examples/lf5/UsingLogMonitorAdapter/0000755000175000017500000000000012126647422022676 5ustar tonytonyapache-log4j1.2-1.2.17.orig/examples/lf5/UsingLogMonitorAdapter/CustomizedLogLevels.java0000644000175000017500000001110611751454714027506 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples.lf5.UsingLogMonitorAdapter; import org.apache.log4j.lf5.LogLevel; import org.apache.log4j.lf5.util.LogMonitorAdapter; /** * This class is a simple example of how use the LogMonitorAdapter to * bypass the Log4JAppender and post LogRecords directly to the LogMonitor * using customized LogLevels * * To make this example work, ensure that the lf5.jar and lf5-license.jar * files are in your classpath, and then run the example at the command line. * * @author Richard Hurst */ // Contributed by ThoughtWorks Inc. public class CustomizedLogLevels { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- public final static LogLevel LEVEL_ONE = new LogLevel("LEVEL 1", 1); public final static LogLevel LEVEL_TWO = new LogLevel("LEVEL 2", 2); public final static LogLevel LEVEL_THREE = new LogLevel("LEVEL 3", 3); public final static LogLevel LEVEL_FOUR = new LogLevel("LEVEL 4", 4); public final static LogLevel DEFAULT = new LogLevel("DEFAULT", 0); //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- private static LogMonitorAdapter _adapter; static { // The first LogLevel in the Array will be used as the default LogLevel. _adapter = LogMonitorAdapter.newInstance(new LogLevel[]{DEFAULT, LEVEL_ONE, LEVEL_TWO, LEVEL_THREE, LEVEL_FOUR, LogLevel.FATAL}); // if a different log level is to be used it can be specified as such // _adapter.setDefaultLevel(LEVEL_THREE); } //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public static void main(String[] args) { CustomizedLogLevels test = new CustomizedLogLevels(); test.doMyBidding(); } public void doMyBidding() { // tell the LogMonitorAdapter which LogLevel is the severe Level if necessary _adapter.setSevereLevel(LEVEL_ONE); String levels = this.getClass().getName(); // will used the default Level _adapter.log(levels, "Using the customized LogLevels"); _adapter.log(levels, LEVEL_FOUR, "This is a test"); _adapter.log(levels, LEVEL_THREE, "Hmmm fobidden doughnut"); _adapter.log(levels, LEVEL_ONE, "Danger Danger Will Robinson", new RuntimeException("DANGER"), "32"); _adapter.log(levels, LEVEL_TWO, "Exit stage right->"); _adapter.log(levels, LEVEL_FOUR, "What's up Doc?", new NullPointerException("Unfortunate exception")); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/examples/lf5/UsingLogMonitorAdapter/UsingLogMonitorAdapter.java0000644000175000017500000000712311751454714030147 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples.lf5.UsingLogMonitorAdapter; import org.apache.log4j.lf5.LogLevel; import org.apache.log4j.lf5.util.LogMonitorAdapter; /** * This class is a simple example of how use the LogMonitorAdapter to * bypass the Log4JAppender and post LogRecords directly to the LogMonitor * * To make this example work, ensure that the lf5.jar and lf5-license.jar * files are in your classpath, and then run the example at the command line. * * @author Richard Hurst */ // Contributed by ThoughtWorks Inc. public class UsingLogMonitorAdapter { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- private static LogMonitorAdapter _adapter; static { _adapter = LogMonitorAdapter.newInstance(LogMonitorAdapter.LOG4J_LOG_LEVELS); } //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public static void main(String[] args) { UsingLogMonitorAdapter test = new UsingLogMonitorAdapter(); test.doMyBidding(); } public void doMyBidding() { String logger = this.getClass().getName(); // will default to debug log level _adapter.log(logger, "Doh this is a debugging"); _adapter.log(logger, LogLevel.INFO, "Hmmm fobidden doughnut"); _adapter.log(logger, LogLevel.WARN, "Danger Danger Will Robinson", new RuntimeException("DANGER"), "32"); _adapter.log(logger, LogLevel.ERROR, "Exit stage right->"); _adapter.log(logger, LogLevel.FATAL, "What's up Doc?", new NullPointerException("Unfortunate exception")); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/examples/lf5/index.html0000644000175000017500000000202411751454714020274 0ustar tonytony

See Examples section in the LogFactor5 user guide.

apache-log4j1.2-1.2.17.orig/examples/lf5/OpeningLogFiles/0000755000175000017500000000000011751454714021325 5ustar tonytonyapache-log4j1.2-1.2.17.orig/examples/lf5/InitUsingPropertiesFile/0000755000175000017500000000000012126647422023064 5ustar tonytonyapache-log4j1.2-1.2.17.orig/examples/lf5/InitUsingPropertiesFile/InitUsingPropertiesFile.java0000644000175000017500000001235311751454714030524 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples.lf5.InitUsingPropertiesFile; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import java.io.IOException; import java.net.URL; /** * This is another simple example of how to use the LogFactor5 * logging console. * * The LF5Appender is the primary class that enables logging to the * LogFactor5 logging window. If the following line is added to a properties * file, the LF5Appender will be appended to the root category when * the properties file is loaded: * * log4j.appender.A1=org.apache.log4j.lf5.LF5Appender * * To make this example work, you must ensure that the example.properties file * is in your classpath.You can then run the example at the command line. * * @author Brent Sprecher */ // Contributed by ThoughtWorks Inc. public class InitUsingPropertiesFile { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- private static Logger logger = Logger.getLogger(InitUsingPropertiesFile.class); //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public static void main(String argv[]) { // Use a PropertyConfigurator to initialize from a property file. String resource = "/examples/lf5/InitUsingPropertiesFile/example.properties"; URL configFileResource = InitUsingPropertiesFile.class.getResource(resource); PropertyConfigurator.configure(configFileResource); // Add a bunch of logging statements ... logger.debug("Hello, my name is Homer Simpson."); logger.debug("Hello, my name is Lisa Simpson."); logger.debug("Hello, my name is Marge Simpson."); logger.debug("Hello, my name is Bart Simpson."); logger.debug("Hello, my name is Maggie Simpson."); logger.info("We are the Simpsons!"); logger.info("Mmmmmm .... Chocolate."); logger.info("Homer likes chocolate"); logger.info("Doh!"); logger.info("We are the Simpsons!"); logger.warn("Bart: I am through with working! Working is for chumps!" + "Homer: Son, I'm proud of you. I was twice your age before " + "I figured that out."); logger.warn("Mmm...forbidden donut."); logger.warn("D'oh! A deer! A female deer!"); logger.warn("Truly, yours is a butt that won't quit." + "- Bart, writing as Woodrow to Ms. Krabappel."); logger.error("Dear Baby, Welcome to Dumpsville. Population: you."); logger.error("Dear Baby, Welcome to Dumpsville. Population: you.", new IOException("Dumpsville, USA")); logger.error("Mr. Hutz, are you aware you're not wearing pants?"); logger.error("Mr. Hutz, are you aware you're not wearing pants?", new IllegalStateException("Error !!")); logger.fatal("Eep."); logger.fatal("Mmm...forbidden donut.", new SecurityException("Fatal Exception")); logger.fatal("D'oh! A deer! A female deer!"); logger.fatal("Mmmmmm .... Chocolate.", new SecurityException("Fatal Exception")); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/examples/lf5/InitUsingPropertiesFile/example.properties0000644000175000017500000000267211751454714026647 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # For the general syntax of property based configuration files see the # documenation of org.apache.log4j.PropertyConfigurator. # The root category uses the appender called A1. Since no priority is # specified, the root category assumes the default priority for root # which is DEBUG in log4j. The root category is the only category that # has a default priority. All other categories need not be assigned a # priority in which case they inherit their priority from the # hierarchy. log4j.rootCategory=, A1 # A1 is set to be a LF5Appender which outputs to a swing # logging console. log4j.appender.A1=org.apache.log4j.lf5.LF5Appender log4j.appender.A1.MaxNumberOfRecords=700 apache-log4j1.2-1.2.17.orig/examples/lf5/InitUsingXMLPropertiesFile/0000755000175000017500000000000012126647422023445 5ustar tonytonyapache-log4j1.2-1.2.17.orig/examples/lf5/InitUsingXMLPropertiesFile/example.xml0000644000175000017500000000224111751454714025624 0ustar tonytony apache-log4j1.2-1.2.17.orig/examples/lf5/InitUsingXMLPropertiesFile/InitUsingXMLPropertiesFile.java0000644000175000017500000001176611751454714031475 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples.lf5.InitUsingXMLPropertiesFile; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import java.io.IOException; import java.net.URL; /** * This is another simple example of how to use the LogFactor5 * logging console. * * To make this example work, ensure that the lf5.jar, lf5-license.jar * and example.xml files are in your classpath. Once your classpath has * been set up, you can run the example from the command line. * * @author Brent Sprecher */ // Contributed by ThoughtWorks Inc. public class InitUsingXMLPropertiesFile { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- private static Logger logger = Logger.getLogger(InitUsingXMLPropertiesFile.class); //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public static void main(String argv[]) { // Use a PropertyConfigurator to initialize from a property file. String resource = "/examples/lf5/InitUsingXMLPropertiesFile/example.xml"; URL configFileResource = InitUsingXMLPropertiesFile.class.getResource(resource); DOMConfigurator.configure(configFileResource.getFile()); // Add a bunch of logging statements ... logger.debug("Hello, my name is Homer Simpson."); logger.debug("Hello, my name is Lisa Simpson."); logger.debug("Hello, my name is Marge Simpson."); logger.debug("Hello, my name is Bart Simpson."); logger.debug("Hello, my name is Maggie Simpson."); logger.info("We are the Simpsons!"); logger.info("Mmmmmm .... Chocolate."); logger.info("Homer likes chocolate"); logger.info("Doh!"); logger.info("We are the Simpsons!"); logger.warn("Bart: I am through with working! Working is for chumps!" + "Homer: Son, I'm proud of you. I was twice your age before " + "I figured that out."); logger.warn("Mmm...forbidden donut."); logger.warn("D'oh! A deer! A female deer!"); logger.warn("Truly, yours is a butt that won't quit." + "- Bart, writing as Woodrow to Ms. Krabappel."); logger.error("Dear Baby, Welcome to Dumpsville. Population: you."); logger.error("Dear Baby, Welcome to Dumpsville. Population: you.", new IOException("Dumpsville, USA")); logger.error("Mr. Hutz, are you aware you're not wearing pants?"); logger.error("Mr. Hutz, are you aware you're not wearing pants?", new IllegalStateException("Error !!")); logger.fatal("Eep."); logger.fatal("Mmm...forbidden donut.", new SecurityException("Fatal Exception")); logger.fatal("D'oh! A deer! A female deer!"); logger.fatal("Mmmmmm .... Chocolate.", new SecurityException("Fatal Exception")); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/examples/mycat.good0000644000175000017500000000305211751454714017602 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Setting the logger factory to MyLoggerFactory solves the # ClassCastException problem encountered with the "mycat.bad" # configuration file. log4j.loggerFactory=examples.subclass.MyLoggerFactory # The usual stuff. Note that A1 is configured in root not in "some.cat" log4j.rootLogger=DEBUG, A1 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%5p [%t] %c - %m%n # Set the priority of "some.cat" to TRACE (defined in # examples.customLevel.XLevel). Since we specified MyLoggerFactory as # the logger factory, the following line willl also have the side # effect of instanciating a MyLogger object having the name # "some.cat". log4j.logger.some.cat=TRACE#examples.customLevel.XLevel apache-log4j1.2-1.2.17.orig/examples/NumberCruncher.java0000644000175000017500000000240511751454714021401 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples; import java.rmi.Remote; import java.rmi.RemoteException; /** NumberCruncher's factor positive integers. See source code for more details. @author Ceki Gülcü */ public interface NumberCruncher extends Remote { /** Factor a positive integer number and return its distinct factor's as an integer array. */ int[] factor(int number) throws RemoteException; } apache-log4j1.2-1.2.17.orig/examples/NumberCruncherClient.java0000644000175000017500000000622011751454714022537 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples; import java.rmi.RemoteException; import java.rmi.Naming; import java.io.*; /** NumberCruncherClient is a simple client for factoring integers. A remote NumberCruncher is contacted and asked to factor an integer. The factors returned by the {@link NumberCruncherServer} are displayed on the screen.

See source code of NumberCruncherClient for more details.

   Usage: java  org.apache.log4j.examples.NumberCruncherClient HOST
        where HOST is the machine where the NumberCruncherServer is running
   

Note that class files for the example code is not included in any of the distributed log4j jar files. You will have to add the directory /dir-where-you-unpacked-log4j/classes to your classpath before trying out the examples. @author Ceki Gülcü */ public class NumberCruncherClient { public static void main(String[] args) { if(args.length == 1) { try { String url = "rmi://"+args[0]+ "/Factor"; NumberCruncher nc = (NumberCruncher) Naming.lookup(url); loop(nc); } catch(Exception e) { e.printStackTrace(); } } else usage("Wrong number of arguments."); } static void usage(String msg) { System.err.println(msg); System.err.println( "Usage: java org.apache.log4j.examples.NumberCruncherClient HOST\n" + " where HOST is the machine where the NumberCruncherServer is running."); System.exit(1); } static void loop(NumberCruncher nc) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int i = 0; while (true) { System.out.print("Enter a number to factor, '-1' to quit: "); try { i = Integer.parseInt(in.readLine()); } catch(Exception e) { e.printStackTrace(); } if(i == -1) { System.out.print("Exiting loop."); return; } else { try { System.out.println("Will attempt to factor "+i); int[] factors = nc.factor(i); System.out.print("The factors of "+i+" are"); for(int k=0; k < factors.length; k++) { System.out.print(" " + factors[k]); } System.out.println("."); } catch(RemoteException e) { System.err.println("Could not factor "+i); e.printStackTrace(); } } } } } apache-log4j1.2-1.2.17.orig/examples/sort2.properties0000644000175000017500000000547511751454714021015 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # An example log4j configuration file that outputs both to System.out # and a file named 'test'. # For the general syntax of property based configuration files see the # documenation of org.apache.log4j.PropertyConfigurator. # WARNING: Location information can be useful but is very costly in # terms of computation. # The root logger uses the appender called A1. # The root logger uses the appenders called A1 and A2. Since no level # is specified, note the empty string between the comma (",") and the # equals sign ("="), the level of the root logger remains # untouched. Log4j always initializes the level for the root logger to # DEBUG. The root logger is the only logger that has a default # level. Bu default, all other loggers do not have an assigned level, # such that they inherit their level instead. log4j.rootLogger=, A1, A2 # A1 is set to be ConsoleAppender sending its output to System.out log4j.appender.A1=org.apache.log4j.ConsoleAppender # A1 uses PatternLayout. log4j.appender.A1.layout=org.apache.log4j.PatternLayout # The conversion pattern consists of date in ISO8601 format, level, # thread name, logger name truncated to its rightmost two components # and left justified to 17 characters, location information consisting # of file name (padded to 13 characters) and line number, nested # diagnostic context, the and the application supplied message log4j.appender.A1.layout.ConversionPattern=%d %-5p [%t] %-17c{2} (%13F:%L) %3x - %m%n # Appender A2 writes to the file "test". log4j.appender.A2=org.apache.log4j.FileAppender log4j.appender.A2.File=test # Truncate 'test' if it aleady exists. log4j.appender.A2.Append=false # Appender A2 uses the PatternLayout. log4j.appender.A2.layout=org.apache.log4j.PatternLayout log4j.appender.A2.layout.ConversionPattern=%-5r %-5p [%t] %c{2} - %m%n # In this example, we are not interested in INNER loop or SWAP # messages. You might try to set INNER and SWAP to DEBUG for more # verbose output. log4j.logger.org.apache.log4j.examples.SortAlgo.INNER=INFO log4j.logger.org.apache.log4j.examples.SortAlgo.SWAP=INFO apache-log4j1.2-1.2.17.orig/examples/factor.lcf0000644000175000017500000000366611751454714017572 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # # # For the general syntax of property based configuration files see the # documenation of org.apache.log4j.PropertyConfigurator. # The root category uses the appender called A1. Since no priority is # specified, the root category assumes the default priority for root # which is DEBUG in log4j. The root category is the only category that # has a default priority. All other categories need not be assigned a # priority in which case they inherit their priority from the # hierarchy. log4j.rootCategory=, A1 # A1 is set to be a FileAppender which outputs to the file # "factor.log". Start the server NumberCruncherServer and two # NumberCruncherClients, and ask to factor two numbers # near-simultaneously. Notice that the log output from these two # requests are logged in the file factor.log. Nevertheless, the logs # of these requests can still be distinguished given their distinct # nested diagnostic contexts. log4j.appender.A1=org.apache.log4j.FileAppender log4j.appender.A1.File=factor.log log4j.appender.A1.layout=org.apache.log4j.PatternLayout # Note the %x conversion specifier for NDC printing. log4j.appender.A1.layout.ConversionPattern=%-4r %-5p [%t] (%x) - %m\n apache-log4j1.2-1.2.17.orig/examples/MyPatternParser.java0000644000175000017500000000443211751454714021561 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples; import org.apache.log4j.helpers.FormattingInfo; import org.apache.log4j.helpers.PatternConverter; import org.apache.log4j.helpers.PatternParser; import org.apache.log4j.spi.LoggingEvent; /** Example showing how to extend PatternParser to recognize additional conversion characters. The examples shows that minimum and maximum width and alignment settings apply for "extension" conversion characters just as they do for PatternLayout recognized characters.

In this case MyPatternParser recognizes %# and outputs the value of an internal counter which is also incremented at each call. See source code for more details. @see org.apache.log4j.examples.MyPatternLayout @see org.apache.log4j.helpers.PatternParser @see org.apache.log4j.PatternLayout @author Anders Kristensen */ public class MyPatternParser extends PatternParser { int counter = 0; public MyPatternParser(String pattern) { super(pattern); } public void finalizeConverter(char c) { if (c == '#') { addConverter(new UserDirPatternConverter(formattingInfo)); currentLiteral.setLength(0); } else { super.finalizeConverter(c); } } private class UserDirPatternConverter extends PatternConverter { UserDirPatternConverter(FormattingInfo formattingInfo) { super(formattingInfo); } public String convert(LoggingEvent event) { return String.valueOf(++counter); } } } apache-log4j1.2-1.2.17.orig/tests/0000755000175000017500000000000012126647422015134 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/build.xml0000644000175000017500000005505311751454673016774 0ustar tonytony These are the targets supported by this ANT build scpript: build - compile all project files, if a certain library is missing, then the compilation of its dependents are skipped. regression - Run regression tests which check large parts of log4j. runAll - run all available tests Specify the log4j.jar property to test an arbitrary jar, otherwise the parent log4j will be built and tested. clover.jar must be in the classpath and should also be placed in the lib directory. A version of clover (http://www.cenqua.com/clover) for use with ASF projects is available from the committers/donated-licenses/clover module in the SVN repository. Specify files to reformat with -Djalopy.files=PATTERN. apache-log4j1.2-1.2.17.orig/tests/resources/0000755000175000017500000000000012126647422017146 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/resources/TestLogSFPatterns.properties0000644000175000017500000000165111751454673024631 0ustar tonytony# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Iteration0=Iteration {} Hello1=Hello, World Malformed=Hello, {. Hello2=Hello, {}World Hello3=Hello, {} Hello4={}, {}. Hello5={}{} {}. Hello6={}{} {}{} apache-log4j1.2-1.2.17.orig/tests/resources/org/0000755000175000017500000000000011751454673017744 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/resources/org/apache/0000755000175000017500000000000011751454673021165 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/resources/org/apache/log4j/0000755000175000017500000000000012126647422022175 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/resources/org/apache/log4j/TestLogSFPatterns.properties0000644000175000017500000000165111751454673027660 0ustar tonytony# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Iteration0=Iteration {} Hello1=Hello, World Malformed=Hello, {. Hello2=Hello, {}World Hello3=Hello, {} Hello4={}, {}. Hello5={}{} {}. Hello6={}{} {}{} apache-log4j1.2-1.2.17.orig/tests/resources/org/apache/log4j/rewrite/0000755000175000017500000000000012126647422023656 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/resources/org/apache/log4j/rewrite/reflection.log0000644000175000017500000000035211751454673026522 0ustar tonytonyINFO org.apache.log4j.rewrite.RewriteAppenderTest - p1: p2: Message 0 INFO org.apache.log4j.rewrite.RewriteAppenderTest - p1: p2:Hello I am bean. INFO org.apache.log4j.rewrite.RewriteAppenderTest - p1:Hola p2:Hello Welcome to The Hub apache-log4j1.2-1.2.17.orig/tests/resources/org/apache/log4j/rewrite/reflection.xml0000644000175000017500000000270511751454673026545 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/resources/org/apache/log4j/rewrite/property.log0000644000175000017500000000023711751454673026256 0ustar tonytonyINFO org.apache.log4j.rewrite.RewriteAppenderTest - p1:Hello p2:World Message 0 INFO org.apache.log4j.rewrite.RewriteAppenderTest - p1:Hola p2:World Message 1 apache-log4j1.2-1.2.17.orig/tests/resources/org/apache/log4j/rewrite/map.xml0000644000175000017500000000267611751454673025177 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/resources/org/apache/log4j/rewrite/property.xml0000644000175000017500000000304211751454673026272 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/resources/org/apache/log4j/rewrite/map.log0000644000175000017500000000037311751454673025150 0ustar tonytonyINFO org.apache.log4j.rewrite.RewriteAppenderTest - p1: p2: Message 0 INFO org.apache.log4j.rewrite.RewriteAppenderTest - p1:Hello p2:World {p1=Hello, p2=World, x1=Mundo} INFO org.apache.log4j.rewrite.RewriteAppenderTest - p1:Hello p2:World Message 1 apache-log4j1.2-1.2.17.orig/tests/resources/org/apache/log4j/TestLogMFPatterns.properties0000644000175000017500000000166511751454673027657 0ustar tonytony# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Iteration0=Iteration {0} Hello1=Hello, World Malformed=Hello, {. Hello2=Hello, {0}World Hello3=Hello, {0} Hello4={1}, {0}. Hello5={1}{2} {0}. Hello6={1}{2} {0}{3} apache-log4j1.2-1.2.17.orig/tests/resources/L7D_fr.properties0000644000175000017500000000163311751454673022353 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. test=Ceci est le test en francais pour la France. hello_world=Bonjour la France. msg1=Ceci est le test numero {0} contenant l''argument {1}. apache-log4j1.2-1.2.17.orig/tests/resources/L7D_fr_CH.properties0000644000175000017500000000154311751454673022725 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. test=Ceci est le test en francais pour la p'tite Suisse. hello world=Salut le monde. apache-log4j1.2-1.2.17.orig/tests/resources/L7D_en_US.properties0000644000175000017500000000160111751454673022750 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. test=This is the English, US test. hello_world=Hello world. msg1=This is test number {0} with string argument {1}. apache-log4j1.2-1.2.17.orig/tests/run-tests.bat0000755000175000017500000001576211751454673017615 0ustar tonytonyrem Licensed to the Apache Software Foundation (ASF) under one or more rem contributor license agreements. See the NOTICE file distributed with rem this work for additional information regarding copyright ownership. rem The ASF licenses this file to You under the Apache License, Version 2.0 rem (the "License"); you may not use this file except in compliance with rem the License. You may obtain a copy of the License at rem rem http://www.apache.org/licenses/LICENSE-2.0 rem rem Unless required by applicable law or agreed to in writing, software rem distributed under the License is distributed on an "AS IS" BASIS, rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. rem See the License for the specific language governing permissions and rem limitations under the License. rem Batch file for running tests on JDK 1.1 rem SET CLASSPATH=\java\junit3.8.1\junit.jar;\java\crimson-1.1.3\crimson.jar;\java\jakarta-oro-2.0.8\jakarta-oro-2.0.8.jar;target\classes;..\..\target\classes;resources;%log4j.jar% mkdir target mkdir target\classes cd src\java javac -d ..\..\target\classes org\apache\log4j\util\SerializationTestHelper.java javac -d ..\..\target\classes org\apache\log4j\spi\LoggingEventTest.java javac -d ..\..\target\classes org\apache\log4j\LevelTest.java javac -d ..\..\target\classes org\apache\log4j\FileAppenderTest.java javac -d ..\..\target\classes org\apache\log4j\PriorityTest.java javac -d ..\..\target\classes org\apache\log4j\CategoryTest.java javac -d ..\..\target\classes org\apache\log4j\LogManagerTest.java javac -d ..\..\target\classes org\apache\log4j\helpers\LogLogTest.java javac -d ..\..\target\classes org\apache\log4j\LayoutTest.java javac -d ..\..\target\classes org\apache\log4j\helpers\DateLayoutTest.java javac -d ..\..\target\classes org\apache\log4j\TTCCLayoutTest.java javac -d ..\..\target\classes org\apache\log4j\xml\XMLLayoutTest.java javac -d ..\..\target\classes org\apache\log4j\HTMLLayoutTest.java javac -d ..\..\target\classes org\apache\log4j\PatternLayoutTest.java javac -d ..\..\target\classes org\apache\log4j\spi\ThrowableInformationTest.java javac -d ..\..\target\classes org\apache\log4j\spi\LocationInfoTest.java javac -d ..\..\target\classes org\apache\log4j\PropertyConfiguratorTest.java javac -d ..\..\target\classes org\apache\log4j\CoreTestSuite.java javac -d ..\..\target\classes org\apache\log4j\util\UnexpectedFormatException.java javac -d ..\..\target\classes org\apache\log4j\util\Filter.java javac -d ..\..\target\classes org\apache\log4j\util\Compare.java javac -d ..\..\target\classes org\apache\log4j\util\ControlFilter.java javac -d ..\..\target\classes org\apache\log4j\util\Transformer.java javac -d ..\..\target\classes org\apache\log4j\util\LineNumberFilter.java javac -d ..\..\target\classes org\apache\log4j\util\AbsoluteDateAndTimeFilter.java javac -d ..\..\target\classes org\apache\log4j\MinimumTestCase.java javac -d ..\..\target\classes org\apache\log4j\VectorAppender.java javac -d ..\..\target\classes org\apache\log4j\LoggerTestCase.java javac -d ..\..\target\classes org\apache\log4j\util\ISO8601Filter.java javac -d ..\..\target\classes org\apache\log4j\util\SunReflectFilter.java javac -d ..\..\target\classes org\apache\log4j\util\JunitTestRunnerFilter.java javac -d ..\..\target\classes org\apache\log4j\xml\DOMTestCase.java javac -d ..\..\target\classes org\apache\log4j\xml\XLevel.java javac -d ..\..\target\classes org\apache\log4j\xml\CustomLevelTestCase.java javac -d ..\..\target\classes org\apache\log4j\customLogger\XLogger.java javac -d ..\..\target\classes org\apache\log4j\customLogger\XLoggerTestCase.java javac -d ..\..\target\classes org\apache\log4j\defaultInit\TestCase1.java javac -d ..\..\target\classes org\apache\log4j\defaultInit\TestCase3.java javac -d ..\..\target\classes org\apache\log4j\defaultInit\TestCase4.java javac -d ..\..\target\classes org\apache\log4j\util\XMLTimestampFilter.java javac -d ..\..\target\classes org\apache\log4j\util\XMLLineAttributeFilter.java javac -d ..\..\target\classes org\apache\log4j\xml\XMLLayoutTestCase.java javac -d ..\..\target\classes org\apache\log4j\AsyncAppenderTestCase.java javac -d ..\..\target\classes org\apache\log4j\helpers\OptionConverterTestCase.java javac -d ..\..\target\classes org\apache\log4j\helpers\BoundedFIFOTestCase.java javac -d ..\..\target\classes org\apache\log4j\helpers\CyclicBufferTestCase.java javac -d ..\..\target\classes org\apache\log4j\or\ORTestCase.java javac -d ..\..\target\classes org\apache\log4j\varia\LevelMatchFilterTestCase.java javac -d ..\..\target\classes org\apache\log4j\helpers\PatternParserTestCase.java javac -d ..\..\target\classes org\apache\log4j\util\AbsoluteTimeFilter.java javac -d ..\..\target\classes org\apache\log4j\util\RelativeTimeFilter.java javac -d ..\..\target\classes org\apache\log4j\PatternLayoutTestCase.java javac -d ..\..\target\classes org\apache\log4j\MyPatternParser.java javac -d ..\..\target\classes org\apache\log4j\MyPatternLayout.java javac -d ..\..\target\classes org\apache\log4j\VectorErrorHandler.java javac -d ..\..\target\classes org\apache\log4j\DRFATestCase.java cd ..\.. mkdir output java junit.textui.TestRunner org.apache.log4j.CoreTestSuite java junit.textui.TestRunner org.apache.log4j.MinimumTestCase java junit.textui.TestRunner org.apache.log4j.LoggerTestCase java junit.textui.TestRunner org.apache.log4j.xml.DOMTestCase java junit.textui.TestRunner org.apache.log4j.xml.CustomLevelTestCase java junit.textui.TestRunner org.apache.log4j.customLogger.XLoggerTestCase del target\classes\log4j.xml del target\classes\log4j.properties java junit.textui.TestRunner org.apache.log4j.defaultInit.TestCase1 copy input\xml\defaultInit.xml target\classes\log4j.xml java junit.textui.TestRunner org.apache.log4j.defaultInit.TestCase2 del target\classes\log4j.xml copy input\xml\defaultInit.xml target\classes\log4j.xml java -Dlog4j.defaultInitOverride=true junit.textui.TestRunner org.apache.log4j.defaultInit.TestCase1 del target\classes\log4j.xml copy input\defaultInit3.properties target\classes\log4j.properties java junit.textui.TestRunner org.apache.log4j.defaultInit.TestCase3 del target\classes\log4j.properties copy input\xml\defaultInit.xml target\classes\log4j.xml copy input\defaultInit3.properties target\classes\log4j.properties java junit.textui.TestRunner org.apache.log4j.defaultInit.TestCase4 del target\classes\log4j.xml del target\classes\log4j.properties java junit.textui.TestRunner org.apache.log4j.xml.XMLLayoutTestCase java junit.textui.TestRunner org.apache.log4j.AsyncAppenderTestCase java junit.textui.TestRunner org.apache.log4j.helpers.OptionConverterTestCase java junit.textui.TestRunner org.apache.log4j.helpers.BoundedFIFOTestCase java junit.textui.TestRunner org.apache.log4j.helpers.CyclicBufferTestCase java junit.textui.TestRunner org.apache.log4j.or.ORTestCase java junit.textui.TestRunner org.apache.log4j.varia.LevelMatchFilterTestCase java junit.textui.TestRunner org.apache.log4j.helpers.PatternParserTestCase java junit.textui.TestRunner org.apache.log4j.PatternLayoutTestCase java junit.textui.TestRunner org.apache.log4j.DRFATestCase apache-log4j1.2-1.2.17.orig/tests/build.properties.sample0000644000175000017500000000323711751454673021645 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # by default assume that all necessary dependencies # are relative to the user's home directory # lib.home.dir=/java # The jaxp interface and a jaxp parser are required # to build the DOMConfigurator. # # modern equivalents are xml-commons-apis.jar # and xercesImpl.jar jaxp.home=${lib.home.dir}/crimson-1.1.3 jaxp.jaxp.jar=${jaxp.home}/crimson.jar jaxp.parser.jar=${jaxp.home}/crimson.jar jakarta.oro.jar=${lib.home.dir}/jakarta-oro-2.0.8/jakarta-oro-2.0.8.jar clover.jar=${lib.home.dir}/clover-1.3.8/lib/clover.jar deprecation=on # junit must be on the classpath or specified with -lib # only needs to be set here for JDK 1.1. junit.jar=${lib.home.dir}/junit3.8.1/junit.jar # # Jalopy source code reformatter # # jalopy-ant.dir=${lib.home.dir}/jalopy-ant-0.6.2 # # Checkstyle coding convention checker # checkstyle.jar=${lib.home.dir}/checkstyle-4.0-beta2/checkstyle-all-4.0-beta2.jar apache-log4j1.2-1.2.17.orig/tests/README0000644000175000017500000000423111751454673016023 0ustar tonytony This directory contains a series of log4j test cases. Prerequisites ============= Jakarta-ant is used to compile and run the tests. Jakarta-ant version 1.4.0 was used to compile and run the tests. The optional jakarta-ant-1.4-optional.jar file is required to be in the $ANT_HOME/lib directory where ANT_HOME envrironment variable point to the directory where you installed jakarta-ant. The tests cases as well running ant require a JAXP compatible parser. Such a parser is placed on the classpath by the shell or batch script that invokes ant, namely $ANT_HOME/bin/ant on UNIX and %ANT_HOME%/bin/ant.bat on Windows. The test cases are based on Junit version 3.7+. IMPORTANT: You need to place junit.jar in your CLASSPATH environment variable. The test cases perform some regular expression based filtering. This requires jakarta-oro. Version-2.0.5 was used when writing the tests. You need to have jakarta.oro.jar property (found in the build.properties file) to point to jakarta-oro.jar. See the file build.properties.sample for an example of a build.properties file. Assuming jakarta-ant is installed properly, depending on your platform type $ANT_HOME/bin/ant or %ANT_HOME%/bin/ant.bat to see the available commands. ------------------------------------------------------------------------ NOTE: The compilation and execution of tests must be performed from within the tests/ directory, that is from the directory where this README file is located. ------------------------------------------------------------------------ Writing a new test case ======================= Our test cases are based on junit and you should be familiar with junit in order to write new a test case. Some of the existing test are actually regression tests. They compare the output of a test with the output of a previous run, a.k.a a witness, which is purported to be correct. Since the ouput of some tests vary on time and line numbers, before comparing the output with a witness, we transform the output by unifying the result, for example by removing date and time information. To automatically run your test case with the rest of the log4j test cases, you need to modify tests/build.xml. apache-log4j1.2-1.2.17.orig/tests/witness/0000755000175000017500000000000012126647422016630 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/witness/hierarchyThreshold.20000644000175000017500000000006311751454673022554 0ustar tonytonyFATAL [main] log4j.HierarchyThresholdTestCase = m5 apache-log4j1.2-1.2.17.orig/tests/witness/patternLayout.140000644000175000017500000001040611751454673021661 0ustar tonytonyTRACE 1 - Message 0 TRACE 2 - Message 0 DEBUG 3 - Message 1 DEBUG 4 - Message 1 INFO 5 - Message 2 INFO 6 - Message 2 WARN 7 - Message 3 WARN 8 - Message 3 ERROR 9 - Message 4 ERROR 10 - Message 4 FATAL 11 - Message 5 FATAL 12 - Message 5 TRACE 13 - Message 6 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test14(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) DEBUG 14 - Message 7 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test14(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) INFO 15 - Message 8 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test14(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) WARN 16 - Message 9 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test14(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR 17 - Message 10 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test14(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) FATAL 18 - Message 11 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test14(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/socketServer.70000644000175000017500000000366711751454673021422 0ustar tonytonyTRACE some7 T7 client-test7 MDC-TEST7 [main] SocketServerTestCase - Message 1 TRACE some7 T7 client-test7 MDC-TEST7 [main] root - Message 2 DEBUG some7 T7 client-test7 MDC-TEST7 [main] SocketServerTestCase - Message 3 DEBUG some7 T7 client-test7 MDC-TEST7 [main] root - Message 4 INFO some7 T7 client-test7 MDC-TEST7 [main] SocketServerTestCase - Message 5 WARN some7 T7 client-test7 MDC-TEST7 [main] SocketServerTestCase - Message 6 LETHAL some7 T7 client-test7 MDC-TEST7 [main] SocketServerTestCase - Message 7 DEBUG some7 T7 client-test7 MDC-TEST7 [main] SocketServerTestCase - Message 8 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test7(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR some7 T7 client-test7 MDC-TEST7 [main] root - Message 9 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test7(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/serialization/0000755000175000017500000000000012126647422021505 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/witness/serialization/exception.bin0000644000175000017500000000346311751454673024212 0ustar tonytony¬ísr!org.apache.log4j.spi.LoggingEventóò¹#t µ? ZmdcCopyLookupRequiredZndcLookupRequiredJ timeStampL categoryNametLjava/lang/String;L locationInfot#Lorg/apache/log4j/spi/LocationInfo;LmdcCopytLjava/util/Hashtable;Lndcq~LrenderedMessageq~L threadNameq~L throwableInfot+Lorg/apache/log4j/spi/ThrowableInformation;xp&×trootpppt Hello, world.tmainsr)org.apache.log4j.spi.ThrowableInformation¾þàrQ[rept[Ljava/lang/String;xpur[Ljava.lang.String;­ÒVçé{Gxpt java.lang.Exception: Don't panictb at org.apache.log4j.spi.LoggingEventTest.testSerializationWithException(LoggingEventTest.java:70)t? at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)tQ at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)tY at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)t4 at java.lang.reflect.Method.invoke(Method.java:324)t7 at junit.framework.TestCase.runTest(TestCase.java:154)t7 at junit.framework.TestCase.runBare(TestCase.java:127)t= at junit.framework.TestResult$1.protect(TestResult.java:106)t@ at junit.framework.TestResult.runProtected(TestResult.java:124)t7 at junit.framework.TestResult.run(TestResult.java:109)t3 at junit.framework.TestCase.run(TestCase.java:118)t9 at junit.framework.TestSuite.runTest(TestSuite.java:208)t5 at junit.framework.TestSuite.run(TestSuite.java:203)t9 at junit.framework.TestSuite.runTest(TestSuite.java:208)t5 at junit.framework.TestSuite.run(TestSuite.java:203)t^ at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:289)ta at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:656)t_ at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:558)wN pxapache-log4j1.2-1.2.17.orig/tests/witness/serialization/mdc.bin0000644000175000017500000000077411751454673022761 0ustar tonytony¬ísr!org.apache.log4j.spi.LoggingEventóò¹#t µ? ZmdcCopyLookupRequiredZndcLookupRequiredJ timeStampL categoryNametLjava/lang/String;L locationInfot#Lorg/apache/log4j/spi/LocationInfo;LmdcCopytLjava/util/Hashtable;Lndcq~LrenderedMessageq~L threadNameq~L throwableInfot+Lorg/apache/log4j/spi/ThrowableInformation;xp&!éátrootpsrjava.util.Hashtable»%!Jä¸F loadFactorI thresholdxp?@wtmdckeytmdcvaluextndc testt Hello, world.tmainpwN pxapache-log4j1.2-1.2.17.orig/tests/witness/serialization/simple.bin0000644000175000017500000000061711751454673023503 0ustar tonytony¬ísr!org.apache.log4j.spi.LoggingEventóò¹#t µ? ZmdcCopyLookupRequiredZndcLookupRequiredJ timeStampL categoryNametLjava/lang/String;L locationInfot#Lorg/apache/log4j/spi/LocationInfo;LmdcCopytLjava/util/Hashtable;Lndcq~LrenderedMessageq~L threadNameq~L throwableInfot+Lorg/apache/log4j/spi/ThrowableInformation;xp&ë trootpppt Hello, world.tmainpwN pxapache-log4j1.2-1.2.17.orig/tests/witness/serialization/ndc.bin0000644000175000017500000000063111751454673022752 0ustar tonytony¬ísr!org.apache.log4j.spi.LoggingEventóò¹#t µ? ZmdcCopyLookupRequiredZndcLookupRequiredJ timeStampL categoryNametLjava/lang/String;L locationInfot#Lorg/apache/log4j/spi/LocationInfo;LmdcCopytLjava/util/Hashtable;Lndcq~LrenderedMessageq~L threadNameq~L throwableInfot+Lorg/apache/log4j/spi/ThrowableInformation;xp&!…5trootpptndc testt Hello, world.tmainpwN pxapache-log4j1.2-1.2.17.orig/tests/witness/serialization/location.bin0000644000175000017500000000072111751454673024016 0ustar tonytony¬ísr!org.apache.log4j.spi.LoggingEventóò¹#t µ? ZmdcCopyLookupRequiredZndcLookupRequiredJ timeStampL categoryNametLjava/lang/String;L locationInfot#Lorg/apache/log4j/spi/LocationInfo;LmdcCopytLjava/util/Hashtable;Lndcq~LrenderedMessageq~L threadNameq~L throwableInfot+Lorg/apache/log4j/spi/ThrowableInformation;xp&ýÕtrootsr!org.apache.log4j.spi.LocationInfoí™»áJ‘¥|LfullInfoq~xppppt Hello, world.tmainpwN pxapache-log4j1.2-1.2.17.orig/tests/witness/serialization/info.bin0000644000175000017500000000007411751454673023142 0ustar tonytony¬ísrorg.apache.log4j.Level0sÄ6xpwN INFOxapache-log4j1.2-1.2.17.orig/tests/witness/socketServer.10000644000175000017500000000343611751454673021406 0ustar tonytonyTRACE T1 [main] org.apache.log4j.net.SocketServerTestCase Message 1 TRACE T1 [main] root Message 2 DEBUG T1 [main] org.apache.log4j.net.SocketServerTestCase Message 3 DEBUG T1 [main] root Message 4 INFO T1 [main] org.apache.log4j.net.SocketServerTestCase Message 5 WARN T1 [main] org.apache.log4j.net.SocketServerTestCase Message 6 LETHAL T1 [main] org.apache.log4j.net.SocketServerTestCase Message 7 DEBUG T1 [main] org.apache.log4j.net.SocketServerTestCase Message 8 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test1(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR T1 [main] root Message 9 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test1(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/socketServer.80000644000175000017500000000374411751454673021417 0ustar tonytonyTRACE some8 T8 shortSocketServer MDC-TEST8 [main] SocketServerTestCase - Message 1 TRACE some8 T8 shortSocketServer MDC-TEST8 [main] root - Message 2 DEBUG some8 T8 shortSocketServer MDC-TEST8 [main] SocketServerTestCase - Message 3 DEBUG some8 T8 shortSocketServer MDC-TEST8 [main] root - Message 4 INFO some8 T8 shortSocketServer MDC-TEST8 [main] SocketServerTestCase - Message 5 WARN some8 T8 shortSocketServer MDC-TEST8 [main] SocketServerTestCase - Message 6 LETHAL some8 T8 shortSocketServer MDC-TEST8 [main] SocketServerTestCase - Message 7 DEBUG some8 T8 shortSocketServer MDC-TEST8 [main] SocketServerTestCase - Message 8 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test8(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR some8 T8 shortSocketServer MDC-TEST8 [main] root - Message 9 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test8(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/patternLayout.80000644000175000017500000001104011751454673021577 0ustar tonytony [main] TRACE rnLayoutTestCase - Message 0 [main] TRACE root - Message 0 [main] DEBUG rnLayoutTestCase - Message 1 [main] DEBUG root - Message 1 [main] INFO rnLayoutTestCase - Message 2 [main] INFO root - Message 2 [main] WARN rnLayoutTestCase - Message 3 [main] WARN root - Message 3 [main] ERROR rnLayoutTestCase - Message 4 [main] ERROR root - Message 4 [main] FATAL rnLayoutTestCase - Message 5 [main] FATAL root - Message 5 [main] TRACE rnLayoutTestCase - Message 6 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test8(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] DEBUG rnLayoutTestCase - Message 7 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test8(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] INFO rnLayoutTestCase - Message 8 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test8(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] WARN rnLayoutTestCase - Message 9 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test8(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] ERROR rnLayoutTestCase - Message 10 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test8(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] FATAL rnLayoutTestCase - Message 11 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test8(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/dom.A2.10000644000175000017500000000621411751454673017744 0ustar tonytony [main] TRACE org.apache.log4j.xml.DOMTestCase - Message 0 [main] TRACE root - Message 0 [main] DEBUG org.apache.log4j.xml.DOMTestCase - Message 1 [main] DEBUG root - Message 1 [main] INFO org.apache.log4j.xml.DOMTestCase - Message 2 [main] INFO root - Message 2 [main] WARN org.apache.log4j.xml.DOMTestCase - Message 3 [main] WARN root - Message 3 [main] ERROR org.apache.log4j.xml.DOMTestCase - Message 4 [main] ERROR root - Message 4 [main] FATAL org.apache.log4j.xml.DOMTestCase - Message 5 [main] FATAL root - Message 5 [main] DEBUG org.apache.log4j.xml.DOMTestCase - Message 6 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test1(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] DEBUG root - Message 6 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test1(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] ERROR org.apache.log4j.xml.DOMTestCase - Message 7 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test1(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] ERROR root - Message 7 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test1(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/ttcc0000644000175000017500000000320211751454673017514 0ustar tonytony [main] FATAL ERR - Message 0 [main] ERROR ERR - Message 1 [main] FATAL INF - Message 2 [main] ERROR INF - Message 3 [main] WARN INF - Message 4 [main] INFO INF - Message 5 [main] FATAL INF.UNDEF - Message 6 [main] ERROR INF.UNDEF - Message 7 [main] WARN INF.UNDEF - Message 8 [main] INFO INF.UNDEF - Message 9 [main] FATAL INF.ERR - Message 10 [main] ERROR INF.ERR - Message 11 [main] FATAL INF.ERR.UNDEF - Message 12 [main] ERROR INF.ERR.UNDEF - Message 13 [main] FATAL DEB - Message 14 [main] ERROR DEB - Message 15 [main] WARN DEB - Message 16 [main] INFO DEB - Message 17 [main] DEBUG DEB - Message 18 [main] FATAL TRC - Message 19 [main] ERROR TRC - Message 20 [main] WARN TRC - Message 21 [main] INFO TRC - Message 22 [main] DEBUG TRC - Message 23 [main] TRACE TRC - Message 24 [main] FATAL UNDEF - Message 25 [main] ERROR UNDEF - Message 26 [main] WARN UNDEF - Message 27 [main] INFO UNDEF - Message 28 [main] DEBUG UNDEF - Message 29 java.lang.Exception: Just testing. at org.apache.log4j.MinimumTestCase.common(MinimumTestCase.java:XXX) at org.apache.log4j.MinimumTestCase.ttcc(MinimumTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] INFO INF - Messages should bear numbers 0 through 29. apache-log4j1.2-1.2.17.orig/tests/witness/socketServer.50000644000175000017500000000350211751454673021404 0ustar tonytonyTRACE some5 T5 MDC-TEST5 [main] SocketServerTestCase - Message 1 TRACE some5 T5 MDC-TEST5 [main] root - Message 2 DEBUG some5 T5 MDC-TEST5 [main] SocketServerTestCase - Message 3 DEBUG some5 T5 MDC-TEST5 [main] root - Message 4 INFO some5 T5 MDC-TEST5 [main] SocketServerTestCase - Message 5 WARN some5 T5 MDC-TEST5 [main] SocketServerTestCase - Message 6 LETHAL some5 T5 MDC-TEST5 [main] SocketServerTestCase - Message 7 DEBUG some5 T5 MDC-TEST5 [main] SocketServerTestCase - Message 8 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test5(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR some5 T5 MDC-TEST5 [main] root - Message 9 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test5(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/xmlLayout.20000644000175000017500000001672511751454673020733 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/witness/hierarchyThreshold.30000644000175000017500000000014611751454673022557 0ustar tonytonyERROR [main] log4j.HierarchyThresholdTestCase = m4 FATAL [main] log4j.HierarchyThresholdTestCase = m5 apache-log4j1.2-1.2.17.orig/tests/witness/customLevel.10000644000175000017500000000032211751454673021220 0ustar tonytonyDEBUG xml.CustomLevelTestCase - Message 1 INFO xml.CustomLevelTestCase - Message 2 WARN xml.CustomLevelTestCase - Message 3 ERROR xml.CustomLevelTestCase - Message 4 TRACE xml.CustomLevelTestCase - Message 5 apache-log4j1.2-1.2.17.orig/tests/witness/socketServer.20000644000175000017500000000313311751454673021401 0ustar tonytonyTRACE T2 [main] ? (?:?) Message 1 TRACE T2 [main] ? (?:?) Message 2 DEBUG T2 [main] ? (?:?) Message 3 DEBUG T2 [main] ? (?:?) Message 4 INFO T2 [main] ? (?:?) Message 5 WARN T2 [main] ? (?:?) Message 6 LETHAL T2 [main] ? (?:?) Message 7 DEBUG T2 [main] ? (?:?) Message 8 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test2(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR T2 [main] ? (?:?) Message 9 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test2(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/patternLayout.40000644000175000017500000001104011751454673021573 0ustar tonytony [main] TRACE rnLayoutTestCase - Message 0 [main] TRACE root - Message 0 [main] DEBUG rnLayoutTestCase - Message 1 [main] DEBUG root - Message 1 [main] INFO rnLayoutTestCase - Message 2 [main] INFO root - Message 2 [main] WARN rnLayoutTestCase - Message 3 [main] WARN root - Message 3 [main] ERROR rnLayoutTestCase - Message 4 [main] ERROR root - Message 4 [main] FATAL rnLayoutTestCase - Message 5 [main] FATAL root - Message 5 [main] TRACE rnLayoutTestCase - Message 6 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test4(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] DEBUG rnLayoutTestCase - Message 7 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test4(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] INFO rnLayoutTestCase - Message 8 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test4(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] WARN rnLayoutTestCase - Message 9 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test4(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] ERROR rnLayoutTestCase - Message 10 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test4(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] FATAL rnLayoutTestCase - Message 11 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test4(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/customLevel.20000644000175000017500000000032211751454673021221 0ustar tonytonyDEBUG xml.CustomLevelTestCase - Message 1 INFO xml.CustomLevelTestCase - Message 2 WARN xml.CustomLevelTestCase - Message 3 ERROR xml.CustomLevelTestCase - Message 4 TRACE xml.CustomLevelTestCase - Message 5 apache-log4j1.2-1.2.17.orig/tests/witness/socketServer.40000644000175000017500000000347111751454673021410 0ustar tonytonyTRACE some T4 MDC-TEST4 [main] SocketServerTestCase - Message 1 TRACE some T4 MDC-TEST4 [main] root - Message 2 DEBUG some T4 MDC-TEST4 [main] SocketServerTestCase - Message 3 DEBUG some T4 MDC-TEST4 [main] root - Message 4 INFO some T4 MDC-TEST4 [main] SocketServerTestCase - Message 5 WARN some T4 MDC-TEST4 [main] SocketServerTestCase - Message 6 LETHAL some T4 MDC-TEST4 [main] SocketServerTestCase - Message 7 DEBUG some T4 MDC-TEST4 [main] SocketServerTestCase - Message 8 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test4(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR some T4 MDC-TEST4 [main] root - Message 9 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test4(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/patternLayout.120000644000175000017500000001322411751454673021660 0ustar tonytony[main] TRACE org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 0 [main] TRACE org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 0 [main] DEBUG org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 1 [main] DEBUG org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 1 [main] INFO org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 2 [main] INFO org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 2 [main] WARN org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 3 [main] WARN org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 3 [main] ERROR org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 4 [main] ERROR org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 4 [main] FATAL org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 5 [main] FATAL org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 5 [main] TRACE org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 6 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test12(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] DEBUG org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 7 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test12(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] INFO org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 8 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test12(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] WARN org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 9 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test12(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] ERROR org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 10 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test12(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] FATAL org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 11 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test12(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/patternLayout.90000644000175000017500000001101611751454673021603 0ustar tonytony[main] TRACE rnLayoutTestCase : Message 0 [main] TRACE root : Message 0 [main] DEBUG rnLayoutTestCase : Message 1 [main] DEBUG root : Message 1 [main] INFO rnLayoutTestCase : Message 2 [main] INFO root : Message 2 [main] WARN rnLayoutTestCase : Message 3 [main] WARN root : Message 3 [main] ERROR rnLayoutTestCase : Message 4 [main] ERROR root : Message 4 [main] FATAL rnLayoutTestCase : Message 5 [main] FATAL root : Message 5 [main] TRACE rnLayoutTestCase : Message 6 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test9(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] DEBUG rnLayoutTestCase : Message 7 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test9(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] INFO rnLayoutTestCase : Message 8 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test9(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] WARN rnLayoutTestCase : Message 9 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test9(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] ERROR rnLayoutTestCase : Message 10 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test9(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] FATAL rnLayoutTestCase : Message 11 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test9(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/patternLayout.70000644000175000017500000001104011751454673021576 0ustar tonytony [main] TRACE rnLayoutTestCase - Message 0 [main] TRACE root - Message 0 [main] DEBUG rnLayoutTestCase - Message 1 [main] DEBUG root - Message 1 [main] INFO rnLayoutTestCase - Message 2 [main] INFO root - Message 2 [main] WARN rnLayoutTestCase - Message 3 [main] WARN root - Message 3 [main] ERROR rnLayoutTestCase - Message 4 [main] ERROR root - Message 4 [main] FATAL rnLayoutTestCase - Message 5 [main] FATAL root - Message 5 [main] TRACE rnLayoutTestCase - Message 6 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test7(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] DEBUG rnLayoutTestCase - Message 7 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test7(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] INFO rnLayoutTestCase - Message 8 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test7(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] WARN rnLayoutTestCase - Message 9 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test7(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] ERROR rnLayoutTestCase - Message 10 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test7(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] FATAL rnLayoutTestCase - Message 11 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test7(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/hierarchyThreshold.40000644000175000017500000000023011751454673022552 0ustar tonytonyWARN [main] log4j.HierarchyThresholdTestCase = m3 ERROR [main] log4j.HierarchyThresholdTestCase = m4 FATAL [main] log4j.HierarchyThresholdTestCase = m5 apache-log4j1.2-1.2.17.orig/tests/witness/PatternParser_mdc0000644000175000017500000000072711751454673022205 0ustar tonytonystarting mdc pattern test empty mdc, no key specified in pattern : {} empty mdc, key1 in pattern : empty mdc, key2 in pattern : empty mdc, key3 in pattern : empty mdc, key1, key2, and key3 in pattern : ,, filled mdc, no key specified in pattern : {{key1,value1}{key2,value2}} filled mdc, key1 in pattern : value1 filled mdc, key2 in pattern : value2 filled mdc, key3 in pattern : filled mdc, key1, key2, and key3 in pattern : value1,value2, finished mdc pattern test apache-log4j1.2-1.2.17.orig/tests/witness/hierarchyThreshold.60000644000175000017500000000037511751454673022566 0ustar tonytonyDEBUG [main] log4j.HierarchyThresholdTestCase = m1 INFO [main] log4j.HierarchyThresholdTestCase = m2 WARN [main] log4j.HierarchyThresholdTestCase = m3 ERROR [main] log4j.HierarchyThresholdTestCase = m4 FATAL [main] log4j.HierarchyThresholdTestCase = m5 apache-log4j1.2-1.2.17.orig/tests/witness/hierarchyThreshold.80000644000175000017500000000046011751454673022563 0ustar tonytonyTRACE [main] log4j.HierarchyThresholdTestCase = m0 DEBUG [main] log4j.HierarchyThresholdTestCase = m1 INFO [main] log4j.HierarchyThresholdTestCase = m2 WARN [main] log4j.HierarchyThresholdTestCase = m3 ERROR [main] log4j.HierarchyThresholdTestCase = m4 FATAL [main] log4j.HierarchyThresholdTestCase = m5 apache-log4j1.2-1.2.17.orig/tests/witness/xmlLayout.10000644000175000017500000001256511751454673020730 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/witness/prudent0000644000175000017500000000000011751454673020231 0ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/witness/fallback10000644000175000017500000000575011751454673020411 0ustar tonytonyFALLBACK - test - Message 0 FALLBACK - root - Message 0 FALLBACK - test - Message 1 FALLBACK - root - Message 1 FALLBACK - test - Message 2 FALLBACK - root - Message 2 FALLBACK - test - Message 3 FALLBACK - root - Message 3 FALLBACK - test - Message 4 FALLBACK - root - Message 4 FALLBACK - test - Message 5 java.lang.Exception: Just testing at org.apache.log4j.varia.ErrorHandlerTestCase.common(ErrorHandlerTestCase.java:XXX) at org.apache.log4j.varia.ErrorHandlerTestCase.test1(ErrorHandlerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) FALLBACK - root - Message 5 java.lang.Exception: Just testing at org.apache.log4j.varia.ErrorHandlerTestCase.common(ErrorHandlerTestCase.java:XXX) at org.apache.log4j.varia.ErrorHandlerTestCase.test1(ErrorHandlerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) FALLBACK - test - Message 6 java.lang.Exception: Just testing at org.apache.log4j.varia.ErrorHandlerTestCase.common(ErrorHandlerTestCase.java:XXX) at org.apache.log4j.varia.ErrorHandlerTestCase.test1(ErrorHandlerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) FALLBACK - root - Message 6 java.lang.Exception: Just testing at org.apache.log4j.varia.ErrorHandlerTestCase.common(ErrorHandlerTestCase.java:XXX) at org.apache.log4j.varia.ErrorHandlerTestCase.test1(ErrorHandlerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/hierarchyThreshold.10000644000175000017500000000000011751454673022542 0ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/witness/customLogger.20000644000175000017500000000005711751454673021376 0ustar tonytonyTRACE customLogger.XLoggerTestCase - Message 0 apache-log4j1.2-1.2.17.orig/tests/witness/drfa_blockedRollover.log0000644000175000017500000000014511751454673023466 0ustar tonytonyINFO - Prior to rollover INFO - Rollover attempt while blocked INFO - Message after block removed apache-log4j1.2-1.2.17.orig/tests/witness/xmlLayout.null0000644000175000017500000000212511751454673021531 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/witness/simple0000644000175000017500000000232211751454673020052 0ustar tonytonyFATAL - Message 0 ERROR - Message 1 FATAL - Message 2 ERROR - Message 3 WARN - Message 4 INFO - Message 5 FATAL - Message 6 ERROR - Message 7 WARN - Message 8 INFO - Message 9 FATAL - Message 10 ERROR - Message 11 FATAL - Message 12 ERROR - Message 13 FATAL - Message 14 ERROR - Message 15 WARN - Message 16 INFO - Message 17 DEBUG - Message 18 FATAL - Message 19 ERROR - Message 20 WARN - Message 21 INFO - Message 22 DEBUG - Message 23 TRACE - Message 24 FATAL - Message 25 ERROR - Message 26 WARN - Message 27 INFO - Message 28 DEBUG - Message 29 java.lang.Exception: Just testing. at org.apache.log4j.MinimumTestCase.common(MinimumTestCase.java:XXX) at org.apache.log4j.MinimumTestCase.simple(MinimumTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) INFO - Messages should bear numbers 0 through 29. apache-log4j1.2-1.2.17.orig/tests/witness/socketServer.60000644000175000017500000000366711751454673021421 0ustar tonytonyTRACE some6 T6 client-test6 MDC-TEST6 [main] SocketServerTestCase - Message 1 TRACE some6 T6 client-test6 MDC-TEST6 [main] root - Message 2 DEBUG some6 T6 client-test6 MDC-TEST6 [main] SocketServerTestCase - Message 3 DEBUG some6 T6 client-test6 MDC-TEST6 [main] root - Message 4 INFO some6 T6 client-test6 MDC-TEST6 [main] SocketServerTestCase - Message 5 WARN some6 T6 client-test6 MDC-TEST6 [main] SocketServerTestCase - Message 6 LETHAL some6 T6 client-test6 MDC-TEST6 [main] SocketServerTestCase - Message 7 DEBUG some6 T6 client-test6 MDC-TEST6 [main] SocketServerTestCase - Message 8 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test6(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR some6 T6 client-test6 MDC-TEST6 [main] root - Message 9 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test6(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/customLevel.30000644000175000017500000000005211751454673021222 0ustar tonytonyTRACE xml.CustomLevelTestCase - Message 5 apache-log4j1.2-1.2.17.orig/tests/witness/LevelMatchFilter_deny0000644000175000017500000000274611751454673023004 0ustar tonytonyDEBUG - pass 0; filter set to deny only TRACE msgs INFO - pass 0; filter set to deny only TRACE msgs WARN - pass 0; filter set to deny only TRACE msgs ERROR - pass 0; filter set to deny only TRACE msgs FATAL - pass 0; filter set to deny only TRACE msgs TRACE - pass 1; filter set to deny only DEBUG msgs INFO - pass 1; filter set to deny only DEBUG msgs WARN - pass 1; filter set to deny only DEBUG msgs ERROR - pass 1; filter set to deny only DEBUG msgs FATAL - pass 1; filter set to deny only DEBUG msgs TRACE - pass 2; filter set to deny only INFO msgs DEBUG - pass 2; filter set to deny only INFO msgs WARN - pass 2; filter set to deny only INFO msgs ERROR - pass 2; filter set to deny only INFO msgs FATAL - pass 2; filter set to deny only INFO msgs TRACE - pass 3; filter set to deny only WARN msgs DEBUG - pass 3; filter set to deny only WARN msgs INFO - pass 3; filter set to deny only WARN msgs ERROR - pass 3; filter set to deny only WARN msgs FATAL - pass 3; filter set to deny only WARN msgs TRACE - pass 4; filter set to deny only ERROR msgs DEBUG - pass 4; filter set to deny only ERROR msgs INFO - pass 4; filter set to deny only ERROR msgs WARN - pass 4; filter set to deny only ERROR msgs FATAL - pass 4; filter set to deny only ERROR msgs TRACE - pass 5; filter set to deny only FATAL msgs DEBUG - pass 5; filter set to deny only FATAL msgs INFO - pass 5; filter set to deny only FATAL msgs WARN - pass 5; filter set to deny only FATAL msgs ERROR - pass 5; filter set to deny only FATAL msgs apache-log4j1.2-1.2.17.orig/tests/witness/hierarchyThreshold.70000644000175000017500000000046011751454673022562 0ustar tonytonyTRACE [main] log4j.HierarchyThresholdTestCase = m0 DEBUG [main] log4j.HierarchyThresholdTestCase = m1 INFO [main] log4j.HierarchyThresholdTestCase = m2 WARN [main] log4j.HierarchyThresholdTestCase = m3 ERROR [main] log4j.HierarchyThresholdTestCase = m4 FATAL [main] log4j.HierarchyThresholdTestCase = m5 apache-log4j1.2-1.2.17.orig/tests/witness/dom.A1.40000644000175000017500000001057011751454673017746 0ustar tonytonyTRACE xml.DOMTestCase - Message 0 TRACE xml.DOMTestCase - Message 0 TRACE root - Message 0 DEBUG xml.DOMTestCase - Message 1 DEBUG xml.DOMTestCase - Message 1 DEBUG root - Message 1 INFO xml.DOMTestCase - Message 2 INFO xml.DOMTestCase - Message 2 INFO root - Message 2 WARN xml.DOMTestCase - Message 3 WARN xml.DOMTestCase - Message 3 WARN root - Message 3 ERROR xml.DOMTestCase - Message 4 ERROR xml.DOMTestCase - Message 4 ERROR root - Message 4 FATAL xml.DOMTestCase - Message 5 FATAL xml.DOMTestCase - Message 5 FATAL root - Message 5 DEBUG xml.DOMTestCase - Message 6 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test4(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) DEBUG xml.DOMTestCase - Message 6 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test4(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) DEBUG root - Message 6 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test4(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR xml.DOMTestCase - Message 7 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test4(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR xml.DOMTestCase - Message 7 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test4(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR root - Message 7 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test4(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/LevelMatchFilter_accept0000644000175000017500000000047211751454673023276 0ustar tonytonyTRACE - pass 0; filter set to accept only TRACE msgs DEBUG - pass 1; filter set to accept only DEBUG msgs INFO - pass 2; filter set to accept only INFO msgs WARN - pass 3; filter set to accept only WARN msgs ERROR - pass 4; filter set to accept only ERROR msgs FATAL - pass 5; filter set to accept only FATAL msgs apache-log4j1.2-1.2.17.orig/tests/witness/dom.A2.40000644000175000017500000000621411751454673017747 0ustar tonytony [main] TRACE org.apache.log4j.xml.DOMTestCase - Message 0 [main] TRACE root - Message 0 [main] DEBUG org.apache.log4j.xml.DOMTestCase - Message 1 [main] DEBUG root - Message 1 [main] INFO org.apache.log4j.xml.DOMTestCase - Message 2 [main] INFO root - Message 2 [main] WARN org.apache.log4j.xml.DOMTestCase - Message 3 [main] WARN root - Message 3 [main] ERROR org.apache.log4j.xml.DOMTestCase - Message 4 [main] ERROR root - Message 4 [main] FATAL org.apache.log4j.xml.DOMTestCase - Message 5 [main] FATAL root - Message 5 [main] DEBUG org.apache.log4j.xml.DOMTestCase - Message 6 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test4(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] DEBUG root - Message 6 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test4(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] ERROR org.apache.log4j.xml.DOMTestCase - Message 7 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test4(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] ERROR root - Message 7 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test4(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/pattern/0000755000175000017500000000000012126647422020305 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/witness/pattern/enhancedPatternLayout.130000644000175000017500000000735411751454673024773 0ustar tonytony[main] DEBUG apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 0 [main] DEBUG apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 0 [main] INFO apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 1 [main] INFO apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 1 [main] WARN apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 2 [main] WARN apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 2 [main] ERROR apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 3 [main] ERROR apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 3 [main] FATAL apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 4 [main] FATAL apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 4 [main] DEBUG apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test13(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] INFO apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test13(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] WARN apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test13(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] ERROR apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test13(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] FATAL apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test13(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) apache-log4j1.2-1.2.17.orig/tests/witness/pattern/enhancedPatternLayout.150000644000175000017500000000556711751454673025001 0ustar tonytonyDEBUG 1 - Message 0 DEBUG 2 - Message 0 INFO 3 - Message 1 INFO 4 - Message 1 WARN 5 - Message 2 WARN 6 - Message 2 ERROR 7 - Message 3 ERROR 8 - Message 3 FATAL 9 - Message 4 FATAL 10 - Message 4 DEBUG 11 - Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test15(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) INFO 12 - Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test15(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) WARN 13 - Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test15(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) ERROR 14 - Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test15(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) FATAL 15 - Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test15(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) apache-log4j1.2-1.2.17.orig/tests/witness/pattern/enhancedPatternLayout.80000644000175000017500000000625511751454673024716 0ustar tonytony [main] DEBUG atternLayoutTest - Message 0 [main] DEBUG root - Message 0 [main] INFO atternLayoutTest - Message 1 [main] INFO root - Message 1 [main] WARN atternLayoutTest - Message 2 [main] WARN root - Message 2 [main] ERROR atternLayoutTest - Message 3 [main] ERROR root - Message 3 [main] FATAL atternLayoutTest - Message 4 [main] FATAL root - Message 4 [main] DEBUG atternLayoutTest - Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test8(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] INFO atternLayoutTest - Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test8(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] WARN atternLayoutTest - Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test8(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] ERROR atternLayoutTest - Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test8(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] FATAL atternLayoutTest - Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test8(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) apache-log4j1.2-1.2.17.orig/tests/witness/pattern/enhancedPatternLayout.110000644000175000017500000000645211751454673024767 0ustar tonytonyDEBUG [main] log4j.EnhancedPatternLayoutTest: Message 0 DEBUG [main] root: Message 0 INFO [main] log4j.EnhancedPatternLayoutTest: Message 1 INFO [main] root: Message 1 WARN [main] log4j.EnhancedPatternLayoutTest: Message 2 WARN [main] root: Message 2 ERROR [main] log4j.EnhancedPatternLayoutTest: Message 3 ERROR [main] root: Message 3 FATAL [main] log4j.EnhancedPatternLayoutTest: Message 4 FATAL [main] root: Message 4 DEBUG [main] log4j.EnhancedPatternLayoutTest: Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test11(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) INFO [main] log4j.EnhancedPatternLayoutTest: Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test11(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) WARN [main] log4j.EnhancedPatternLayoutTest: Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test11(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) ERROR [main] log4j.EnhancedPatternLayoutTest: Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test11(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) FATAL [main] log4j.EnhancedPatternLayoutTest: Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test11(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) apache-log4j1.2-1.2.17.orig/tests/witness/pattern/enhancedPatternLayout.140000644000175000017500000000645211751454673024772 0ustar tonytonyDEBUG [main] o.a.l.EnhancedPatternLayoutTest: Message 0 DEBUG [main] root: Message 0 INFO [main] o.a.l.EnhancedPatternLayoutTest: Message 1 INFO [main] root: Message 1 WARN [main] o.a.l.EnhancedPatternLayoutTest: Message 2 WARN [main] root: Message 2 ERROR [main] o.a.l.EnhancedPatternLayoutTest: Message 3 ERROR [main] root: Message 3 FATAL [main] o.a.l.EnhancedPatternLayoutTest: Message 4 FATAL [main] root: Message 4 DEBUG [main] o.a.l.EnhancedPatternLayoutTest: Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test14(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) INFO [main] o.a.l.EnhancedPatternLayoutTest: Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test14(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) WARN [main] o.a.l.EnhancedPatternLayoutTest: Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test14(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) ERROR [main] o.a.l.EnhancedPatternLayoutTest: Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test14(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) FATAL [main] o.a.l.EnhancedPatternLayoutTest: Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test14(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) apache-log4j1.2-1.2.17.orig/tests/witness/pattern/enhancedPatternLayout.50000644000175000017500000000625511751454673024713 0ustar tonytony [main] DEBUG atternLayoutTest - Message 0 [main] DEBUG root - Message 0 [main] INFO atternLayoutTest - Message 1 [main] INFO root - Message 1 [main] WARN atternLayoutTest - Message 2 [main] WARN root - Message 2 [main] ERROR atternLayoutTest - Message 3 [main] ERROR root - Message 3 [main] FATAL atternLayoutTest - Message 4 [main] FATAL root - Message 4 [main] DEBUG atternLayoutTest - Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test5(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] INFO atternLayoutTest - Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test5(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] WARN atternLayoutTest - Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test5(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] ERROR atternLayoutTest - Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test5(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] FATAL atternLayoutTest - Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test5(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) apache-log4j1.2-1.2.17.orig/tests/witness/pattern/enhancedPatternLayout.100000644000175000017500000000745011751454673024765 0ustar tonytony[main] DEBUG org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 0 [main] DEBUG org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 0 [main] INFO org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 1 [main] INFO org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 1 [main] WARN org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 2 [main] WARN org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 2 [main] ERROR org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 3 [main] ERROR org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 3 [main] FATAL org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 4 [main] FATAL org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 4 [main] DEBUG org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test10(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] INFO org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test10(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] WARN org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test10(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] ERROR org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test10(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] FATAL org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test10(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) apache-log4j1.2-1.2.17.orig/tests/witness/pattern/enhancedPatternLayout.90000644000175000017500000000623611751454673024716 0ustar tonytony[main] DEBUG atternLayoutTest : Message 0 [main] DEBUG root : Message 0 [main] INFO atternLayoutTest : Message 1 [main] INFO root : Message 1 [main] WARN atternLayoutTest : Message 2 [main] WARN root : Message 2 [main] ERROR atternLayoutTest : Message 3 [main] ERROR root : Message 3 [main] FATAL atternLayoutTest : Message 4 [main] FATAL root : Message 4 [main] DEBUG atternLayoutTest : Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test9(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] INFO atternLayoutTest : Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test9(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] WARN atternLayoutTest : Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test9(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] ERROR atternLayoutTest : Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test9(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] FATAL atternLayoutTest : Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test9(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) apache-log4j1.2-1.2.17.orig/tests/witness/pattern/enhancedPatternLayout.70000644000175000017500000000625511751454673024715 0ustar tonytony [main] DEBUG atternLayoutTest - Message 0 [main] DEBUG root - Message 0 [main] INFO atternLayoutTest - Message 1 [main] INFO root - Message 1 [main] WARN atternLayoutTest - Message 2 [main] WARN root - Message 2 [main] ERROR atternLayoutTest - Message 3 [main] ERROR root - Message 3 [main] FATAL atternLayoutTest - Message 4 [main] FATAL root - Message 4 [main] DEBUG atternLayoutTest - Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test7(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] INFO atternLayoutTest - Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test7(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] WARN atternLayoutTest - Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test7(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] ERROR atternLayoutTest - Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test7(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] FATAL atternLayoutTest - Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test7(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) apache-log4j1.2-1.2.17.orig/tests/witness/pattern/enhancedPatternLayout.60000644000175000017500000000625511751454673024714 0ustar tonytony [main] DEBUG atternLayoutTest - Message 0 [main] DEBUG root - Message 0 [main] INFO atternLayoutTest - Message 1 [main] INFO root - Message 1 [main] WARN atternLayoutTest - Message 2 [main] WARN root - Message 2 [main] ERROR atternLayoutTest - Message 3 [main] ERROR root - Message 3 [main] FATAL atternLayoutTest - Message 4 [main] FATAL root - Message 4 [main] DEBUG atternLayoutTest - Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test6(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] INFO atternLayoutTest - Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test6(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] WARN atternLayoutTest - Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test6(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] ERROR atternLayoutTest - Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test6(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] FATAL atternLayoutTest - Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test6(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) apache-log4j1.2-1.2.17.orig/tests/witness/pattern/enhancedPatternLayout.20000644000175000017500000000625511751454673024710 0ustar tonytony [main] DEBUG atternLayoutTest - Message 0 [main] DEBUG root - Message 0 [main] INFO atternLayoutTest - Message 1 [main] INFO root - Message 1 [main] WARN atternLayoutTest - Message 2 [main] WARN root - Message 2 [main] ERROR atternLayoutTest - Message 3 [main] ERROR root - Message 3 [main] FATAL atternLayoutTest - Message 4 [main] FATAL root - Message 4 [main] DEBUG atternLayoutTest - Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test2(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] INFO atternLayoutTest - Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test2(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] WARN atternLayoutTest - Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test2(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] ERROR atternLayoutTest - Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test2(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] FATAL atternLayoutTest - Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test2(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) apache-log4j1.2-1.2.17.orig/tests/witness/pattern/enhancedPatternLayout.mdc.10000644000175000017500000000005411751454673025440 0ustar tonytonyDEBUG - Hello World {{key1,va11}{key2,va12}}apache-log4j1.2-1.2.17.orig/tests/witness/pattern/enhancedPatternLayout.40000644000175000017500000000625511751454673024712 0ustar tonytony [main] DEBUG atternLayoutTest - Message 0 [main] DEBUG root - Message 0 [main] INFO atternLayoutTest - Message 1 [main] INFO root - Message 1 [main] WARN atternLayoutTest - Message 2 [main] WARN root - Message 2 [main] ERROR atternLayoutTest - Message 3 [main] ERROR root - Message 3 [main] FATAL atternLayoutTest - Message 4 [main] FATAL root - Message 4 [main] DEBUG atternLayoutTest - Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test4(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] INFO atternLayoutTest - Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test4(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] WARN atternLayoutTest - Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test4(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] ERROR atternLayoutTest - Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test4(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] FATAL atternLayoutTest - Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test4(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) apache-log4j1.2-1.2.17.orig/tests/witness/pattern/enhancedPatternLayout.10000644000175000017500000000556211751454673024707 0ustar tonytonyDEBUG - Message 0 DEBUG - Message 0 INFO - Message 1 INFO - Message 1 WARN - Message 2 WARN - Message 2 ERROR - Message 3 ERROR - Message 3 FATAL - Message 4 FATAL - Message 4 DEBUG - Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test1(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) INFO - Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test1(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) WARN - Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test1(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) ERROR - Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test1(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) FATAL - Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test1(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) apache-log4j1.2-1.2.17.orig/tests/witness/pattern/enhancedPatternLayout.throwable0000644000175000017500000000404411751454673026530 0ustar tonytonystarting throwable pattern test plain pattern, no exception plain pattern, with exception java.lang.Exception: Test Exception at org.apache.log4j.EnhancedPatternLayoutTestCase.testThrowable(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) %throwable, no exception %throwable, with exception java.lang.Exception: Test Exception at org.apache.log4j.EnhancedPatternLayoutTestCase.testThrowable(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) %throwable{short}, no exception %throwable{short}, with exception java.lang.Exception: Test Exception %throwable{none}, no exception %throwable{none}, with exception %throwable{0}, no exception %throwable{0}, with exception %throwable{1}, no exception %throwable{1}, with exception java.lang.Exception: Test Exception %throwable{100}, no exception %throwable{100}, with exception java.lang.Exception: Test Exception at org.apache.log4j.EnhancedPatternLayoutTestCase.testThrowable(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) %throwable{-n}, no exception %throwable{-n}, with exception java.lang.Exception: Test Exception at org.apache.log4j.EnhancedPatternLayoutTestCase.testThrowable(X) apache-log4j1.2-1.2.17.orig/tests/witness/pattern/enhancedPatternLayout.mdc.20000644000175000017500000000074311751454673025446 0ustar tonytonystarting mdc pattern test empty mdc, no key specified in pattern : {} empty mdc, key1 in pattern : empty mdc, key2 in pattern : empty mdc, key3 in pattern : empty mdc, key1, key2, and key3 in pattern : ,, filled mdc, no key specified in pattern : {{key1,value1}{key2,value2}} filled mdc, key1 in pattern : value1 filled mdc, key2 in pattern : value2 filled mdc, key3 in pattern : filled mdc, key1, key2, and key3 in pattern : value1,value2, finished mdc pattern test apache-log4j1.2-1.2.17.orig/tests/witness/pattern/enhancedPatternLayout.30000644000175000017500000000625511751454673024711 0ustar tonytony [main] DEBUG atternLayoutTest - Message 0 [main] DEBUG root - Message 0 [main] INFO atternLayoutTest - Message 1 [main] INFO root - Message 1 [main] WARN atternLayoutTest - Message 2 [main] WARN root - Message 2 [main] ERROR atternLayoutTest - Message 3 [main] ERROR root - Message 3 [main] FATAL atternLayoutTest - Message 4 [main] FATAL root - Message 4 [main] DEBUG atternLayoutTest - Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test3(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] INFO atternLayoutTest - Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test3(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] WARN atternLayoutTest - Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test3(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] ERROR atternLayoutTest - Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test3(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] FATAL atternLayoutTest - Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test3(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) apache-log4j1.2-1.2.17.orig/tests/witness/pattern/enhancedPatternLayout.120000644000175000017500000000745011751454673024767 0ustar tonytony[main] DEBUG org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 0 [main] DEBUG org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 0 [main] INFO org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 1 [main] INFO org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 1 [main] WARN org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 2 [main] WARN org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 2 [main] ERROR org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 3 [main] ERROR org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 3 [main] FATAL org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 4 [main] FATAL org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 4 [main] DEBUG org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test12(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] INFO org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test12(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] WARN org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test12(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] ERROR org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test12(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) [main] FATAL org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test12(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) apache-log4j1.2-1.2.17.orig/tests/witness/patternLayout.130000644000175000017500000001311411751454673021657 0ustar tonytony[main] TRACE apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 0 [main] TRACE apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 0 [main] DEBUG apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 1 [main] DEBUG apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 1 [main] INFO apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 2 [main] INFO apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 2 [main] WARN apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 3 [main] WARN apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 3 [main] ERROR apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 4 [main] ERROR apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 4 [main] FATAL apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 5 [main] FATAL apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 5 [main] TRACE apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 6 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test13(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] DEBUG apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 7 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test13(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] INFO apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 8 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test13(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] WARN apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 9 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test13(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] ERROR apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 10 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test13(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] FATAL apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 11 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test13(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/patternLayout.10000644000175000017500000001024611751454673021577 0ustar tonytonyTRACE - Message 0 TRACE - Message 0 DEBUG - Message 1 DEBUG - Message 1 INFO - Message 2 INFO - Message 2 WARN - Message 3 WARN - Message 3 ERROR - Message 4 ERROR - Message 4 FATAL - Message 5 FATAL - Message 5 TRACE - Message 6 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test1(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) DEBUG - Message 7 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test1(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) INFO - Message 8 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test1(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) WARN - Message 9 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test1(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR - Message 10 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test1(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) FATAL - Message 11 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test1(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/socketServer.30000644000175000017500000000425511751454673021410 0ustar tonytonyTRACE T3 [main] org.apache.log4j.net.SocketServerTestCase (SocketServerTestCase.java:XXX) Message 1 TRACE T3 [main] org.apache.log4j.net.SocketServerTestCase (SocketServerTestCase.java:XXX) Message 2 DEBUG T3 [main] org.apache.log4j.net.SocketServerTestCase (SocketServerTestCase.java:XXX) Message 3 DEBUG T3 [main] org.apache.log4j.net.SocketServerTestCase (SocketServerTestCase.java:XXX) Message 4 INFO T3 [main] org.apache.log4j.net.SocketServerTestCase (SocketServerTestCase.java:XXX) Message 5 WARN T3 [main] org.apache.log4j.net.SocketServerTestCase (SocketServerTestCase.java:XXX) Message 6 LETHAL T3 [main] org.apache.log4j.net.SocketServerTestCase (SocketServerTestCase.java:XXX) Message 7 DEBUG T3 [main] org.apache.log4j.net.SocketServerTestCase (SocketServerTestCase.java:XXX) Message 8 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test3(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR T3 [main] org.apache.log4j.net.SocketServerTestCase (SocketServerTestCase.java:XXX) Message 9 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test3(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/dom.A1.10000644000175000017500000001057011751454673017743 0ustar tonytonyTRACE xml.DOMTestCase - Message 0 TRACE xml.DOMTestCase - Message 0 TRACE root - Message 0 DEBUG xml.DOMTestCase - Message 1 DEBUG xml.DOMTestCase - Message 1 DEBUG root - Message 1 INFO xml.DOMTestCase - Message 2 INFO xml.DOMTestCase - Message 2 INFO root - Message 2 WARN xml.DOMTestCase - Message 3 WARN xml.DOMTestCase - Message 3 WARN root - Message 3 ERROR xml.DOMTestCase - Message 4 ERROR xml.DOMTestCase - Message 4 ERROR root - Message 4 FATAL xml.DOMTestCase - Message 5 FATAL xml.DOMTestCase - Message 5 FATAL root - Message 5 DEBUG xml.DOMTestCase - Message 6 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test1(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) DEBUG xml.DOMTestCase - Message 6 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test1(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) DEBUG root - Message 6 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test1(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR xml.DOMTestCase - Message 7 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test1(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR xml.DOMTestCase - Message 7 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test1(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR root - Message 7 java.lang.Exception: Just testing at org.apache.log4j.xml.DOMTestCase.common(DOMTestCase.java:XXX) at org.apache.log4j.xml.DOMTestCase.test1(DOMTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/patternLayout.110000644000175000017500000001120611751454673021655 0ustar tonytonyTRACE [main] log4j.PatternLayoutTestCase: Message 0 TRACE [main] root: Message 0 DEBUG [main] log4j.PatternLayoutTestCase: Message 1 DEBUG [main] root: Message 1 INFO [main] log4j.PatternLayoutTestCase: Message 2 INFO [main] root: Message 2 WARN [main] log4j.PatternLayoutTestCase: Message 3 WARN [main] root: Message 3 ERROR [main] log4j.PatternLayoutTestCase: Message 4 ERROR [main] root: Message 4 FATAL [main] log4j.PatternLayoutTestCase: Message 5 FATAL [main] root: Message 5 TRACE [main] log4j.PatternLayoutTestCase: Message 6 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test11(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) DEBUG [main] log4j.PatternLayoutTestCase: Message 7 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test11(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) INFO [main] log4j.PatternLayoutTestCase: Message 8 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test11(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) WARN [main] log4j.PatternLayoutTestCase: Message 9 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test11(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR [main] log4j.PatternLayoutTestCase: Message 10 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test11(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) FATAL [main] log4j.PatternLayoutTestCase: Message 11 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test11(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/customLevel.40000644000175000017500000000032211751454673021223 0ustar tonytonyDEBUG xml.CustomLevelTestCase - Message 1 INFO xml.CustomLevelTestCase - Message 2 WARN xml.CustomLevelTestCase - Message 3 ERROR xml.CustomLevelTestCase - Message 4 TRACE xml.CustomLevelTestCase - Message 5 apache-log4j1.2-1.2.17.orig/tests/witness/patternLayout.60000644000175000017500000001104011751454673021575 0ustar tonytony [main] TRACE rnLayoutTestCase - Message 0 [main] TRACE root - Message 0 [main] DEBUG rnLayoutTestCase - Message 1 [main] DEBUG root - Message 1 [main] INFO rnLayoutTestCase - Message 2 [main] INFO root - Message 2 [main] WARN rnLayoutTestCase - Message 3 [main] WARN root - Message 3 [main] ERROR rnLayoutTestCase - Message 4 [main] ERROR root - Message 4 [main] FATAL rnLayoutTestCase - Message 5 [main] FATAL root - Message 5 [main] TRACE rnLayoutTestCase - Message 6 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test6(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] DEBUG rnLayoutTestCase - Message 7 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test6(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] INFO rnLayoutTestCase - Message 8 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test6(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] WARN rnLayoutTestCase - Message 9 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test6(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] ERROR rnLayoutTestCase - Message 10 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test6(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] FATAL rnLayoutTestCase - Message 11 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test6(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/customLogger.10000644000175000017500000000165511751454673021402 0ustar tonytonyTRACE customLogger.XLoggerTestCase - Message 0 DEBUG customLogger.XLoggerTestCase - Message 1 WARN customLogger.XLoggerTestCase - Message 2 ERROR customLogger.XLoggerTestCase - Message 3 FATAL customLogger.XLoggerTestCase - Message 4 DEBUG customLogger.XLoggerTestCase - Message 5 java.lang.Exception: Just testing at org.apache.log4j.customLogger.XLoggerTestCase.common(XLoggerTestCase.java:XXX) at org.apache.log4j.customLogger.XLoggerTestCase.test1(XLoggerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/patternLayout.20000644000175000017500000001104011751454673021571 0ustar tonytony [main] TRACE rnLayoutTestCase - Message 0 [main] TRACE root - Message 0 [main] DEBUG rnLayoutTestCase - Message 1 [main] DEBUG root - Message 1 [main] INFO rnLayoutTestCase - Message 2 [main] INFO root - Message 2 [main] WARN rnLayoutTestCase - Message 3 [main] WARN root - Message 3 [main] ERROR rnLayoutTestCase - Message 4 [main] ERROR root - Message 4 [main] FATAL rnLayoutTestCase - Message 5 [main] FATAL root - Message 5 [main] TRACE rnLayoutTestCase - Message 6 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test2(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] DEBUG rnLayoutTestCase - Message 7 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test2(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] INFO rnLayoutTestCase - Message 8 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test2(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] WARN rnLayoutTestCase - Message 9 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test2(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] ERROR rnLayoutTestCase - Message 10 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test2(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] FATAL rnLayoutTestCase - Message 11 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test2(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/patternLayout.mdc.clear0000644000175000017500000000010311751454673023256 0ustar tonytonyDEBUG - Hello World {{key1,va11}{key2,va12}} DEBUG - Hello World {}apache-log4j1.2-1.2.17.orig/tests/witness/patternLayout.50000644000175000017500000001104011751454673021574 0ustar tonytony [main] TRACE rnLayoutTestCase - Message 0 [main] TRACE root - Message 0 [main] DEBUG rnLayoutTestCase - Message 1 [main] DEBUG root - Message 1 [main] INFO rnLayoutTestCase - Message 2 [main] INFO root - Message 2 [main] WARN rnLayoutTestCase - Message 3 [main] WARN root - Message 3 [main] ERROR rnLayoutTestCase - Message 4 [main] ERROR root - Message 4 [main] FATAL rnLayoutTestCase - Message 5 [main] FATAL root - Message 5 [main] TRACE rnLayoutTestCase - Message 6 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test5(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] DEBUG rnLayoutTestCase - Message 7 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test5(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] INFO rnLayoutTestCase - Message 8 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test5(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] WARN rnLayoutTestCase - Message 9 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test5(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] ERROR rnLayoutTestCase - Message 10 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test5(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] FATAL rnLayoutTestCase - Message 11 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test5(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/patternLayout.mdc.10000644000175000017500000000005411751454673022335 0ustar tonytonyDEBUG - Hello World {{key1,va11}{key2,va12}}apache-log4j1.2-1.2.17.orig/tests/witness/patternLayout.100000644000175000017500000001322411751454673021656 0ustar tonytony[main] TRACE org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 0 [main] TRACE org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 0 [main] DEBUG org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 1 [main] DEBUG org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 1 [main] INFO org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 2 [main] INFO org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 2 [main] WARN org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 3 [main] WARN org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 3 [main] ERROR org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 4 [main] ERROR org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 4 [main] FATAL org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 5 [main] FATAL org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 5 [main] TRACE org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 6 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test10(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] DEBUG org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 7 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test10(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] INFO org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 8 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test10(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] WARN org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 9 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test10(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] ERROR org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 10 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test10(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] FATAL org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX): Message 11 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test10(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/hierarchyThreshold.50000644000175000017500000000031211751454673022554 0ustar tonytonyINFO [main] log4j.HierarchyThresholdTestCase = m2 WARN [main] log4j.HierarchyThresholdTestCase = m3 ERROR [main] log4j.HierarchyThresholdTestCase = m4 FATAL [main] log4j.HierarchyThresholdTestCase = m5 apache-log4j1.2-1.2.17.orig/tests/witness/xmlLayout.mdc.10000644000175000017500000000045011751454673021460 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/witness/xmlLayout.mdc.20000644000175000017500000000054411751454673021465 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/witness/patternLayout.30000644000175000017500000001104011751454673021572 0ustar tonytony [main] TRACE rnLayoutTestCase - Message 0 [main] TRACE root - Message 0 [main] DEBUG rnLayoutTestCase - Message 1 [main] DEBUG root - Message 1 [main] INFO rnLayoutTestCase - Message 2 [main] INFO root - Message 2 [main] WARN rnLayoutTestCase - Message 3 [main] WARN root - Message 3 [main] ERROR rnLayoutTestCase - Message 4 [main] ERROR root - Message 4 [main] FATAL rnLayoutTestCase - Message 5 [main] FATAL root - Message 5 [main] TRACE rnLayoutTestCase - Message 6 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test3(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] DEBUG rnLayoutTestCase - Message 7 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test3(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] INFO rnLayoutTestCase - Message 8 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test3(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] WARN rnLayoutTestCase - Message 9 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test3(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] ERROR rnLayoutTestCase - Message 10 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test3(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) [main] FATAL rnLayoutTestCase - Message 11 java.lang.Exception: Just testing at org.apache.log4j.PatternLayoutTestCase.common(PatternLayoutTestCase.java:XXX) at org.apache.log4j.PatternLayoutTestCase.test3(PatternLayoutTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4j1.2-1.2.17.orig/tests/witness/xmlLayout.30000644000175000017500000000132011751454673020715 0ustar tonytony hi]]>]]> hi]]>]]> apache-log4j1.2-1.2.17.orig/tests/log4j-coding-convention.xml0000644000175000017500000002061211751454673022326 0ustar tonytony 14 6 true false true false false

1
0
false false false false true false true false false false false false false false false false false false 0 0 0 0 false false false false
* Copyright|The Apache Software License, Version 1.1| * Copyright (C) The Apache Software Foundation. All rights reserved. 0 /*| * Copyright 1999,2005 The Apache Software Foundation.| *| * Licensed under the Apache License, Version 2.0 (the "License");| * you may not use this file except in compliance with the License.| * You may obtain a copy of the License at| *| * http://www.apache.org/licenses/LICENSE-2.0| *| * Unless required by applicable law or agreed to in writing, software| * distributed under the License is distributed on an "AS IS" BASIS,| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.| * See the License for the specific language governing permissions and| * limitations under the License.| */ true
timestamp disabled disabled false true false true false 1 1 0 1 2 55 -1 2 -1 0 8 -1 1 false false static|field|initializer|constructor|method|interface|class true public|protected|private|abstract|static|final|synchronized|transient|volatile|native|strictfp true true true true false false false false false false true true false true true true true true true false false 0 false false false false false false false false false false false false false false true true 79 true true false false false false false false apache-log4j1.2-1.2.17.orig/tests/input/0000755000175000017500000000000012126647422016273 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/input/socketServer3.properties0000644000175000017500000000220011751454670023151 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootLogger=TRACE, A log4j.Logger.org.apache.log4j.test.ShortSocketServer=WARN log4j.Logger.org.apache.log4j.net.SocketNode=WARN log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.file=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%5p %x [%t] %C (%F:%L) %m%n apache-log4j1.2-1.2.17.orig/tests/input/filter1.properties0000644000175000017500000000357511751454670021775 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.appender.ROLLING=org.apache.log4j.PropertyConfiguratorTest$RollingFileAppender log4j.appender.ROLLING.append=false log4j.appender.ROLLING.rollingPolicy=org.apache.log4j.PropertyConfiguratorTest$FixedWindowRollingPolicy log4j.appender.ROLLING.rollingPolicy.activeFileName=filterBase-test1.log log4j.appender.ROLLING.rollingPolicy.fileNamePattern=filterBased-test1.%i log4j.appender.ROLLING.rollingPolicy.minIndex=0 log4j.appender.ROLLING.triggeringPolicy=org.apache.log4j.PropertyConfiguratorTest$FilterBasedTriggeringPolicy log4j.appender.ROLLING.triggeringPolicy.filter=org.apache.log4j.varia.LevelRangeFilter log4j.appender.ROLLING.triggeringPolicy.filter.levelMin=info log4j.appender.ROLLING.layout=org.apache.log4j.PatternLayout log4j.appender.ROLLING.layout.ConversionPattern=%m%n log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%m%n log4j.logger.org.apache.log4j.PropertyConfiguratorTest=debug, ROLLING log4j.additivity.org.apache.log4j.rolling.FilterBasedRollingTest=false log4j.roolLogger=info, CONSOLE apache-log4j1.2-1.2.17.orig/tests/input/socketServer1.properties0000644000175000017500000000217111751454670023156 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootLogger=TRACE, A log4j.logger.org.apache.log4j.test.ShortSocketServer=WARN log4j.logger.org.apache.log4j.net.SocketNode=WARN log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.file=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%5p %x [%t] %c %m%n apache-log4j1.2-1.2.17.orig/tests/input/patternLayout11.properties0000644000175000017500000000212211751454670023427 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=TRACE, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p [%t] %c{2}: %m%napache-log4j1.2-1.2.17.orig/tests/input/patternLayout12.properties0000644000175000017500000000213111751454670023430 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=TRACE, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=[%t] %-5p %C.%M(%F:%L): %m%napache-log4j1.2-1.2.17.orig/tests/input/patternLayout2.properties0000644000175000017500000000214411751454670023353 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=TRACE, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append= false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{ISO8601} [%t] %-5p %.16c - %m%n apache-log4j1.2-1.2.17.orig/tests/input/patternLayout9.properties0000644000175000017500000000212311751454670023357 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=TRACE, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=[%t] %-5p %.16c : %m%napache-log4j1.2-1.2.17.orig/tests/input/socketServer5.properties0000644000175000017500000000221611751454670023162 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootLogger=TRACE, A log4j.Logger.org.apache.log4j.test.ShortSocketServer=WARN log4j.Logger.org.apache.log4j.net.SocketNode=WARN log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.file=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%5p %x %X{key1}%X{key5} [%t] %c{1} - %m%n apache-log4j1.2-1.2.17.orig/tests/input/hierarchyThreshold2.properties0000644000175000017500000000203511751454670024332 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.threshold=FATAL log4j.rootLogger=,A log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.File=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p [%t] %c{2} = %m%napache-log4j1.2-1.2.17.orig/tests/input/RFA1.properties0000644000175000017500000000254111751454670021110 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootLogger=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.RollingFileAppender log4j.appender.testAppender.file=output/RFA-test1.log log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%m\n log4j.appender.testAppender.maxFileSize=100 # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j1.2-1.2.17.orig/tests/input/hierarchyThreshold1.properties0000644000175000017500000000203311751454670024327 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.threshold=OFF log4j.rootLogger=,A log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.File=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p [%t] %c{2} = %m%napache-log4j1.2-1.2.17.orig/tests/input/socketServer6.properties0000644000175000017500000000222111751454670023157 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootLogger=TRACE, A log4j.Logger.org.apache.log4j.test.ShortSocketServer=WARN log4j.Logger.org.apache.log4j.net.SocketNode=WARN log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.file=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%5p %x %X{hostID} %X{key6} [%t] %c{1} - %m%n apache-log4j1.2-1.2.17.orig/tests/input/socketServer7.properties0000644000175000017500000000222111751454670023160 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootLogger=TRACE, A log4j.Logger.org.apache.log4j.test.ShortSocketServer=WARN log4j.Logger.org.apache.log4j.net.SocketNode=WARN log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.file=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%5p %x %X{hostID} %X{key7} [%t] %c{1} - %m%n apache-log4j1.2-1.2.17.orig/tests/input/hierarchyThreshold7.properties0000644000175000017500000000207511751454670024343 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.threshold=TRACE#org.apache.log4j.xml.XLevel log4j.rootLogger=ALL,A log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.File=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p [%t] %c{2} = %m%n apache-log4j1.2-1.2.17.orig/tests/input/socketServer4.properties0000644000175000017500000000221611751454670023161 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootLogger=TRACE, A log4j.Logger.org.apache.log4j.test.ShortSocketServer=WARN log4j.Logger.org.apache.log4j.net.SocketNode=WARN log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.file=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%5p %x %X{key1}%X{key4} [%t] %c{1} - %m%n apache-log4j1.2-1.2.17.orig/tests/input/socketServer2.properties0000644000175000017500000000220111751454670023151 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootLogger=TRACE, A log4j.logger.org.apache.log4j.test.ShortSocketServer=WARN log4j.logger.org.apache.log4j.net.SocketNode=WARN log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.file=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%5p %x [%t] %C (%F:%L) %m%n apache-log4j1.2-1.2.17.orig/tests/input/patternLayout3.properties0000644000175000017500000000216311751454670023355 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=TRACE, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %-5p %.16c - %m%napache-log4j1.2-1.2.17.orig/tests/input/patternLayout5.properties0000644000175000017500000000216011751454670023354 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=TRACE, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} [%t] %-5p %.16c - %m%napache-log4j1.2-1.2.17.orig/tests/input/socketServer8.properties0000644000175000017500000000222111751454670023161 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootLogger=TRACE, A log4j.Logger.org.apache.log4j.test.ShortSocketServer=WARN log4j.Logger.org.apache.log4j.net.SocketNode=WARN log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.file=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%5p %x %X{hostID} %X{key8} [%t] %c{1} - %m%n apache-log4j1.2-1.2.17.orig/tests/input/hierarchyThreshold3.properties0000644000175000017500000000203511751454670024333 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.threshold=ERROR log4j.rootLogger=,A log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.File=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p [%t] %c{2} = %m%napache-log4j1.2-1.2.17.orig/tests/input/patternLayout.mdc.1.properties0000644000175000017500000000246311751454670024176 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p - %m %X%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j1.2-1.2.17.orig/tests/input/pattern/0000755000175000017500000000000012126647422017750 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/input/pattern/enhancedPatternLayout12.properties0000644000175000017500000000251011751454670026534 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=[%t] %-5p %C.%M(%F:%L): %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j1.2-1.2.17.orig/tests/input/pattern/enhancedPatternLayout10.properties0000644000175000017500000000250211751454670026533 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append= false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=[%t] %-5p %l: %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j1.2-1.2.17.orig/tests/input/pattern/enhancedPatternLayout4.properties0000644000175000017500000000251611751454670026463 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{DATE} [%t] %-5p %.16c - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j1.2-1.2.17.orig/tests/input/pattern/enhancedPatternLayout8.properties0000644000175000017500000000250511751454670026465 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%r [%t] %-5p %.16c - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j1.2-1.2.17.orig/tests/input/pattern/enhancedPatternLayout2.properties0000644000175000017500000000252211751454670026456 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append= false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{ISO8601} [%t] %-5p %.16c - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j1.2-1.2.17.orig/tests/input/pattern/enhancedPatternLayout14.properties0000644000175000017500000000250111751454670026536 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p [%t] %c{1.}: %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j1.2-1.2.17.orig/tests/input/pattern/enhancedPatternLayout16.properties0000644000175000017500000000260511751454670026545 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # log4j.rootCategory=TRACE, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/patternLayout16.log log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss}{GMT}Z %d{yyyy-MM-dd HH:mm:ss}{GMT-6}-0600 - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j1.2-1.2.17.orig/tests/input/pattern/enhancedPatternLayout1.properties0000644000175000017500000000246611751454670026464 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootLogger=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.file=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j1.2-1.2.17.orig/tests/input/pattern/enhancedPatternLayout.mdc.1.properties0000644000175000017500000000247311751454670027302 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p - %m %X%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j1.2-1.2.17.orig/tests/input/pattern/enhancedPatternLayout5.properties0000644000175000017500000000253711751454670026467 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} [%t] %-5p %.16c - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j1.2-1.2.17.orig/tests/input/pattern/enhancedPatternLayout13.properties0000644000175000017500000000251311751454670026540 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=[%t] %-5p %C{3}.%M(%F:%L): %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j1.2-1.2.17.orig/tests/input/pattern/enhancedPatternLayout6.properties0000644000175000017500000000252011751454670026460 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{ABSOLUTE} [%t] %-5p %.16c - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j1.2-1.2.17.orig/tests/input/pattern/enhancedPatternLayout3.properties0000644000175000017500000000254211751454670026461 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %-5p %.16c - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j1.2-1.2.17.orig/tests/input/pattern/enhancedPatternLayout7.properties0000644000175000017500000000252311751454670026464 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{HH:mm:ss,SSS} [%t] %-5p %.16c - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j1.2-1.2.17.orig/tests/input/pattern/enhancedPatternLayout9.properties0000644000175000017500000000250211751454670026463 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=[%t] %-5p %.16c : %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j1.2-1.2.17.orig/tests/input/pattern/enhancedPatternLayout15.properties0000644000175000017500000000247611751454670026552 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=TRACE, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedMyPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%5p %-4# - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j1.2-1.2.17.orig/tests/input/pattern/enhancedPatternLayout11.properties0000644000175000017500000000250111751454670026533 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p [%t] %c{2}: %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j1.2-1.2.17.orig/tests/input/defaultInit3.properties0000644000175000017500000000203611751454670022751 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=DEBUG, D3 log4j.appender.D3=org.apache.log4j.FileAppender log4j.appender.D3.File=output/temp log4j.appender.D3.Append=false log4j.appender.D3.layout=org.apache.log4j.PatternLayout log4j.appender.D3.layout.ConversionPattern=%d [%t] %-5p %.16c - %m%napache-log4j1.2-1.2.17.orig/tests/input/hierarchyThreshold5.properties0000644000175000017500000000203411751454670024334 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.threshold=INFO log4j.rootLogger=,A log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.File=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p [%t] %c{2} = %m%napache-log4j1.2-1.2.17.orig/tests/input/patternLayout8.properties0000644000175000017500000000212611751454670023361 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=TRACE, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%r [%t] %-5p %.16c - %m%napache-log4j1.2-1.2.17.orig/tests/input/xml/0000755000175000017500000000000012126647422017073 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/input/xml/testReset.xml0000644000175000017500000000220711751454670021604 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/input/xml/defaultInit.xml0000644000175000017500000000240611751454670022073 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/input/xml/customLevel2.xml0000644000175000017500000000313711751454670022211 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/input/xml/loggerfactory1.xml0000644000175000017500000000272211751454670022554 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/input/xml/customLevel1.xml0000644000175000017500000000255311751454670022211 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/input/xml/categoryfactory2.xml0000644000175000017500000000311711751454670023112 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/input/xml/SocketAppenderTestConfig.xml0000644000175000017500000000415511751454670024523 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/input/xml/customLogger2.xml0000644000175000017500000000325211751454670022357 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/input/xml/DOMTest4_A1.xml0000644000175000017500000000210511751454670021503 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/input/xml/customLogger1.xml0000644000175000017500000000263011751454670022355 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/input/xml/DOMTest4_A2.xml0000644000175000017500000000205611751454670021511 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/input/xml/DOMTestCase1.xml0000644000175000017500000000341511751454670021760 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/input/xml/customLevel3.xml0000644000175000017500000000324011751454670022205 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/input/xml/throwableRenderer1.xml0000644000175000017500000000215711751454670023365 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/input/xml/fallback1.xml0000644000175000017500000000346411751454670021450 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/input/xml/smtpAppender1.xml0000644000175000017500000000304311751454670022344 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/input/xml/customLogger3.xml0000644000175000017500000000262211751454670022360 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/input/xml/customLevel4.xml0000644000175000017500000000260611751454670022213 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/input/xml/DOMTest4.xml0000644000175000017500000000335311751454670021170 0ustar tonytony ]> &a1; &a2; apache-log4j1.2-1.2.17.orig/tests/input/xml/categoryfactory1.xml0000644000175000017500000000273011751454670023111 0ustar tonytony apache-log4j1.2-1.2.17.orig/tests/input/patternLayout13.properties0000644000175000017500000000213611751454670023436 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=TRACE, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File= output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=[%t] %-5p %C{3}.%M(%F:%L): %m%napache-log4j1.2-1.2.17.orig/tests/input/patternLayout10.properties0000644000175000017500000000212411751454670023430 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=TRACE, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File= output/temp log4j.appender.testAppender.Append= false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=[%t] %-5p %l: %m%napache-log4j1.2-1.2.17.orig/tests/input/patternLayout7.properties0000644000175000017500000000214511751454670023361 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=TRACE, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{HH:mm:ss,SSS} [%t] %-5p %.16c - %m%n apache-log4j1.2-1.2.17.orig/tests/input/patternLayout1.properties0000644000175000017500000000211111751454670023344 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=TRACE, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p - %m%napache-log4j1.2-1.2.17.orig/tests/input/patternLayout4.properties0000644000175000017500000000213711751454670023357 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=TRACE, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{DATE} [%t] %-5p %.16c - %m%napache-log4j1.2-1.2.17.orig/tests/input/hierarchyThreshold8.properties0000644000175000017500000000203611751454670024341 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.threshold=ALL log4j.rootLogger=ALL,A log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.File=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p [%t] %c{2} = %m%napache-log4j1.2-1.2.17.orig/tests/input/hierarchyThreshold4.properties0000644000175000017500000000203411751454670024333 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.threshold=WARN log4j.rootLogger=,A log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.File=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p [%t] %c{2} = %m%napache-log4j1.2-1.2.17.orig/tests/input/patternLayout14.properties0000644000175000017500000000212711751454670023437 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=TRACE, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File= output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.MyPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%5p %-4# - %m%n apache-log4j1.2-1.2.17.orig/tests/input/fallback1.properties0000644000175000017500000000302211751454670022232 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.debug=true log4j.appender.PRIMARY=org.apache.log4j.FileAppender log4j.appender.PRIMARY.errorhandler=org.apache.log4j.varia.FallbackErrorHandler log4j.appender.PRIMARY.errorhandler.root-ref=true log4j.appender.PRIMARY.errorhandler.appender-ref=FALLBACK log4j.appender.PRIMARY.file=/xyz/:x.log log4j.appender.PRIMARY.append=false log4j.appender.PRIMARY.layout=org.apache.log4j.PatternLayout log4j.appender.PRIMARY.layout.conversionPattern=%-5p %c{2} - %m%n log4j.appender.FALLBACK=org.apache.log4j.FileAppender log4j.appender.FALLBACK.File=output/temp log4j.appender.FALLBACK.Append=false log4j.appender.FALLBACK.layout=org.apache.log4j.PatternLayout log4j.appender.FALLBACK.layout.ConversionPattern=FALLBACK - %c - %m%n log4j.rootLogger=DEBUG, PRIMARY apache-log4j1.2-1.2.17.orig/tests/input/patternLayout6.properties0000644000175000017500000000214011751454670023353 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.rootCategory=TRACE, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=output/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{ABSOLUTE} [%t] %-5p %.16c - %m%napache-log4j1.2-1.2.17.orig/tests/input/hierarchyThreshold6.properties0000644000175000017500000000203511751454670024336 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log4j.threshold=DEBUG log4j.rootLogger=,A log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.File=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p [%t] %c{2} = %m%napache-log4j1.2-1.2.17.orig/tests/src/0000755000175000017500000000000011751454670015727 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/src/java/0000755000175000017500000000000011751454670016650 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/src/java/org/0000755000175000017500000000000011751454670017437 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/0000755000175000017500000000000011751454670020660 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/0000755000175000017500000000000012126647422021673 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/DRFATestCase.java0000644000175000017500000004067511751454673024731 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.FileInputStream; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.apache.log4j.util.Compare; /** Exhaustive test of the DailyRollingFileAppender compute algorithm. @author Ceki Gülcü @author Curt Arnold */ public class DRFATestCase extends TestCase { /** * Create new test. * @param name test name. */ public DRFATestCase(final String name) { super(name); } /** * Reset configuration after every test. */ public void tearDown() { LogManager.resetConfiguration(); } /** * Test prediction of check period. */ public void testComputeCheckPeriod() { DailyRollingFileAppender drfa = new DailyRollingFileAppender(); drfa.setName("testComputeCheckPeriod"); drfa.setDatePattern("yyyy-MM-dd.'log'"); drfa.activateOptions(); drfa.computeCheckPeriod(); assertEquals(drfa.computeCheckPeriod(), DailyRollingFileAppender.TOP_OF_DAY); drfa.setDatePattern("yyyy-MM-dd mm.'log'"); assertEquals(drfa.computeCheckPeriod(), DailyRollingFileAppender.TOP_OF_MINUTE); drfa.setDatePattern("yyyy-MM-dd a.'log'"); assertEquals(drfa.computeCheckPeriod(), DailyRollingFileAppender.HALF_DAY); drfa.setDatePattern("yyyy-MM-dd HH.'log'"); assertEquals(drfa.computeCheckPeriod(), DailyRollingFileAppender.TOP_OF_HOUR); drfa.setDatePattern("yyyy-MM.'log'"); assertEquals(drfa.computeCheckPeriod(), DailyRollingFileAppender.TOP_OF_MONTH); drfa.setDatePattern("'log'HH'log'"); assertEquals(drfa.computeCheckPeriod(), DailyRollingFileAppender.TOP_OF_HOUR); } /** * Test of RollingCalendar. */ public void testRC1() { RollingCalendar rc = new RollingCalendar(); rc.setType(DailyRollingFileAppender.TOP_OF_DAY); Calendar c = Calendar.getInstance(); // jan, mar, may, july, aug, oct, dec have 31 days int [] M31 = {0,2,4,6,7,9,11}; for(int i = 0; i < M31.length; i ++) { for(int d = 1; d <=31; d++) { for(int h = 0; h < 23; h++) { c.clear(); c.set(Calendar.YEAR, 20); c.set(Calendar.MONTH, Calendar.JANUARY + M31[i]); c.set(Calendar.DAY_OF_MONTH, d); c.set(Calendar.HOUR_OF_DAY, h); c.set(Calendar.MINUTE, 10); c.set(Calendar.SECOND, 10); c.set(Calendar.MILLISECOND, 88); c.setTime(rc.getNextCheckDate(c.getTime())); if(d == 31) { assertEquals(c.get(Calendar.MONTH),(Calendar.JANUARY+M31[i]+1)%12); assertEquals(c.get(Calendar.DAY_OF_MONTH), 1); } else { assertEquals(c.get(Calendar.MONTH), Calendar.JANUARY+M31[i]); assertEquals(c.get(Calendar.DAY_OF_MONTH), d+1); } assertEquals(c.get(Calendar.HOUR_OF_DAY), 0); assertEquals(c.get(Calendar.MINUTE), 0); assertEquals(c.get(Calendar.SECOND), 0); assertEquals(c.get(Calendar.MILLISECOND), 0); } } } } /** * RollingCalendar test. */ public void testRC2() { RollingCalendar rc = new RollingCalendar(); rc.setType(DailyRollingFileAppender.TOP_OF_HOUR); Calendar c = Calendar.getInstance(); // jan, mar, may, july, aug, oct, dec have 31 days int [] M31 = {0,2,4,6,7,9,11}; for(int i = 0; i < M31.length; i ++) { System.out.println("Month = "+(M31[i]+1)); for(int d = 1; d <= 31; d++) { for(int h = 0; h < 23; h++) { for(int m = 0; m <= 59; m++) { c.clear(); c.set(Calendar.YEAR, 20); c.set(Calendar.MONTH, Calendar.JANUARY + M31[i]); c.set(Calendar.DAY_OF_MONTH, d); c.set(Calendar.HOUR_OF_DAY, h); c.set(Calendar.MINUTE, m); c.set(Calendar.SECOND, 12); c.set(Calendar.MILLISECOND, 88); boolean dltState0 = c.getTimeZone().inDaylightTime(c.getTime()); c.setTime(rc.getNextCheckDate(c.getTime())); boolean dltState1 = c.getTimeZone().inDaylightTime(c.getTime()); assertEquals(c.get(Calendar.MILLISECOND), 0); assertEquals(c.get(Calendar.SECOND), 0); assertEquals(c.get(Calendar.MINUTE), 0); if(dltState0 == dltState1) { assertEquals(c.get(Calendar.HOUR_OF_DAY), (h+1)%24); } else { // returning to standard time if(dltState0) { assertEquals(c.get(Calendar.HOUR_OF_DAY), h); } else { // switching to day light saving time //System.err.println("m="+m+", h="+h+", d="+d+", i="+i); //if(h==2) { // System.err.println(c); //} //assertEquals(c.get(Calendar.HOUR_OF_DAY), (h+2)%24); } } if(h == 23) { assertEquals(c.get(Calendar.DAY_OF_MONTH), (d+1)%32); if(d == 31) { assertEquals(c.get(Calendar.MONTH), (Calendar.JANUARY+M31[i]+1)%12); } else { assertEquals(c.get(Calendar.MONTH), Calendar.JANUARY+M31[i]); } } else { assertEquals(c.get(Calendar.DAY_OF_MONTH), d); assertEquals(c.get(Calendar.MONTH), Calendar.JANUARY+M31[i]); } } } } } } /** * RollingCalendar test. */ public void testRC3() { RollingCalendar rc = new RollingCalendar(); rc.setType(DailyRollingFileAppender.TOP_OF_MINUTE); int[] S = {0, 1, 5, 10, 21, 30, 59}; int[] M = {0, 1, 5, 10, 21, 30, 59}; Calendar c = Calendar.getInstance(); // jan, mar, may, july, aug, oct, dec have 31 days int [] M31 = {2,9,0,4,6,7,11}; for(int i = 0; i < M31.length; i ++) { System.out.println("Month = "+(M31[i]+1)); for(int d = 1; d <= 31; d++) { for(int h = 0; h < 23; h++) { for(int m = 0; m < M.length; m++) { for(int s = 0; s < S.length; s++) { c.clear(); c.set(Calendar.YEAR, 20); c.set(Calendar.MONTH, Calendar.JANUARY + M31[i]); c.set(Calendar.DAY_OF_MONTH, d); c.set(Calendar.HOUR_OF_DAY, h); c.set(Calendar.MINUTE, M[m]); c.set(Calendar.SECOND, S[s]); c.set(Calendar.MILLISECOND, 88); c.add(Calendar.MILLISECOND, 1); boolean dltState0 = c.getTimeZone().inDaylightTime(c.getTime()); c.setTime(rc.getNextCheckDate(c.getTime())); c.add(Calendar.MILLISECOND, 0); boolean dltState1 = c.getTimeZone().inDaylightTime(c.getTime()); assertEquals(c.get(Calendar.MILLISECOND), 0); assertEquals(c.get(Calendar.SECOND), 0); assertEquals(c.get(Calendar.MINUTE), (M[m]+1)%60); if(M[m] == 59) { if(dltState0 == dltState1) { assertEquals(c.get(Calendar.HOUR_OF_DAY), (h+1)%24); } if(h == 23) { assertEquals(c.get(Calendar.DAY_OF_MONTH), (d+1)%32); if(d == 31) { assertEquals(c.get(Calendar.MONTH), (Calendar.JANUARY+M31[i]+1)%12); } else { assertEquals(c.get(Calendar.MONTH), Calendar.JANUARY+M31[i]); } } else { assertEquals(c.get(Calendar.DAY_OF_MONTH), d); } } else { // allow discrepancies only if we are switching from std to dls time if(c.get(Calendar.HOUR_OF_DAY) != h) { c.add(Calendar.HOUR_OF_DAY, +1); boolean dltState2 = c.getTimeZone().inDaylightTime(c.getTime()); if(dltState1 == dltState2) { fail("No switch"); } } assertEquals(c.get(Calendar.DAY_OF_MONTH), d); assertEquals(c.get(Calendar.MONTH), Calendar.JANUARY+M31[i]); } } } } } } } /** * Common test code for 3 parameter constructor. * * @throws IOException if IOException during test. */ public void test3Param(final String datePattern, final String filename) throws IOException { Layout layout = new SimpleLayout(); DailyRollingFileAppender appender = new DailyRollingFileAppender(layout, filename, datePattern); assertEquals(datePattern, appender.getDatePattern()); Logger root = Logger.getRootLogger(); root.addAppender(appender); root.info("Hello, World"); assertTrue(new File(filename).exists()); } /** * Creates an appender with an unrecognized top-of-year pattern. * * @throws IOException if IOException during test. */ public void testTopOfYear() throws IOException { try { test3Param("'.'yyyy", "output/drfa_topOfYear.log"); fail("Expected illegal state exception."); } catch(IllegalStateException ex) { assertNotNull(ex); } } /** * Creates an appender with a top-of-month pattern. * * @throws IOException if IOException during test. */ public void testTopOfMonth() throws IOException { test3Param("'.'yyyy-MM", "output/drfa_topOfMonth.log"); } /** * Creates an appender with a top-of-week pattern. * * @throws IOException if IOException during test. */ public void testTopOfWeek() throws IOException { test3Param("'.'yyyy-w", "output/drfa_topOfWeek.log"); } /** * Creates an appender with a top-of-day pattern. * * @throws IOException if IOException during test. */ public void testTopOfDay() throws IOException { test3Param("'.'yyyy-MM-dd", "output/drfa_topOfDay.log"); } /** * Creates an appender with a half day pattern. * * @throws IOException if IOException during test. */ public void testHalfDay() throws IOException { test3Param("'.'yyyy-MM-dd-a", "output/drfa_halfDay.log"); } /** * Creates an appender with a top-of-hour pattern. * * @throws IOException if IOException during test. */ public void testTopOfHour() throws IOException { test3Param("'.'yyyy-MM-dd-HH", "output/drfa_topOfHour.log"); } /** * Creates an appender with a top-of-day pattern. * * @throws IOException if IOException during test. */ public void testTopOfMinute() throws IOException { test3Param("'.'yyyy-MM-dd-HH-mm", "output/drfa_topOfMinute.log"); } /** * Attempts to rollOver with no date pattern set. * * @throws IOException if IOException during test. */ public void testRolloverNoPattern() throws IOException { Layout layout = new SimpleLayout(); DailyRollingFileAppender appender = new DailyRollingFileAppender(layout, "output/drfa_nopattern.log", null); VectorErrorHandler errorHandler = new VectorErrorHandler(); appender.setErrorHandler(errorHandler); appender.rollOver(); assertEquals(1, errorHandler.size()); assertEquals("Missing DatePattern option in rollOver().", errorHandler.getMessage(0)); } /** * Tests rollOver with a minute periodicity. * * @throws IOException * @throws InterruptedException */ public void testMinuteRollover() throws IOException, InterruptedException { Layout layout = new SimpleLayout(); String filename = "output/drfa_minuteRollover.log"; String pattern = "'.'yyyy-MM-dd-HH-mm"; DailyRollingFileAppender appender = new DailyRollingFileAppender(layout, filename, pattern); Logger root = Logger.getRootLogger(); root.addAppender(appender); File firstFile = new File(filename + new SimpleDateFormat(pattern).format(new Date())); root.info("Hello, World"); // // create a file by that name so it has to be deleted // on rollover firstFile.createNewFile(); assertTrue(firstFile.exists()); assertEquals(0, firstFile.length()); Calendar cal = Calendar.getInstance(); long now = cal.getTime().getTime(); cal.set(Calendar.SECOND, 3); cal.set(Calendar.MILLISECOND, 0); cal.add(Calendar.MINUTE, 1); long until = cal.getTime().getTime(); Thread.sleep(until - now); root.info("Hello, World"); assertTrue(firstFile.exists()); assertTrue(firstFile.length() > 0); } /** * Naive append method to combine rollover fragments. * @param combined stream to which source is appended. * @param source stream containing bytes to append. * @param buf byte array to use in transfer. * @throws IOException if io error during operation. */ private static void append(final FileOutputStream combined, final FileInputStream source, final byte[] buf) throws IOException { int count1 = source.read(buf); if (count1 > 0) { combined.write(buf, 0, count1); } source.close(); } /** * Tests rollOver when log file is unabled to be renamed. * See bug 43374. * * @throws IOException if io error. * @throws InterruptedException if test interrupted while waiting for the start of the next minute. */ public void testBlockedRollover() throws IOException, InterruptedException { Layout layout = new SimpleLayout(); String filename = "output/drfa_blockedRollover.log"; String pattern = "'.'yyyy-MM-dd-HH-mm"; Date start = new Date(); DailyRollingFileAppender appender = new DailyRollingFileAppender(layout, filename, pattern); appender.setAppend(false); Logger root = Logger.getRootLogger(); root.addAppender(appender); // // open next two anticipated rollover file names // File block1 = new File(filename + new SimpleDateFormat(pattern).format(start)); File block2 = new File(filename + new SimpleDateFormat(pattern).format( new Date(start.getTime() + 60000))); FileOutputStream os1 = new FileOutputStream(block1); FileOutputStream os2 = new FileOutputStream(block2); root.info("Prior to rollover"); // // sleep until three seconds into next minute // Thread.sleep(63000 - (start.getTime() % 60000)); // // should trigger failed rollover // root.info("Rollover attempt while blocked"); os1.close(); os2.close(); root.info("Message after block removed"); appender.close(); // // combine base file and potential rollovers // since rollover may or may not have been blocked // depending on platform. // String combinedFilename = "output/drfa_blockedRollover.combined"; FileOutputStream combined = new FileOutputStream(combinedFilename); byte[] buf = new byte[500]; append(combined, new FileInputStream(block1), buf); append(combined, new FileInputStream(block2), buf); append(combined, new FileInputStream(filename), buf); combined.close(); assertTrue(Compare.compare(combinedFilename, "witness/drfa_blockedRollover.log")); } /** Check that the computed rollover period for a pattern containing a week as the finest unit is set to be * a week. Due to a locale mismatch this was incorrect in non-English locales. See bug 40888. * */ public void testWeeklyRollover() { DailyRollingFileAppender drfa = new DailyRollingFileAppender(); drfa.setDatePattern("'.'yyyy-ww"); int checkPeriod = drfa.computeCheckPeriod(); assertEquals(DailyRollingFileAppender.TOP_OF_WEEK, checkPeriod); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/RFATestCase.java0000644000175000017500000001751111751454673024616 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; import java.io.File; import java.io.FileWriter; import java.io.IOException; /** * Test of RollingFileAppender. * * @author Curt Arnold */ public class RFATestCase extends TestCase { public RFATestCase(String name) { super(name); } public void tearDown() { LogManager.resetConfiguration(); } /** * Test basic rolling functionality using property file configuration. */ public void test1() throws Exception { Logger logger = Logger.getLogger(RFATestCase.class); PropertyConfigurator.configure("input/RFA1.properties"); // Write exactly 10 bytes with each log for (int i = 0; i < 25; i++) { if (i < 10) { logger.debug("Hello---" + i); } else if (i < 100) { logger.debug("Hello--" + i); } } assertTrue(new File("output/RFA-test1.log").exists()); assertTrue(new File("output/RFA-test1.log.1").exists()); } /** * Test basic rolling functionality using API configuration. */ public void test2() throws Exception { Logger logger = Logger.getLogger(RFATestCase.class); Logger root = Logger.getRootLogger(); PatternLayout layout = new PatternLayout("%m\n"); org.apache.log4j.RollingFileAppender rfa = new org.apache.log4j.RollingFileAppender(); rfa.setName("ROLLING"); rfa.setLayout(layout); rfa.setAppend(false); rfa.setMaxBackupIndex(3); rfa.setMaximumFileSize(100); rfa.setFile("output/RFA-test2.log"); rfa.activateOptions(); root.addAppender(rfa); // Write exactly 10 bytes with each log for (int i = 0; i < 55; i++) { if (i < 10) { logger.debug("Hello---" + i); } else if (i < 100) { logger.debug("Hello--" + i); } } assertTrue(new File("output/RFA-test2.log").exists()); assertTrue(new File("output/RFA-test2.log.1").exists()); assertTrue(new File("output/RFA-test2.log.2").exists()); assertTrue(new File("output/RFA-test2.log.3").exists()); assertFalse(new File("output/RFA-test2.log.4").exists()); } /** * Tests 2 parameter constructor. * @throws IOException if IOException during test. */ public void test2ParamConstructor() throws IOException { SimpleLayout layout = new SimpleLayout(); RollingFileAppender appender = new RollingFileAppender(layout,"output/rfa_2param.log"); assertEquals(1, appender.getMaxBackupIndex()); assertEquals(10*1024*1024, appender.getMaximumFileSize()); } /** * Tests 3 parameter constructor. * @throws IOException if IOException during test. */ public void test3ParamConstructor() throws IOException { SimpleLayout layout = new SimpleLayout(); RollingFileAppender appender = new RollingFileAppender(layout,"output/rfa_3param.log", false); assertEquals(1, appender.getMaxBackupIndex()); } /** * Test locking of .1 file. */ public void testLockDotOne() throws Exception { Logger logger = Logger.getLogger(RFATestCase.class); Logger root = Logger.getRootLogger(); PatternLayout layout = new PatternLayout("%m\n"); org.apache.log4j.RollingFileAppender rfa = new org.apache.log4j.RollingFileAppender(); rfa.setName("ROLLING"); rfa.setLayout(layout); rfa.setAppend(false); rfa.setMaxBackupIndex(10); rfa.setMaximumFileSize(100); rfa.setFile("output/RFA-dot1.log"); rfa.activateOptions(); root.addAppender(rfa); new File("output/RFA-dot1.log.2").delete(); FileWriter dot1 = new FileWriter("output/RFA-dot1.log.1"); dot1.write("Locked file"); FileWriter dot5 = new FileWriter("output/RFA-dot1.log.5"); dot5.write("Unlocked file"); dot5.close(); // Write exactly 10 bytes with each log for (int i = 0; i < 15; i++) { if (i < 10) { logger.debug("Hello---" + i); } else if (i < 100) { logger.debug("Hello--" + i); } } dot1.close(); for (int i = 15; i < 25; i++) { logger.debug("Hello--" + i); } rfa.close(); assertTrue(new File("output/RFA-dot1.log.7").exists()); // // if .2 is the locked file then // renaming wasn't successful until the file was closed if (new File("output/RFA-dot1.log.2").length() < 15) { assertEquals(50, new File("output/RFA-dot1.log").length()); assertEquals(200, new File("output/RFA-dot1.log.1").length()); } else { assertTrue(new File("output/RFA-dot1.log").exists()); assertTrue(new File("output/RFA-dot1.log.1").exists()); assertTrue(new File("output/RFA-dot1.log.2").exists()); assertTrue(new File("output/RFA-dot1.log.3").exists()); assertFalse(new File("output/RFA-dot1.log.4").exists()); } } /** * Test locking of .3 file. */ public void testLockDotThree() throws Exception { Logger logger = Logger.getLogger(RFATestCase.class); Logger root = Logger.getRootLogger(); PatternLayout layout = new PatternLayout("%m\n"); org.apache.log4j.RollingFileAppender rfa = new org.apache.log4j.RollingFileAppender(); rfa.setName("ROLLING"); rfa.setLayout(layout); rfa.setAppend(false); rfa.setMaxBackupIndex(10); rfa.setMaximumFileSize(100); rfa.setFile("output/RFA-dot3.log"); rfa.activateOptions(); root.addAppender(rfa); new File("output/RFA-dot3.log.1").delete(); new File("output/RFA-dot3.log.2").delete(); new File("output/RFA-dot3.log.4").delete(); FileWriter dot3 = new FileWriter("output/RFA-dot3.log.3"); dot3.write("Locked file"); FileWriter dot5 = new FileWriter("output/RFA-dot3.log.5"); dot5.write("Unlocked file"); dot5.close(); // Write exactly 10 bytes with each log for (int i = 0; i < 15; i++) { if (i < 10) { logger.debug("Hello---" + i); } else if (i < 100) { logger.debug("Hello--" + i); } } dot3.close(); for (int i = 15; i < 35; i++) { logger.debug("Hello--" + i); } rfa.close(); assertTrue(new File("output/RFA-dot3.log.8").exists()); // // if .3 is the locked file then // renaming wasn't successful until file was closed if (new File("output/RFA-dot3.log.5").exists()) { assertEquals(50, new File("output/RFA-dot3.log").length()); assertEquals(100, new File("output/RFA-dot3.log.1").length()); assertEquals(200, new File("output/RFA-dot3.log.2").length()); } else { assertTrue(new File("output/RFA-dot3.log").exists()); assertTrue(new File("output/RFA-dot3.log.1").exists()); assertTrue(new File("output/RFA-dot3.log.2").exists()); assertTrue(new File("output/RFA-dot3.log.3").exists()); assertFalse(new File("output/RFA-dot3.log.4").exists()); } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/FileAppenderTest.java0000644000175000017500000000501311751454673025742 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; import java.io.File; import java.lang.reflect.Method; /** * * FileAppender tests. * * @author Curt Arnold */ public class FileAppenderTest extends TestCase { /** * Tests that any necessary directories are attempted to * be created if they don't exist. See bug 9150. * */ public void testDirectoryCreation() { // // known to fail on JDK 1.1 if (!System.getProperty("java.version").startsWith("1.1.")) { File newFile = new File("output/newdir/temp.log"); newFile.delete(); File newDir = new File("output/newdir"); newDir.delete(); org.apache.log4j.FileAppender wa = new org.apache.log4j.FileAppender(); wa.setFile("output/newdir/temp.log"); wa.setLayout(new PatternLayout("%m%n")); wa.activateOptions(); assertTrue(new File("output/newdir/temp.log").exists()); } } /** * Tests that the return type of getThreshold is Priority. * @throws Exception */ public void testGetThresholdReturnType() throws Exception { Method method = FileAppender.class.getMethod("getThreshold", (Class[]) null); assertTrue(method.getReturnType() == Priority.class); } /** * Tests getThreshold and setThreshold. */ public void testgetSetThreshold() { FileAppender appender = new FileAppender(); Priority debug = Level.DEBUG; assertNull(appender.getThreshold()); appender.setThreshold(debug); assertTrue(appender.getThreshold() == debug); } /** * Tests isAsSevereAsThreshold. */ public void testIsAsSevereAsThreshold() { FileAppender appender = new FileAppender(); Priority debug = Level.DEBUG; assertTrue(appender.isAsSevereAsThreshold(debug)); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/rewrite/0000755000175000017500000000000012126647422023354 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/rewrite/RewriteAppenderTest.java0000644000175000017500000001021711751454672030166 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.rewrite; import junit.framework.*; import org.apache.log4j.*; import org.apache.log4j.util.Compare; import org.apache.log4j.xml.*; import java.io.InputStream; import java.util.Map; import java.util.HashMap; import java.util.TreeMap; import java.util.Hashtable; import javax.xml.parsers.*; import org.w3c.dom.*; public class RewriteAppenderTest extends TestCase { public RewriteAppenderTest(final String name) { super(name); } public void setUp() { LogManager.getLoggerRepository().resetConfiguration(); Hashtable context = MDC.getContext(); if (context != null) { context.clear(); } } public void tearDown() { LogManager.getLoggerRepository().shutdown(); } public void configure(final String resourceName) throws Exception { InputStream is = RewriteAppenderTest.class.getResourceAsStream(resourceName); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(is); DOMConfigurator.configure(doc.getDocumentElement()); } public void testMapPolicy() throws Exception { configure("map.xml"); Logger logger = Logger.getLogger(RewriteAppenderTest.class); logger.info("Message 0"); MDC.put("p1", "Hola"); Map msg = new TreeMap(); msg.put("p1", "Hello"); msg.put("p2", "World"); msg.put("x1", "Mundo"); logger.info(msg); msg.put("message", "Message 1"); logger.info(msg); assertTrue(Compare.compare(RewriteAppenderTest.class, "temp", "map.log")); } private static class BaseBean { private final Object p2; private final Object x1; public BaseBean(final Object p2, final Object x1) { this.p2 = p2; this.x1 = x1; } public Object getP2() { return p2; } public Object getX1() { return x1; } public String toString() { return "I am bean."; } } private static class MessageBean extends BaseBean { private final Object msg; public MessageBean(final Object msg, final Object p2, final Object x1) { super(p2, x1); this.msg = msg; } public Object getMessage() { return msg; } } public void testReflectionPolicy() throws Exception { configure("reflection.xml"); Logger logger = Logger.getLogger(RewriteAppenderTest.class); logger.info("Message 0"); logger.info(new BaseBean("Hello", "World" )); MDC.put("p1", "Hola"); MDC.put("p2", "p2"); logger.info(new MessageBean("Welcome to The Hub", "Hello", "World" )); assertTrue(Compare.compare(RewriteAppenderTest.class, "temp", "reflection.log")); } public void testPropertyPolicy() throws Exception { configure("property.xml"); Logger logger = Logger.getLogger(RewriteAppenderTest.class); logger.info("Message 0"); MDC.put("p1", "Hola"); logger.info("Message 1"); assertTrue(Compare.compare(RewriteAppenderTest.class, "temp", "property.log")); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/LevelTest.java0000644000175000017500000001526711751454673024467 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; import org.apache.log4j.util.SerializationTestHelper; import java.util.Locale; /** * Tests of Level. * * @author Curt Arnold * @since 1.2.12 */ public class LevelTest extends TestCase { /** * Constructs new instance of test. * @param name test name. */ public LevelTest(final String name) { super(name); } /** * Serialize Level.INFO and check against witness. * @throws Exception if exception during test. * */ public void testSerializeINFO() throws Exception { int[] skip = new int[] { }; SerializationTestHelper.assertSerializationEquals( "witness/serialization/info.bin", Level.INFO, skip, Integer.MAX_VALUE); } /** * Deserialize witness and see if resolved to Level.INFO. * @throws Exception if exception during test. */ public void testDeserializeINFO() throws Exception { Object obj = SerializationTestHelper.deserializeStream( "witness/serialization/info.bin"); assertTrue(obj instanceof Level); Level info = (Level) obj; assertEquals("INFO", info.toString()); // // JDK 1.1 doesn't support readResolve necessary for the assertion if (!System.getProperty("java.version").startsWith("1.1.")) { assertTrue(obj == Level.INFO); } } /** * Tests that a custom level can be serialized and deserialized * and is not resolved to a stock level. * * @throws Exception if exception during test. */ public void testCustomLevelSerialization() throws Exception { CustomLevel custom = new CustomLevel(); Object obj = SerializationTestHelper.serializeClone(custom); assertTrue(obj instanceof CustomLevel); CustomLevel clone = (CustomLevel) obj; assertEquals(Level.INFO.level, clone.level); assertEquals(Level.INFO.levelStr, clone.levelStr); assertEquals(Level.INFO.syslogEquivalent, clone.syslogEquivalent); } /** * Custom level to check that custom levels are * serializable, but not resolved to a plain Level. */ private static class CustomLevel extends Level { private static final long serialVersionUID = 1L; /** * Create an instance of CustomLevel. */ public CustomLevel() { super( Level.INFO.level, Level.INFO.levelStr, Level.INFO.syslogEquivalent); } } /** * Tests Level.TRACE_INT. */ public void testTraceInt() { assertEquals(5000, Level.TRACE_INT); } /** * Tests Level.TRACE. */ public void testTrace() { assertEquals("TRACE", Level.TRACE.toString()); assertEquals(5000, Level.TRACE.toInt()); assertEquals(7, Level.TRACE.getSyslogEquivalent()); } /** * Tests Level.toLevel(Level.TRACE_INT). */ public void testIntToTrace() { Level trace = Level.toLevel(5000); assertEquals("TRACE", trace.toString()); } /** * Tests Level.toLevel("TRACE"); */ public void testStringToTrace() { Level trace = Level.toLevel("TRACE"); assertEquals("TRACE", trace.toString()); } /** * Tests that Level extends Priority. */ public void testLevelExtendsPriority() { assertTrue(Priority.class.isAssignableFrom(Level.class)); } /** * Tests Level.OFF. */ public void testOFF() { assertTrue(Level.OFF instanceof Level); } /** * Tests Level.FATAL. */ public void testFATAL() { assertTrue(Level.FATAL instanceof Level); } /** * Tests Level.ERROR. */ public void testERROR() { assertTrue(Level.ERROR instanceof Level); } /** * Tests Level.WARN. */ public void testWARN() { assertTrue(Level.WARN instanceof Level); } /** * Tests Level.INFO. */ public void testINFO() { assertTrue(Level.INFO instanceof Level); } /** * Tests Level.DEBUG. */ public void testDEBUG() { assertTrue(Level.DEBUG instanceof Level); } /** * Tests Level.TRACE. */ public void testTRACE() { assertTrue(Level.TRACE instanceof Level); } /** * Tests Level.ALL. */ public void testALL() { assertTrue(Level.ALL instanceof Level); } /** * Tests Level.serialVersionUID. */ public void testSerialVersionUID() { assertEquals(3491141966387921974L, Level.serialVersionUID); } /** * Tests Level.toLevel(Level.All_INT). */ public void testIntToAll() { Level level = Level.toLevel(Level.ALL_INT); assertEquals("ALL", level.toString()); } /** * Tests Level.toLevel(Level.FATAL_INT). */ public void testIntToFatal() { Level level = Level.toLevel(Level.FATAL_INT); assertEquals("FATAL", level.toString()); } /** * Tests Level.toLevel(Level.OFF_INT). */ public void testIntToOff() { Level level = Level.toLevel(Level.OFF_INT); assertEquals("OFF", level.toString()); } /** * Tests Level.toLevel(17, Level.FATAL). */ public void testToLevelUnrecognizedInt() { Level level = Level.toLevel(17, Level.FATAL); assertEquals("FATAL", level.toString()); } /** * Tests Level.toLevel(null, Level.FATAL). */ public void testToLevelNull() { Level level = Level.toLevel(null, Level.FATAL); assertEquals("FATAL", level.toString()); } /** * Test that dotless lower I + "nfo" is recognized as INFO. */ public void testDotlessLowerI() { Level level = Level.toLevel("\u0131nfo"); assertEquals("INFO", level.toString()); } /** * Test that dotted lower I + "nfo" is recognized as INFO * even in Turkish locale. */ public void testDottedLowerI() { Locale defaultLocale = Locale.getDefault(); Locale turkey = new Locale("tr", "TR"); Locale.setDefault(turkey); Level level = Level.toLevel("info"); Locale.setDefault(defaultLocale); assertEquals("INFO", level.toString()); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/TestLogXF.java0000644000175000017500000001502111751454673024363 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; /** * Unit test for LogXF. */ public class TestLogXF extends TestCase { /** * Logger. */ private final Logger logger = Logger.getLogger( "org.apache.log4j.formatter.TestLogXF"); /** * Create the test case * * @param testName name of the test case */ public TestLogXF(String testName) { super(testName); } /** * Post test clean up. */ public void tearDown() { LogManager.resetConfiguration(); } private static class BadStringifier { private BadStringifier() {} public static BadStringifier INSTANCE = new BadStringifier(); public String toString() { throw new NullPointerException(); } } /** * Test LogXF.entering with null class and method. */ public void testEnteringNullNull() { LogCapture capture = new LogCapture(Level.DEBUG); logger.setLevel(Level.DEBUG); LogXF.entering(logger, null, null); assertEquals("null.null ENTRY", capture.getMessage()); } /** * Test LogXF.entering with null class, method and parameter. */ public void testEnteringNullNullNull() { LogCapture capture = new LogCapture(Level.DEBUG); logger.setLevel(Level.DEBUG); LogXF.entering(logger, null, null, (String) null); assertEquals("null.null ENTRY null", capture.getMessage()); } /** * Test LogXF.entering with null class, method and parameters. */ public void testEnteringNullNullNullArray() { LogCapture capture = new LogCapture(Level.DEBUG); logger.setLevel(Level.DEBUG); LogXF.entering(logger, null, null, (Object[]) null); assertEquals("null.null ENTRY {}", capture.getMessage()); } /** * Test LogXF.entering with class and method. */ public void testEntering() { LogCapture capture = new LogCapture(Level.DEBUG); logger.setLevel(Level.DEBUG); LogXF.entering(logger, "SomeClass", "someMethod"); assertEquals("SomeClass.someMethod ENTRY", capture.getMessage()); } /** * Test LogXF.entering with class, method and parameter. */ public void testEnteringWithParam() { LogCapture capture = new LogCapture(Level.DEBUG); logger.setLevel(Level.DEBUG); LogXF.entering(logger, "SomeClass", "someMethod", "someParam"); assertEquals("SomeClass.someMethod ENTRY someParam", capture.getMessage()); } /** * Test LogXF.entering with class, method and bad parameter. */ public void testEnteringWithBadParam() { LogCapture capture = new LogCapture(Level.DEBUG); logger.setLevel(Level.DEBUG); LogXF.entering(logger, "SomeClass", "someMethod", BadStringifier.INSTANCE); assertEquals("SomeClass.someMethod ENTRY ?", capture.getMessage()); } /** * Test LogXF.entering with class, method and bad parameters. */ public void testEnteringWithBadParams() { LogCapture capture = new LogCapture(Level.DEBUG); logger.setLevel(Level.DEBUG); LogXF.entering(logger, "SomeClass", "someMethod", new Object[]{"param1",BadStringifier.INSTANCE}); assertEquals("SomeClass.someMethod ENTRY {param1,?}", capture.getMessage()); } /** * Test LogXF.exiting with null class and method. */ public void testExitingNullNull() { LogCapture capture = new LogCapture(Level.DEBUG); logger.setLevel(Level.DEBUG); LogXF.exiting(logger, null, null); assertEquals("null.null RETURN", capture.getMessage()); } /** * Test LogXF.exiting with null class, method and parameter. */ public void testExitingNullNullNull() { LogCapture capture = new LogCapture(Level.DEBUG); logger.setLevel(Level.DEBUG); LogXF.exiting(logger, null, null, (String) null); assertEquals("null.null RETURN null", capture.getMessage()); } /** * Test LogXF.exiting with class and method. */ public void testExiting() { LogCapture capture = new LogCapture(Level.DEBUG); logger.setLevel(Level.DEBUG); LogXF.exiting(logger, "SomeClass", "someMethod"); assertEquals("SomeClass.someMethod RETURN", capture.getMessage()); } /** * Test LogXF.exiting with class, method and return value. */ public void testExitingWithValue() { LogCapture capture = new LogCapture(Level.DEBUG); logger.setLevel(Level.DEBUG); LogXF.exiting(logger, "SomeClass", "someMethod", "someValue"); assertEquals("SomeClass.someMethod RETURN someValue", capture.getMessage()); } /** * Test LogXF.exiting with class, method and bad return value. */ public void testExitingWithBadValue() { LogCapture capture = new LogCapture(Level.DEBUG); logger.setLevel(Level.DEBUG); LogXF.exiting(logger, "SomeClass", "someMethod", BadStringifier.INSTANCE); assertEquals("SomeClass.someMethod RETURN ?", capture.getMessage()); } /** * Test LogXF.throwing with null class, method and throwable. */ public void testThrowingNullNullNull() { LogCapture capture = new LogCapture(Level.DEBUG); logger.setLevel(Level.DEBUG); LogXF.throwing(logger, null, null, null); assertEquals("null.null THROW", capture.getMessage()); } /** * Test LogXF.exiting with class and method. */ public void testThrowing() { LogCapture capture = new LogCapture(Level.DEBUG); logger.setLevel(Level.DEBUG); LogXF.throwing(logger, "SomeClass", "someMethod", new IllegalArgumentException()); assertEquals("SomeClass.someMethod THROW", capture.getMessage()); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/DefaultThrowableRendererTest.java0000644000175000017500000000261211751454673030331 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; import org.apache.log4j.spi.ThrowableRenderer; public class DefaultThrowableRendererTest extends TestCase { public DefaultThrowableRendererTest(final String name) { super(name); } public void testDefaultRender() { ThrowableRenderer r = new DefaultThrowableRenderer(); Exception ex = new Exception(); String[] strRep = r.doRender(ex); assertNotNull(strRep); assertTrue(strRep.length > 0); for(int i = 0; i < strRep.length; i++) { assertNotNull(strRep[i]); } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/nt/0000755000175000017500000000000012126647422022314 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/nt/NTEventLogAppenderTest.java0000755000175000017500000000343111751454672027475 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.nt; import junit.framework.TestCase; import org.apache.log4j.Logger; import org.apache.log4j.LogManager; import org.apache.log4j.Level; import org.apache.log4j.BasicConfigurator; /** * * NTEventLogAppender tests. * * @author Curt Arnold */ public class NTEventLogAppenderTest extends TestCase { /** * Clean up configuration after each test. */ public void tearDown() { LogManager.shutdown(); } /** * Simple test of NTEventLogAppender. */ public void testSimple() { BasicConfigurator.configure(new NTEventLogAppender()); Logger logger = Logger.getLogger("org.apache.log4j.nt.NTEventLogAppenderTest"); int i = 0; logger.debug( "Message " + i++); logger.info( "Message " + i++); logger.warn( "Message " + i++); logger.error( "Message " + i++); logger.log(Level.FATAL, "Message " + i++); logger.debug("Message " + i++, new Exception("Just testing.")); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/TTCCLayoutTest.java0000644000175000017500000000653511751454673025351 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.helpers.DateLayoutTest; import org.apache.log4j.spi.LoggingEvent; /** * Test for TTCCLayout. * * @author Curt Arnold */ public class TTCCLayoutTest extends DateLayoutTest { /** * Construct new instance of TTCCLayoutTest. * * @param testName test name. */ public TTCCLayoutTest(final String testName) { super(testName, "text/plain", true, null, null); } /** * @{inheritDoc} */ protected Layout createLayout() { return new TTCCLayout(); } /** * Tests format. */ public void testFormat() { NDC.clear(); NDC.push("NDC goes here"); Logger logger = Logger.getLogger("org.apache.log4j.LayoutTest"); LoggingEvent event = new LoggingEvent( "org.apache.log4j.Logger", logger, Level.INFO, "Hello, World", null); TTCCLayout layout = (TTCCLayout) createLayout(); String result = layout.format(event); NDC.pop(); StringBuffer buf = new StringBuffer(100); layout.dateFormat(buf, event); buf.append('['); buf.append(event.getThreadName()); buf.append("] "); buf.append(event.getLevel().toString()); buf.append(' '); buf.append(event.getLoggerName()); buf.append(' '); buf.append("NDC goes here"); buf.append(" - "); buf.append(event.getMessage()); buf.append(System.getProperty("line.separator")); assertEquals(buf.toString(), result); } /** * Tests getThreadPrinting and setThreadPrinting. */ public void testGetSetThreadPrinting() { TTCCLayout layout = new TTCCLayout(); assertEquals(true, layout.getThreadPrinting()); layout.setThreadPrinting(false); assertEquals(false, layout.getThreadPrinting()); layout.setThreadPrinting(true); assertEquals(true, layout.getThreadPrinting()); } /** * Tests getCategoryPrefixing and setCategoryPrefixing. */ public void testGetSetCategoryPrefixing() { TTCCLayout layout = new TTCCLayout(); assertEquals(true, layout.getCategoryPrefixing()); layout.setCategoryPrefixing(false); assertEquals(false, layout.getCategoryPrefixing()); layout.setCategoryPrefixing(true); assertEquals(true, layout.getCategoryPrefixing()); } /** * Tests getContextPrinting and setContextPrinting. */ public void testGetSetContextPrinting() { TTCCLayout layout = new TTCCLayout(); assertEquals(true, layout.getContextPrinting()); layout.setContextPrinting(false); assertEquals(false, layout.getContextPrinting()); layout.setContextPrinting(true); assertEquals(true, layout.getContextPrinting()); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/net/0000755000175000017500000000000012126647422022461 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/net/ShortSocketServer.java0000644000175000017500000000531011751454672026770 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.net; import java.net.Socket; import java.net.ServerSocket; import org.apache.log4j.Logger; import org.apache.log4j.LogManager; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.MDC; import org.apache.log4j.helpers.LogLog; /** * This SocketServer exits after certain number of connections from a * client. This number is determined the totalsTest parameter, that is * the first argument on the commmand line. The second argument, * prefix, determines the prefix of the configuration file to * use. Each run of the server will use a different properties * file. For the i-th run, the path to the file is * (prefix+i+".properties"). * * @author Ceki Gulcu */ public class ShortSocketServer { static Logger cat = Logger.getLogger(ShortSocketServer.class); public static void main(String args[]) throws Exception { int totalTests = 0; String prefix = null; if(args.length == 2) { totalTests = Integer.parseInt(args[0]); prefix = args[1]; } else { usage("Wrong number of arguments."); } LogLog.debug("Listening on port " + SocketServerTestCase.PORT); ServerSocket serverSocket = new ServerSocket(SocketServerTestCase.PORT); MDC.put("hostID", "shortSocketServer"); for(int i = 1; i <= totalTests; i++) { PropertyConfigurator.configure(prefix+i+".properties"); 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."); SocketNode sn = new SocketNode(socket, LogManager.getLoggerRepository()); Thread t = new Thread(sn); t.start(); t.join(); } } static void usage(String msg) { System.err.println(msg); System.err.println( "Usage: java " +ShortSocketServer.class.getName() + " totalTests configFilePrefix"); System.exit(1); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/net/SocketAppenderTest.java0000644000175000017500000000537611751454672027114 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.net; import junit.framework.TestCase; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.xml.DOMConfigurator; public class SocketAppenderTest extends TestCase { /** * Create new instance. */ public SocketAppenderTest(final String testName) { super(testName); } /* JUnit's setUp and tearDown */ protected void setUp() { DOMConfigurator.configure("input/xml/SocketAppenderTestConfig.xml"); logger = Logger.getLogger(SocketAppenderTest.class); secondary = (LastOnlyAppender) Logger.getLogger( "org.apache.log4j.net.SocketAppenderTestDummy").getAppender("lastOnly"); } protected void tearDown() { } /* Tests */ public void testFallbackErrorHandlerWhenStarting() { String msg = "testFallbackErrorHandlerWhenStarting"; logger.debug(msg); // above debug log will fail and shoul be redirected to secondary appender assertEquals("SocketAppender with FallbackErrorHandler", msg, secondary.getLastMessage()); } /* Fields */ private static Logger logger; private static LastOnlyAppender secondary; /* Inner classes */ /** * Inner-class For debugging purposes only Saves last LoggerEvent */ static public class LastOnlyAppender extends AppenderSkeleton { protected void append(LoggingEvent event) { this.lastEvent = event; } public boolean requiresLayout() { return false; } public void close() { this.closed = true; } /** * @return last appended LoggingEvent's message */ public String getLastMessage() { if (this.lastEvent != null) return this.lastEvent.getMessage().toString(); else return ""; } private LoggingEvent lastEvent; }; }apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/net/SocketServerTestCase.java0000644000175000017500000003412211751454672027407 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.net; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; import org.apache.log4j.*; import org.apache.log4j.util.*; import org.apache.log4j.Logger; import org.apache.log4j.NDC; import org.apache.log4j.xml.XLevel; /** @author Ceki Gülcü */ public class SocketServerTestCase extends TestCase { static String TEMP = "output/temp"; static String FILTERED = "output/filtered"; // %5p %x [%t] %c %m%n // DEBUG T1 [main] org.apache.log4j.net.SocketAppenderTestCase Message 1 static String PAT1 = "^(TRACE|DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) T1 \\[main]\\ " + ".* Message \\d{1,2}"; // DEBUG T2 [main] ? (?:?) Message 1 static String PAT2 = "^(TRACE|DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) T2 \\[main]\\ " + "\\? \\(\\?:\\?\\) Message \\d{1,2}"; // DEBUG T3 [main] org.apache.log4j.net.SocketServerTestCase (SocketServerTestCase.java:121) Message 1 static String PAT3 = "^(TRACE|DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) T3 \\[main]\\ " + "org.apache.log4j.net.SocketServerTestCase " + "\\(SocketServerTestCase.java:\\d{3}\\) Message \\d{1,2}"; // DEBUG some T4 MDC-TEST4 [main] SocketAppenderTestCase - Message 1 // DEBUG some T4 MDC-TEST4 [main] SocketAppenderTestCase - Message 1 static String PAT4 = "^(TRACE|DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some T4 MDC-TEST4 \\[main]\\" + " (root|SocketServerTestCase) - Message \\d{1,2}"; static String PAT5 = "^(TRACE|DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some5 T5 MDC-TEST5 \\[main]\\" + " (root|SocketServerTestCase) - Message \\d{1,2}"; static String PAT6 = "^(TRACE|DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some6 T6 client-test6 MDC-TEST6" + " \\[main]\\ (root|SocketServerTestCase) - Message \\d{1,2}"; static String PAT7 = "^(TRACE|DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some7 T7 client-test7 MDC-TEST7" + " \\[main]\\ (root|SocketServerTestCase) - Message \\d{1,2}"; // DEBUG some8 T8 shortSocketServer MDC-TEST7 [main] SocketServerTestCase - Message 1 static String PAT8 = "^(TRACE|DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some8 T8 shortSocketServer" + " MDC-TEST8 \\[main]\\ (root|SocketServerTestCase) - Message \\d{1,2}"; static String EXCEPTION1 = "java.lang.Exception: Just testing"; static String EXCEPTION2 = "\\s*at .*\\(.*\\)"; static String EXCEPTION3 = "\\s*at .*\\(Native Method\\)"; static String EXCEPTION4 = "\\s*at .*\\(.*Compiled Code\\)"; static String EXCEPTION5 = "\\s*at .*\\(.*libgcj.*\\)"; static Logger logger = Logger.getLogger(SocketServerTestCase.class); static public final int PORT = 12345; static Logger rootLogger = Logger.getRootLogger(); SocketAppender socketAppender; public SocketServerTestCase(String name) { super(name); } public void setUp() { System.out.println("Setting up test case."); } public void tearDown() { System.out.println("Tearing down test case."); socketAppender = null; rootLogger.removeAllAppenders(); } /** * The pattern on the server side: %5p %x [%t] %c %m%n * * We are testing NDC functionality across the wire. */ public void test1() throws Exception { socketAppender = new SocketAppender("localhost", PORT); rootLogger.addAppender(socketAppender); common("T1", "key1", "MDC-TEST1"); delay(1); ControlFilter cf = new ControlFilter(new String[]{PAT1, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf, new LineNumberFilter(), new JunitTestRunnerFilter(), new SunReflectFilter() }); assertTrue(Compare.compare(FILTERED, "witness/socketServer.1")); } /** * The pattern on the server side: %5p %x [%t] %C (%F:%L) %m%n * * We are testing NDC across the wire. Localization is turned off by * default so it is not tested here even if the conversion pattern * uses localization. */ public void test2() throws Exception { socketAppender = new SocketAppender("localhost", PORT); rootLogger.addAppender(socketAppender); common("T2", "key2", "MDC-TEST2"); delay(1); ControlFilter cf = new ControlFilter(new String[]{PAT2, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf, new LineNumberFilter(), new JunitTestRunnerFilter(), new SunReflectFilter() }); assertTrue(Compare.compare(FILTERED, "witness/socketServer.2")); } /** * The pattern on the server side: %5p %x [%t] %C (%F:%L) %m%n * meaning that we are testing NDC and locatization functionality * across the wire. */ public void test3() throws Exception { socketAppender = new SocketAppender("localhost", PORT); socketAppender.setLocationInfo(true); rootLogger.addAppender(socketAppender); common("T3", "key3", "MDC-TEST3"); delay(1); ControlFilter cf = new ControlFilter(new String[]{PAT3, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf, new LineNumberFilter(), new JunitTestRunnerFilter(), new SunReflectFilter() }); assertTrue(Compare.compare(FILTERED, "witness/socketServer.3")); } /** * The pattern on the server side: %5p %x %X{key1}%X{key4} [%t] %c{1} - %m%n * meaning that we are testing NDC, MDC and localization functionality across * the wire. */ public void test4() throws Exception { socketAppender = new SocketAppender("localhost", PORT); socketAppender.setLocationInfo(true); rootLogger.addAppender(socketAppender); NDC.push("some"); common("T4", "key4", "MDC-TEST4"); NDC.pop(); delay(1); // // These tests check MDC operation which // requires JDK 1.2 or later if(!System.getProperty("java.version").startsWith("1.1.")) { ControlFilter cf = new ControlFilter(new String[]{PAT4, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf, new LineNumberFilter(), new JunitTestRunnerFilter(), new SunReflectFilter() }); assertTrue(Compare.compare(FILTERED, "witness/socketServer.4")); } } /** * The pattern on the server side: %5p %x %X{key1}%X{key5} [%t] %c{1} - %m%n * * The test case uses wraps an AsyncAppender around the * SocketAppender. This tests was written specifically for bug * report #9155. * Prior to the bug fix the output on the server did not contain the * MDC-TEST5 string because the MDC clone operation (in getMDCCopy * method) operation is performed twice, once from the main thread * which is correct, and a second time from the AsyncAppender's * dispatch thread which is incrorrect. */ public void test5() throws Exception { socketAppender = new SocketAppender("localhost", PORT); socketAppender.setLocationInfo(true); AsyncAppender asyncAppender = new AsyncAppender(); asyncAppender.setLocationInfo(true); asyncAppender.addAppender(socketAppender); rootLogger.addAppender(asyncAppender); NDC.push("some5"); common("T5", "key5", "MDC-TEST5"); NDC.pop(); delay(2); // // These tests check MDC operation which // requires JDK 1.2 or later if(!System.getProperty("java.version").startsWith("1.1.")) { ControlFilter cf = new ControlFilter(new String[]{PAT5, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf, new LineNumberFilter(), new JunitTestRunnerFilter(), new SunReflectFilter() }); assertTrue(Compare.compare(FILTERED, "witness/socketServer.5")); } } /** * The pattern on the server side: %5p %x %X{hostID}${key6} [%t] %c{1} - %m%n * * This test checks whether client-side MDC overrides the server side. * It uses an AsyncAppender encapsulating a SocketAppender */ public void test6() throws Exception { socketAppender = new SocketAppender("localhost", PORT); socketAppender.setLocationInfo(true); AsyncAppender asyncAppender = new AsyncAppender(); asyncAppender.setLocationInfo(true); asyncAppender.addAppender(socketAppender); rootLogger.addAppender(asyncAppender); NDC.push("some6"); MDC.put("hostID", "client-test6"); common("T6", "key6", "MDC-TEST6"); NDC.pop(); MDC.remove("hostID"); delay(2); // // These tests check MDC operation which // requires JDK 1.2 or later if(!System.getProperty("java.version").startsWith("1.1.")) { ControlFilter cf = new ControlFilter(new String[]{PAT6, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf, new LineNumberFilter(), new JunitTestRunnerFilter(), new SunReflectFilter() }); assertTrue(Compare.compare(FILTERED, "witness/socketServer.6")); } } /** * The pattern on the server side: %5p %x %X{hostID}${key7} [%t] %c{1} - %m%n * * This test checks whether client-side MDC overrides the server side. */ public void test7() throws Exception { socketAppender = new SocketAppender("localhost", PORT); socketAppender.setLocationInfo(true); rootLogger.addAppender(socketAppender); NDC.push("some7"); MDC.put("hostID", "client-test7"); common("T7", "key7", "MDC-TEST7"); NDC.pop(); MDC.remove("hostID"); delay(2); // // These tests check MDC operation which // requires JDK 1.2 or later if(!System.getProperty("java.version").startsWith("1.1.")) { ControlFilter cf = new ControlFilter(new String[]{PAT7, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf, new LineNumberFilter(), new JunitTestRunnerFilter(), new SunReflectFilter() }); assertTrue(Compare.compare(FILTERED, "witness/socketServer.7")); } } /** * The pattern on the server side: %5p %x %X{hostID} ${key8} [%t] %c{1} - %m%n * * This test checks whether server side MDC works. */ public void test8() throws Exception { socketAppender = new SocketAppender("localhost", PORT); socketAppender.setLocationInfo(true); rootLogger.addAppender(socketAppender); NDC.push("some8"); // // The test has relied on the receiving code to // combine the sent MDC with the receivers MDC // (which contains a value for hostID). // The mechanism of how that happens is not clear // and it does not work with Apache Harmony. // Unclear if it is a Harmony issue. if (System.getProperty("java.vendor").indexOf("Apache") != -1) { MDC.put("hostID", "shortSocketServer"); } common("T8", "key8", "MDC-TEST8"); NDC.pop(); delay(2); // // These tests check MDC operation which // requires JDK 1.2 or later if(!System.getProperty("java.version").startsWith("1.1.")) { ControlFilter cf = new ControlFilter(new String[]{PAT8, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf, new LineNumberFilter(), new JunitTestRunnerFilter(), new SunReflectFilter() }); assertTrue(Compare.compare(FILTERED, "witness/socketServer.8")); } } static void common(String dc, String key, Object o) { String oldThreadName = Thread.currentThread().getName(); Thread.currentThread().setName("main"); int i = -1; NDC.push(dc); MDC.put(key, o); Logger root = Logger.getRootLogger(); logger.setLevel(Level.DEBUG); rootLogger.setLevel(Level.DEBUG); logger.log(XLevel.TRACE, "Message " + ++i); logger.setLevel(Level.TRACE); rootLogger.setLevel(Level.TRACE); logger.trace("Message " + ++i); root.trace("Message " + ++i); logger.debug("Message " + ++i); root.debug("Message " + ++i); logger.info("Message " + ++i); logger.warn("Message " + ++i); logger.log(XLevel.LETHAL, "Message " + ++i); //5 Exception e = new Exception("Just testing"); logger.debug("Message " + ++i, e); root.error("Message " + ++i, e); NDC.pop(); MDC.remove(key); Thread.currentThread().setName(oldThreadName); } public void delay(int secs) { try {Thread.sleep(secs*1000);} catch(Exception e) {} } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new SocketServerTestCase("test1")); suite.addTest(new SocketServerTestCase("test2")); suite.addTest(new SocketServerTestCase("test3")); suite.addTest(new SocketServerTestCase("test4")); suite.addTest(new SocketServerTestCase("test5")); suite.addTest(new SocketServerTestCase("test6")); suite.addTest(new SocketServerTestCase("test7")); suite.addTest(new SocketServerTestCase("test8")); return suite; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/net/SMTPAppenderTest.java0000644000175000017500000000406711751454672026443 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.net; import junit.framework.TestCase; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.TriggeringEventEvaluator; import org.apache.log4j.xml.DOMConfigurator; /** * Tests for SMTPAppender. */ public class SMTPAppenderTest extends TestCase { public SMTPAppenderTest(final String testName) { super(testName); } /** * Reset configuration after every test. */ public void tearDown() { LogManager.resetConfiguration(); } /** * Trivial implementation of TriggeringEventEvaluator. */ public static final class MockTriggeringEventEvaluator implements TriggeringEventEvaluator { /** * {@inheritDoc} */ public boolean isTriggeringEvent(final LoggingEvent event) { return true; } } /** * Tests that triggeringPolicy element will set evaluator. */ public void testTrigger() { DOMConfigurator.configure("input/xml/smtpAppender1.xml"); SMTPAppender appender = (SMTPAppender) Logger.getRootLogger().getAppender("A1"); TriggeringEventEvaluator evaluator = appender.getEvaluator(); assertTrue(evaluator instanceof MockTriggeringEventEvaluator); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/net/SyslogAppenderTest.java0000644000175000017500000004470511751454672027143 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.net; import junit.framework.TestCase; import org.apache.log4j.AsyncAppender; import org.apache.log4j.Layout; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.VectorErrorHandler; import org.apache.log4j.HTMLLayout; import java.util.StringTokenizer; import java.net.DatagramSocket; import java.net.DatagramPacket; import java.text.SimpleDateFormat; import java.util.Locale; import java.util.Date; import java.util.Calendar; /** * Tests for SyslogAppender * * * */ public class SyslogAppenderTest extends TestCase { /** * Create new instance of SyslogAppenderTest. * @param testName test name */ public SyslogAppenderTest(final String testName) { super(testName); } /** * Resets configuration after every test. */ public void tearDown() { LogManager.resetConfiguration(); } /** * Test default constructor. */ public void testDefaultConstructor() { SyslogAppender appender = new SyslogAppender(); assertEquals("user", appender.getFacility()); assertEquals(false, appender.getFacilityPrinting()); assertNull(appender.getLayout()); assertNull(appender.getSyslogHost()); assertTrue(appender.requiresLayout()); } /** * Test two parameter constructor. */ public void testTwoParamConstructor() { Layout layout = new PatternLayout(); SyslogAppender appender = new SyslogAppender(layout, 24); assertEquals("daemon", appender.getFacility()); assertEquals(false, appender.getFacilityPrinting()); assertEquals(layout, appender.getLayout()); assertNull(appender.getSyslogHost()); assertTrue(appender.requiresLayout()); } /** * Test two parameter constructor with unexpected facility. */ public void testTwoParamConstructorBadFacility() { Layout layout = new PatternLayout(); SyslogAppender appender = new SyslogAppender(layout, 25); assertEquals("user", appender.getFacility()); assertEquals(false, appender.getFacilityPrinting()); assertEquals(layout, appender.getLayout()); assertNull(appender.getSyslogHost()); assertTrue(appender.requiresLayout()); } /** * Test three parameter constructor. */ public void testThreeParamConstructor() { Layout layout = new PatternLayout(); SyslogAppender appender = new SyslogAppender(layout, "syslog.example.org", 24); assertEquals("daemon", appender.getFacility()); assertEquals(false, appender.getFacilityPrinting()); assertEquals(layout, appender.getLayout()); assertEquals("syslog.example.org", appender.getSyslogHost()); assertTrue(appender.requiresLayout()); } /** * Test getFacilityString for expected facility codes. */ public void testGetFacilityString() { String expected = "kern user mail daemon auth syslog lpr news " + "uucp cron authpriv ftp local0 local1 local2 local3 " + "local4 local5 local6 local7 "; StringBuffer actual = new StringBuffer(); for (int i = 0; i <= 11; i++) { actual.append(SyslogAppender.getFacilityString(i << 3)); actual.append(' '); } for (int i = 16; i <= 23; i++) { actual.append(SyslogAppender.getFacilityString(i << 3)); actual.append(' '); } assertEquals(expected, actual.toString()); } /** * Test getFacilityString for some unexpected facility codes. */ public void testGetFacilityStringUnexpected() { assertNull(SyslogAppender.getFacilityString(1)); assertNull(SyslogAppender.getFacilityString(12 << 3)); } /** * Test getFacility with a bogus facility name. */ public void testGetFacilityBogus() { assertEquals(-1, SyslogAppender.getFacility("bogus")); } /** * Test getFacility with a null facility name. */ public void testGetFacilityNull() { assertEquals(-1, SyslogAppender.getFacility(null)); } /** * Test getFacility for expected system facility names. */ public void testGetFacilitySystemNames() { String[] names = new String[] { "kErn", "usEr", "MaIL", "daemOn", "auTh", "syslOg", "lPr", "newS", "Uucp", "croN", "authprIv", "ftP" }; for (int i = 0; i <= 11; i++) { assertEquals(i << 3, SyslogAppender.getFacility(names[i])); } } /** * Test getFacility for expected system facility names. */ public void testGetFacilityLocalNames() { String[] names = new String[] { "lOcal0", "LOCAL1", "loCal2", "locAl3", "locaL4", "local5", "LOCal6", "loCAL7" }; for (int i = 0; i <= 7; i++) { assertEquals((16 + i) << 3, SyslogAppender.getFacility(names[i])); } } /** * Test setFacilityPrinting. */ public void testSetFacilityPrinting() { SyslogAppender appender = new SyslogAppender(); assertFalse(appender.getFacilityPrinting()); appender.setFacilityPrinting(true); assertTrue(appender.getFacilityPrinting()); appender.setFacilityPrinting(false); assertFalse(appender.getFacilityPrinting()); } /** * Test of SyslogAppender constants. */ public void testConstants() { assertEquals(0 << 3, SyslogAppender.LOG_KERN); assertEquals(1 << 3, SyslogAppender.LOG_USER); assertEquals(2 << 3, SyslogAppender.LOG_MAIL); assertEquals(3 << 3, SyslogAppender.LOG_DAEMON); assertEquals(4 << 3, SyslogAppender.LOG_AUTH); assertEquals(5 << 3, SyslogAppender.LOG_SYSLOG); assertEquals(6 << 3, SyslogAppender.LOG_LPR); assertEquals(7 << 3, SyslogAppender.LOG_NEWS); assertEquals(8 << 3, SyslogAppender.LOG_UUCP); assertEquals(9 << 3, SyslogAppender.LOG_CRON); assertEquals(10 << 3, SyslogAppender.LOG_AUTHPRIV); assertEquals(11 << 3, SyslogAppender.LOG_FTP); assertEquals(16 << 3, SyslogAppender.LOG_LOCAL0); assertEquals(17 << 3, SyslogAppender.LOG_LOCAL1); assertEquals(18 << 3, SyslogAppender.LOG_LOCAL2); assertEquals(19 << 3, SyslogAppender.LOG_LOCAL3); assertEquals(20 << 3, SyslogAppender.LOG_LOCAL4); assertEquals(21 << 3, SyslogAppender.LOG_LOCAL5); assertEquals(22 << 3, SyslogAppender.LOG_LOCAL6); assertEquals(23 << 3, SyslogAppender.LOG_LOCAL7); } /** * Test setFacility with null. * Should have no effect. */ public void testSetFacilityKern() { SyslogAppender appender = new SyslogAppender(); appender.setFacility("kern"); appender.setFacility(null); assertEquals("kern", appender.getFacility()); } /** * Test setFacility with null. * Should have no effect. */ public void testSetFacilityNull() { SyslogAppender appender = new SyslogAppender(); appender.setFacility("kern"); appender.setFacility(null); assertEquals("kern", appender.getFacility()); } /** * Test setFacility with bogus value. * Should reset to user. */ public void testSetFacilityBogus() { SyslogAppender appender = new SyslogAppender(); appender.setFacility("kern"); appender.setFacility("bogus"); assertEquals("user", appender.getFacility()); } /** * Tests calling setFacility after appender has been activated. */ public void testSetFacilityAfterActivation() { SyslogAppender appender = new SyslogAppender(); appender.setName("foo"); appender.setThreshold(Level.INFO); appender.setSyslogHost("localhost"); appender.setFacility("user"); appender.setLayout(new PatternLayout("%m%n")); VectorErrorHandler errorHandler = new VectorErrorHandler(); appender.setErrorHandler(errorHandler); appender.activateOptions(); appender.setFacility("kern"); assertEquals("kern", appender.getFacility()); } /** * Tests that append method drops messages below threshold. * Can't reach isSevereAsThreshold call in SyslogAppender.append * since it is checked in AppenderSkeleton.doAppend. */ public void testAppendBelowThreshold() { SyslogAppender appender = new SyslogAppender(); appender.setThreshold(Level.ERROR); appender.activateOptions(); Logger logger = Logger.getRootLogger(); logger.addAppender(appender); logger.info( "Should not be logged by SyslogAppenderTest.testAppendBelowThreshold."); } /** * Tests that append method drops messages below threshold. */ public void testAppendNoHost() { SyslogAppender appender = new SyslogAppender(); appender.setName("foo"); appender.setThreshold(Level.INFO); VectorErrorHandler errorHandler = new VectorErrorHandler(); appender.setErrorHandler(errorHandler); appender.setLayout(new PatternLayout("%m%n")); appender.activateOptions(); Logger logger = Logger.getRootLogger(); logger.addAppender(appender); logger.info( "Should not be logged by SyslogAppenderTest.testAppendNoHost."); assertEquals(1, errorHandler.size()); // // Appender is misspelled in implementation // assertEquals( "No syslog host is set for SyslogAppedender named \"foo\".", errorHandler.getMessage(0)); } /** * Tests append method under normal conditions. */ public void testAppend() { SyslogAppender appender = new SyslogAppender(); appender.setName("foo"); appender.setThreshold(Level.INFO); appender.setSyslogHost("localhost"); appender.setFacility("user"); appender.setLayout(new PatternLayout("%m%n")); VectorErrorHandler errorHandler = new VectorErrorHandler(); appender.setErrorHandler(errorHandler); appender.activateOptions(); // // wrap SyslogAppender with an Async since appender may // hang if syslogd is not accepting network messages // AsyncAppender asyncAppender = new AsyncAppender(); asyncAppender.addAppender(appender); asyncAppender.activateOptions(); Logger logger = Logger.getRootLogger(); logger.addAppender(asyncAppender); Exception e = new Exception("Expected exception from SyslogAppenderTest.testAppend"); logger.info( "Expected message from log4j unit test SyslogAppenderTest.testAppend.", e); assertEquals(0, errorHandler.size()); } /** * Tests SyslogAppender with IPv6 address. */ public void testIPv6() { SyslogAppender appender = new SyslogAppender(); appender.setSyslogHost("::1"); } /** * Tests SyslogAppender with IPv6 address enclosed in square brackets. */ public void testIPv6InBrackets() { SyslogAppender appender = new SyslogAppender(); appender.setSyslogHost("[::1]"); } /** * Tests SyslogAppender with IPv6 address enclosed in square brackets * followed by port specification. */ public void testIPv6AndPort() { SyslogAppender appender = new SyslogAppender(); appender.setSyslogHost("[::1]:1514"); } /** * Tests SyslogAppender with host name enclosed in square brackets * followed by port specification. */ public void testHostNameAndPort() { SyslogAppender appender = new SyslogAppender(); appender.setSyslogHost("localhost:1514"); } /** * Tests SyslogAppender with IPv4 address followed by port specification. */ public void testIPv4AndPort() { SyslogAppender appender = new SyslogAppender(); appender.setSyslogHost("127.0.0.1:1514"); } private static String[] log(final boolean header, final String msg, final Exception ex, final int packets) throws Exception { DatagramSocket ds = new DatagramSocket(); ds.setSoTimeout(2000); SyslogAppender appender = new SyslogAppender(); appender.setSyslogHost("localhost:" + ds.getLocalPort()); appender.setName("name"); appender.setHeader(header); PatternLayout pl = new PatternLayout("%m"); appender.setLayout(pl); appender.activateOptions(); Logger l = Logger.getRootLogger(); l.addAppender(appender); if (ex == null) { l.info(msg); } else { l.error(msg, ex); } appender.close(); String[] retval = new String[packets]; byte[] buf = new byte[1000]; for(int i = 0; i < packets; i++) { DatagramPacket p = new DatagramPacket(buf, 0, buf.length); ds.receive(p); retval[i] = new String(p.getData(), 0, p.getLength()); } ds.close(); return retval; } public void testActualLogging() throws Exception { String s = log(false, "greetings", null, 1)[0]; StringTokenizer st = new StringTokenizer(s, "<>() "); assertEquals("14", st.nextToken()); assertEquals("greetings", st.nextToken()); } /** * Exception with printStackTrace that breaks earlier SyslogAppender. */ private static class MishandledException extends Exception { private static final long serialVersionUID = 1L; /* * Create new instance. */ public MishandledException() { } /** * Print stack trace. * @param w print writer, may not be null. */ public void printStackTrace(final java.io.PrintWriter w) { w.println("Mishandled stack trace follows:"); w.println(""); w.println("No tab here"); w.println("\ttab here"); w.println("\t"); } } /** * Tests fix for bug 40502. * @throws Exception on IOException. */ public void testBadTabbing() throws Exception { String[] s = log(false, "greetings", new MishandledException(), 6); StringTokenizer st = new StringTokenizer(s[0], "<>() "); assertEquals("11", st.nextToken()); assertEquals("greetings", st.nextToken()); assertEquals("<11>Mishandled stack trace follows:", s[1]); assertEquals("<11>", s[2]); assertEquals("<11>No tab here", s[3]); assertEquals("<11>" + SyslogAppender.TAB + "tab here", s[4]); assertEquals("<11>" + SyslogAppender.TAB, s[5]); } /** * Tests presence of timestamp if header = true. * * @throws Exception if IOException. */ public void testHeaderLogging() throws Exception { Date preDate = new Date(); String s = log(true, "greetings", null, 1)[0]; Date postDate = new Date(); assertEquals("<14>", s.substring(0, 4)); String syslogDateStr = s.substring(4, 20); SimpleDateFormat fmt = new SimpleDateFormat("MMM dd HH:mm:ss ", Locale.ENGLISH); Date syslogDate = fmt.parse(syslogDateStr); Calendar cal = Calendar.getInstance(Locale.ENGLISH); cal.setTime(syslogDate); int syslogMonth = cal.get(Calendar.MONTH); int syslogDay = cal.get(Calendar.DATE); if (syslogDay < 10) { assertEquals(' ', syslogDateStr.charAt(4)); } cal.setTime(preDate); int preMonth = cal.get(Calendar.MONTH); cal.set(Calendar.MILLISECOND, 0); preDate = cal.getTime(); int syslogYear; if (preMonth == syslogMonth) { syslogYear = cal.get(Calendar.YEAR); } else { cal.setTime(postDate); syslogYear = cal.get(Calendar.YEAR); } cal.setTime(syslogDate); cal.set(Calendar.YEAR, syslogYear); syslogDate = cal.getTime(); assertTrue(syslogDate.compareTo(preDate) >= 0); assertTrue(syslogDate.compareTo(postDate) <= 0); } /** * Tests that any header or footer in layout is sent. * @throws Exception if exception during test. */ public void testLayoutHeader() throws Exception { DatagramSocket ds = new DatagramSocket(); ds.setSoTimeout(2000); SyslogAppender appender = new SyslogAppender(); appender.setSyslogHost("localhost:" + ds.getLocalPort()); appender.setName("name"); appender.setHeader(false); HTMLLayout pl = new HTMLLayout(); appender.setLayout(pl); appender.activateOptions(); Logger l = Logger.getRootLogger(); l.addAppender(appender); l.info("Hello, World"); appender.close(); String[] s = new String[3]; byte[] buf = new byte[1000]; for(int i = 0; i < 3; i++) { DatagramPacket p = new DatagramPacket(buf, 0, buf.length); ds.receive(p); s[i] = new String(p.getData(), 0, p.getLength()); } ds.close(); assertEquals("<14>", s[2].substring(0,12)); } /** * Tests that syslog packets do not exceed 1024 bytes. * See bug 42087. * @throws Exception if exception during test. */ public void testBigPackets() throws Exception { DatagramSocket ds = new DatagramSocket(); ds.setSoTimeout(2000); SyslogAppender appender = new SyslogAppender(); appender.setSyslogHost("localhost:" + ds.getLocalPort()); appender.setName("name"); appender.setHeader(false); PatternLayout pl = new PatternLayout("%m"); appender.setLayout(pl); appender.activateOptions(); Logger l = Logger.getRootLogger(); l.addAppender(appender); StringBuffer msgbuf = new StringBuffer(); while(msgbuf.length() < 8000) { msgbuf.append("0123456789"); } String msg = msgbuf.toString(); l.info(msg); appender.close(); String[] s = new String[8]; byte[] buf = new byte[1200]; for(int i = 0; i < 8; i++) { DatagramPacket p = new DatagramPacket(buf, 0, buf.length); ds.receive(p); assertTrue(p.getLength() <= 1024); s[i] = new String(p.getData(), 0, p.getLength()); } ds.close(); StringBuffer rcvbuf = new StringBuffer(s[0]); rcvbuf.delete(0, 4); for(int i = 1; i < 8; i++) { rcvbuf.setLength(rcvbuf.length() - 3); rcvbuf.append(s[i].substring(s[i].indexOf("...") + 3)); } assertEquals(msg.length(), rcvbuf.length()); assertEquals(msg, rcvbuf.toString()); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/net/TelnetAppenderTest.java0000644000175000017500000000440011751454672027102 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.net; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import junit.framework.TestCase; public class TelnetAppenderTest extends TestCase { int port = 54353; ByteArrayOutputStream bo = new ByteArrayOutputStream(); public class ReadThread extends Thread { public void run() { try { Socket s = new Socket("localhost", port); InputStream i = s.getInputStream(); while (!Thread.interrupted()) { int c = i.read(); if (c == -1) break; bo.write(c); } s.close(); } catch (IOException e) { e.printStackTrace(); } } } public void testIt() throws Exception { int oldActive = Thread.activeCount(); TelnetAppender ta = new TelnetAppender(); ta.setName("ta"); ta.setPort(port); ta.setLayout(new PatternLayout("%p - %m")); ta.activateOptions(); Logger l = Logger.getLogger("x"); l.addAppender(ta); Thread t = new ReadThread(); t.start(); Thread.sleep(200); l.info("hi"); Thread.sleep(1000); ta.close(); Thread.sleep(200); t.interrupt(); t.join(); String s = bo.toString(); assertTrue(s.endsWith("INFO - hi")); if(System.getProperty("java.vendor").indexOf("Free") == -1) { assertEquals(oldActive, Thread.activeCount()); } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/HTMLLayoutTest.java0000644000175000017500000001602311751454673025351 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.spi.LoggingEvent; import org.w3c.dom.Document; import org.xml.sax.InputSource; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.Reader; import java.io.StringReader; import java.util.Hashtable; /** * Test for HTMLLayout. * * @author Curt Arnold */ public class HTMLLayoutTest extends LayoutTest { /** * Construct new instance of XMLLayoutTest. * * @param testName test name. */ public HTMLLayoutTest(final String testName) { super(testName, "text/html", false, null, null); } /** * @{inheritDoc} */ protected Layout createLayout() { return new HTMLLayout(); } /** * Parses the string as the body of an XML document and returns the document element. * @param source source string. * @return document element. * @throws Exception if parser can not be constructed or source is not a valid XML document. */ private Document parse(final String source) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false); factory.setCoalescing(true); DocumentBuilder builder = factory.newDocumentBuilder(); Reader reader = new StringReader(source); return builder.parse(new InputSource(reader)); } /** * Tests formatted results. * @throws Exception if unable to create parser or output is not valid XML. */ public void testFormat() throws Exception { Logger logger = Logger.getLogger("org.apache.log4j.xml.HTMLLayoutTest"); NDC.push("NDC goes here"); LoggingEvent event = new LoggingEvent( "org.apache.log4j.Logger", logger, Level.INFO, "Hello, World", null); HTMLLayout layout = (HTMLLayout) createLayout(); layout.setLocationInfo(true); String result = layout.format(event); NDC.pop(); String src = "]>" + result + ""; parse(src); } /** * Tests getHeader. */ public void testGetHeader() { assertEquals("", createLayout().getFooter().substring(0, 8)); } /** * Tests getLocationInfo and setLocationInfo. */ public void testGetSetLocationInfo() { HTMLLayout layout = new HTMLLayout(); assertEquals(false, layout.getLocationInfo()); layout.setLocationInfo(true); assertEquals(true, layout.getLocationInfo()); layout.setLocationInfo(false); assertEquals(false, layout.getLocationInfo()); } /** * Tests activateOptions(). */ public void testActivateOptions() { HTMLLayout layout = new HTMLLayout(); layout.activateOptions(); } /** * Tests getTitle and setTitle. */ public void testGetSetTitle() { HTMLLayout layout = new HTMLLayout(); assertEquals("Log4J Log Messages", layout.getTitle()); layout.setTitle(null); assertNull(layout.getTitle()); String newTitle = "A treatise on messages of log persuasion"; layout.setTitle(newTitle); assertEquals(newTitle, layout.getTitle()); } /** * Tests buffer downsizing and DEBUG and WARN colorization code paths. */ public void testFormatResize() { Logger logger = Logger.getLogger("org.apache.log4j.xml.HTMLLayoutTest"); NDC.clear(); char[] msg = new char[2000]; for (int i = 0; i < msg.length; i++) { msg[i] = 'A'; } LoggingEvent event1 = new LoggingEvent( "org.apache.log4j.Logger", logger, Level.DEBUG, new String(msg), null); HTMLLayout layout = (HTMLLayout) createLayout(); layout.setLocationInfo(true); String result = layout.format(event1); Exception ex = new IllegalArgumentException("'foo' is not a valid value."); LoggingEvent event2 = new LoggingEvent( "org.apache.log4j.Logger", logger, Level.WARN, "Hello, World", ex); result = layout.format(event2); assertEquals( Layout.LINE_SEP + "", result.substring(0, Layout.LINE_SEP.length() + 4)); } /** * Level with arbitrary toString value. */ private static final class ProblemLevel extends Level { private static final long serialVersionUID = 1L; /** * Construct new instance. * @param levelName level name, may not be null. */ public ProblemLevel(final String levelName) { super(6000, levelName, 6); } } /** * Tests problematic characters in multiple fields. * @throws Exception if parser can not be constructed * or source is not a valid XML document. */ public void testProblemCharacters() throws Exception { String problemName = "com.example.bar<>&\"'"; Logger logger = Logger.getLogger(problemName); Level level = new ProblemLevel(problemName); Exception ex = new IllegalArgumentException(problemName); String threadName = Thread.currentThread().getName(); Thread.currentThread().setName(problemName); NDC.push(problemName); Hashtable mdcMap = MDC.getContext(); if (mdcMap != null) { mdcMap.clear(); } MDC.put(problemName, problemName); LoggingEvent event = new LoggingEvent( problemName, logger, level, problemName, ex); HTMLLayout layout = (HTMLLayout) createLayout(); String result = layout.format(event); mdcMap = MDC.getContext(); if (mdcMap != null) { mdcMap.clear(); } Thread.currentThread().setName(threadName); // // do a little fixup to make output XHTML // StringBuffer buf = new StringBuffer( "]>"); buf.append(result); buf.append("
"); String doc = buf.toString(); for(int i = doc.lastIndexOf("
"); i != -1; i = doc.lastIndexOf("
", i - 1)) { buf.replace(i, i + 4, "
"); } parse(buf.toString()); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/LogCapture.java0000755000175000017500000000421011751454673024612 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.Assert; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.VectorAppender; import org.apache.log4j.spi.LoggingEvent; import java.util.Vector; /** * Helper class to set up and capture log messages. */ public class LogCapture { /** * Appender. */ private final VectorAppender appender; /** * Expected level. */ private final Level level; /** * Creates new instance of LogCapture. * */ public LogCapture(final Level level) { this.level = level; Logger root = Logger.getRootLogger(); appender = new VectorAppender(); root.addAppender(appender); } /** * Get message. * @return rendered message, null if no logging event captured. */ public String getMessage() { Vector vector = appender.getVector(); String msg = null; switch (vector.size()) { case 0: break; case 1: LoggingEvent event = (LoggingEvent) vector.elementAt(0); Assert.assertNotNull(event); Assert.assertEquals(level, event.getLevel()); msg = event.getRenderedMessage(); break; default: Assert.fail("More than one request captured"); } return msg; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/VectorAppender.java0000644000175000017500000000346711751454673025500 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import java.util.Vector; import org.apache.log4j.spi.LoggingEvent; /** An appender that appends logging events to a vector. @author Ceki Gülcü */ public class VectorAppender extends AppenderSkeleton { public Vector vector; public VectorAppender() { vector = new Vector(); } /** Does nothing. */ public void activateOptions() { } /** This method is called by the {@link AppenderSkeleton#doAppend} method. */ public void append(LoggingEvent event) { //System.out.println("---Vector appender called with message ["+event.getRenderedMessage()+"]."); //System.out.flush(); try { Thread.sleep(100); } catch(Exception e) { } vector.addElement(event); } public Vector getVector() { return vector; } public synchronized void close() { if(this.closed) return; this.closed = true; } public boolean isClosed() { return closed; } public boolean requiresLayout() { return false; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/EnhancedMyPatternLayout.java0000644000175000017500000000331211751454673027313 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.helpers.PatternParser; /** Example showing how to extend EnhancedPatternLayout to recognize additional conversion characters.

In this case MyPatternLayout recognizes %# conversion pattern. It outputs the value of an internal counter which is also incremented at each call.

See source code for more details. @see MyPatternParser @see org.apache.log4j.EnhancedPatternLayout @author Anders Kristensen */ public class EnhancedMyPatternLayout extends EnhancedPatternLayout { public EnhancedMyPatternLayout() { this(DEFAULT_CONVERSION_PATTERN); } public EnhancedMyPatternLayout(String pattern) { super(pattern); } public PatternParser createPatternParser(String pattern) { return new MyPatternParser( pattern == null ? DEFAULT_CONVERSION_PATTERN : pattern); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/Last.java0000644000175000017500000000223611751454673023453 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; public class Last extends TestCase { public Last(String name) { super(name); } public void test1() { } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new Last("test1")); return suite; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/MyPatternLayout.java0000644000175000017500000000373511751454673025676 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.helpers.PatternParser; /** Example showing how to extend PatternLayout to recognize additional conversion characters.

In this case MyPatternLayout recognizes %# conversion pattern. It outputs the value of an internal counter which is also incremented at each call.

See source code for more details. @see MyPatternParser @see org.apache.log4j.PatternLayout @author Anders Kristensen */ public class MyPatternLayout extends PatternLayout { public MyPatternLayout() { this(DEFAULT_CONVERSION_PATTERN); } public MyPatternLayout(String pattern) { super(pattern); } public PatternParser createPatternParser(String pattern) { return new MyPatternParser( pattern == null ? DEFAULT_CONVERSION_PATTERN : pattern); } public static void main(String[] args) { Layout layout = new MyPatternLayout("[counter=%.10#] - %m%n"); Logger logger = Logger.getLogger("some.cat"); logger.addAppender(new ConsoleAppender(layout, ConsoleAppender.SYSTEM_OUT)); logger.debug("Hello, log"); logger.info("Hello again..."); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/TestLogMF.java0000755000175000017500000012157011751454673024362 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; import java.io.CharArrayWriter; import java.text.MessageFormat; import java.text.NumberFormat; import java.util.Date; import java.text.DateFormat; /** * Unit test for LogMF. */ public class TestLogMF extends TestCase { /** * Trace level. */ private static final Level TRACE = getTraceLevel(); /** * Gets Trace level. * Trace level was not defined prior to log4j 1.2.12. * @return trace level */ private static Level getTraceLevel() { try { return (Level) Level.class.getField("TRACE").get(null); } catch(Exception ex) { return new Level(5000, "TRACE", 7); } } /** * Logger. */ private final Logger logger = Logger.getLogger( "org.apache.log4j.formatter.TestLogMF"); /** * Create the test case * * @param testName name of the test case */ public TestLogMF(String testName) { super(testName); } /** * Post test clean up. */ public void tearDown() { LogManager.resetConfiguration(); } /** * Test class name when logging through LogMF. */ public void testClassName() { CharArrayWriter writer = new CharArrayWriter(); PatternLayout layout = new PatternLayout("%C"); WriterAppender appender = new WriterAppender(layout, writer); appender.activateOptions(); Logger.getRootLogger().addAppender(appender); LogMF.debug(logger, null, Math.PI); assertEquals(TestLogMF.class.getName(), writer.toString()); } /** * Test LogMF.trace with null pattern. */ public void testTraceNullPattern() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); LogMF.trace(logger, null, Math.PI); assertNull(capture.getMessage()); } /** * Test LogMF.trace with no-field pattern. */ public void testTraceNoArg() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); LogMF.trace(logger, "Hello, World", Math.PI); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogMF.trace with malformed pattern. */ public void testTraceBadPattern() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); LogMF.trace(logger, "Hello, {.", Math.PI); assertEquals("Hello, {.", capture.getMessage()); } /** * Test LogMF.trace with missing argument. */ public void testTraceMissingArg() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); LogMF.trace(logger, "Hello, {0}World", new Object[0]); assertEquals("Hello, {0}World", capture.getMessage()); } /** * Test LogMF.trace with single field pattern with string argument. */ public void testTraceString() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); LogMF.trace(logger, "Hello, {0}", "World"); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogMF.trace with single field pattern with null argument. */ public void testTraceNull() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); LogMF.trace(logger, "Hello, {0}", (Object) null); assertEquals("Hello, null", capture.getMessage()); } /** * Test LogMF.trace with single field pattern with int argument. */ public void testTraceInt() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); int val = 42; LogMF.trace(logger, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.trace with single field pattern with byte argument. */ public void testTraceByte() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); byte val = 42; LogMF.trace(logger, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.trace with single field pattern with short argument. */ public void testTraceShort() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); short val = 42; LogMF.trace(logger, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.trace with single field pattern with long argument. */ public void testTraceLong() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); long val = 42; LogMF.trace(logger, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.trace with single field pattern with char argument. */ public void testTraceChar() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); char val = 'C'; LogMF.trace(logger, "Iteration {0}", val); assertEquals("Iteration C", capture.getMessage()); } /** * Test LogMF.trace with single field pattern with boolean argument. */ public void testTraceBoolean() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); boolean val = true; LogMF.trace(logger, "Iteration {0}", val); assertEquals("Iteration true", capture.getMessage()); } /** * Test LogMF.trace with single field pattern with float argument. */ public void testTraceFloat() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); float val = 3.14f; NumberFormat format = NumberFormat.getInstance(); LogMF.trace(logger, "Iteration {0}", val); assertEquals("Iteration "+ format.format(val), capture.getMessage()); } /** * Test LogMF.trace with single field pattern with double argument. */ public void testTraceDouble() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); double val = 3.14; NumberFormat format = NumberFormat.getInstance(); LogMF.trace(logger, "Iteration {0}", val); assertEquals("Iteration "+ format.format(val), capture.getMessage()); } /** * Test LogMF.trace with two arguments. */ public void testTraceTwoArg() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); LogMF.trace(logger, "{1}, {0}.", "World", "Hello"); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.trace with three arguments. */ public void testTraceThreeArg() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); LogMF.trace(logger, "{1}{2} {0}.", "World", "Hello", ","); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.trace with four arguments. */ public void testTraceFourArg() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); LogMF.trace(logger, "{1}{2} {0}{3}", "World", "Hello", ",", "."); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.trace with Object[] argument. */ public void testTraceArrayArg() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); Object[] args = new Object[] { "World", "Hello", ",", "." }; LogMF.trace(logger, "{1}{2} {0}{3}", args); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.trace with null Object[] argument. */ public void testTraceNullArrayArg() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); Object[] args = null; LogMF.trace(logger, "{1}{2} {0}{3}", args); assertEquals("{1}{2} {0}{3}", capture.getMessage()); } /** * Test LogMF.debug with null pattern. */ public void testDebugNullPattern() { LogCapture capture = new LogCapture(Level.DEBUG); LogMF.debug(logger, null, Math.PI); assertEquals(null, capture.getMessage()); } /** * Test LogMF.debug with no-field pattern. */ public void testDebugNoArg() { LogCapture capture = new LogCapture(Level.DEBUG); LogMF.debug(logger, "Hello, World", Math.PI); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogMF.debug with malformed pattern. */ public void testDebugBadPattern() { LogCapture capture = new LogCapture(Level.DEBUG); LogMF.debug(logger, "Hello, {.", Math.PI); assertEquals("Hello, {.", capture.getMessage()); } /** * Test LogMF.debug with missing argument. */ public void testDebugMissingArg() { LogCapture capture = new LogCapture(Level.DEBUG); LogMF.debug(logger, "Hello, {0}World", new Object[0]); assertEquals("Hello, {0}World", capture.getMessage()); } /** * Test LogMF.debug with single field pattern with string argument. */ public void testDebugString() { LogCapture capture = new LogCapture(Level.DEBUG); LogMF.debug(logger, "Hello, {0}", "World"); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogMF.debug with single field pattern with null argument. */ public void testDebugNull() { LogCapture capture = new LogCapture(Level.DEBUG); LogMF.debug(logger, "Hello, {0}", (Object) null); assertEquals("Hello, null", capture.getMessage()); } /** * Test LogMF.debug with single field pattern with int argument. */ public void testDebugInt() { LogCapture capture = new LogCapture(Level.DEBUG); int val = 42; LogMF.debug(logger, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.debug with single field pattern with byte argument. */ public void testDebugByte() { LogCapture capture = new LogCapture(Level.DEBUG); byte val = 42; LogMF.debug(logger, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.debug with single field pattern with short argument. */ public void testDebugShort() { LogCapture capture = new LogCapture(Level.DEBUG); short val = 42; LogMF.debug(logger, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.debug with single field pattern with long argument. */ public void testDebugLong() { LogCapture capture = new LogCapture(Level.DEBUG); long val = 42; LogMF.debug(logger, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.debug with single field pattern with char argument. */ public void testDebugChar() { LogCapture capture = new LogCapture(Level.DEBUG); char val = 'C'; LogMF.debug(logger, "Iteration {0}", val); assertEquals("Iteration C", capture.getMessage()); } /** * Test LogMF.debug with single field pattern with boolean argument. */ public void testDebugBoolean() { LogCapture capture = new LogCapture(Level.DEBUG); boolean val = true; LogMF.debug(logger, "Iteration {0}", val); assertEquals("Iteration true", capture.getMessage()); } /** * Test LogMF.debug with single field pattern with float argument. */ public void testDebugFloat() { LogCapture capture = new LogCapture(Level.DEBUG); LogMF.debug(logger, "Iteration {0}", (float) Math.PI); String expected = MessageFormat.format("Iteration {0}", new Object[] { new Float(Math.PI) }); assertEquals(expected, capture.getMessage()); } /** * Test LogMF.debug with single field pattern with double argument. */ public void testDebugDouble() { LogCapture capture = new LogCapture(Level.DEBUG); LogMF.debug(logger, "Iteration {0}", Math.PI); String expected = MessageFormat.format("Iteration {0}", new Object[] { new Double(Math.PI) }); assertEquals(expected, capture.getMessage()); } /** * Test LogMF.debug with two arguments. */ public void testDebugTwoArg() { LogCapture capture = new LogCapture(Level.DEBUG); LogMF.debug(logger, "{1}, {0}.", "World", "Hello"); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.debug with three arguments. */ public void testDebugThreeArg() { LogCapture capture = new LogCapture(Level.DEBUG); LogMF.debug(logger, "{1}{2} {0}.", "World", "Hello", ","); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.debug with four arguments. */ public void testDebugFourArg() { LogCapture capture = new LogCapture(Level.DEBUG); LogMF.debug(logger, "{1}{2} {0}{3}", "World", "Hello", ",", "."); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.debug with Object[] argument. */ public void testDebugArrayArg() { LogCapture capture = new LogCapture(Level.DEBUG); Object[] args = new Object[] { "World", "Hello", ",", "." }; LogMF.debug(logger, "{1}{2} {0}{3}", args); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.debug with single field pattern with double argument. */ public void testDebugDate() { LogCapture capture = new LogCapture(Level.DEBUG); Date epoch = new Date(0); LogMF.debug(logger, "Iteration {0}", epoch); String expected = MessageFormat.format("Iteration {0}", new Object[] { epoch }); String expected2 = "Iteration " + DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.SHORT).format(epoch); String actual = capture.getMessage(); // // gcj has been observed to output 12/31/69 6:00:00 PM // instead of the expected 12/31/69 6:00 PM if (System.getProperty("java.vendor").indexOf("Free") == -1) { assertEquals(expected, actual); } assertEquals(expected2, actual); } /** * Test LogMF.debug with null Object[] argument. */ public void testDebugNullArrayArg() { LogCapture capture = new LogCapture(Level.DEBUG); Object[] args = null; LogMF.debug(logger, "{1}{2} {0}{3}", args); assertEquals("{1}{2} {0}{3}", capture.getMessage()); } public void testDebugPercent() { LogCapture capture = new LogCapture(Level.DEBUG); LogMF.debug(logger, "{0, number, percent}", Math.PI); String expected = java.text.MessageFormat.format("{0, number, percent}", new Object[] { new Double(Math.PI) }); assertEquals(expected, capture.getMessage()); } public void testDebugFullPrecisionAndPercent() { LogCapture capture = new LogCapture(Level.DEBUG); LogMF.debug(logger, "{0}{0, number, percent}", Math.PI); String expected = java.text.MessageFormat.format("{0}{0, number, percent}", new Object[] { new Double(Math.PI) }); assertEquals(expected, capture.getMessage()); } public void testDebugQuoted() { LogCapture capture = new LogCapture(Level.DEBUG); LogMF.debug(logger, "'{0}'", "World"); assertEquals("{0}", capture.getMessage()); } /** * Test LogMF.info with null pattern. */ public void testInfoNullPattern() { LogCapture capture = new LogCapture(Level.INFO); LogMF.info(logger, null, Math.PI); assertNull(capture.getMessage()); } /** * Test LogMF.info with no-field pattern. */ public void testInfoNoArg() { LogCapture capture = new LogCapture(Level.INFO); LogMF.info(logger, "Hello, World", Math.PI); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogMF.info with malformed pattern. */ public void testInfoBadPattern() { LogCapture capture = new LogCapture(Level.INFO); LogMF.info(logger, "Hello, {.", Math.PI); assertEquals("Hello, {.", capture.getMessage()); } /** * Test LogMF.info with missing argument. */ public void testInfoMissingArg() { LogCapture capture = new LogCapture(Level.INFO); LogMF.info(logger, "Hello, {0}World", new Object[0]); assertEquals("Hello, {0}World", capture.getMessage()); } /** * Test LogMF.info with single field pattern with string argument. */ public void testInfoString() { LogCapture capture = new LogCapture(Level.INFO); LogMF.info(logger, "Hello, {0}", "World"); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogMF.info with single field pattern with null argument. */ public void testInfoNull() { LogCapture capture = new LogCapture(Level.INFO); LogMF.info(logger, "Hello, {0}", (Object) null); assertEquals("Hello, null", capture.getMessage()); } /** * Test LogMF.info with single field pattern with int argument. */ public void testInfoInt() { LogCapture capture = new LogCapture(Level.INFO); int val = 42; LogMF.info(logger, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.info with single field pattern with byte argument. */ public void testInfoByte() { LogCapture capture = new LogCapture(Level.INFO); byte val = 42; LogMF.info(logger, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.info with single field pattern with short argument. */ public void testInfoShort() { LogCapture capture = new LogCapture(Level.INFO); short val = 42; LogMF.info(logger, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.info with single field pattern with long argument. */ public void testInfoLong() { LogCapture capture = new LogCapture(Level.INFO); long val = 42; LogMF.info(logger, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.info with single field pattern with char argument. */ public void testInfoChar() { LogCapture capture = new LogCapture(Level.INFO); char val = 'C'; LogMF.info(logger, "Iteration {0}", val); assertEquals("Iteration C", capture.getMessage()); } /** * Test LogMF.info with single field pattern with boolean argument. */ public void testInfoBoolean() { LogCapture capture = new LogCapture(Level.INFO); boolean val = true; LogMF.info(logger, "Iteration {0}", val); assertEquals("Iteration true", capture.getMessage()); } /** * Test LogMF.info with single field pattern with float argument. */ public void testInfoFloat() { LogCapture capture = new LogCapture(Level.INFO); LogMF.info(logger, "Iteration {0}", (float) Math.PI); String expected = MessageFormat.format("Iteration {0}", new Object[] { new Float(Math.PI) }); assertEquals(expected, capture.getMessage()); } /** * Test LogMF.info with single field pattern with double argument. */ public void testInfoDouble() { LogCapture capture = new LogCapture(Level.INFO); LogMF.info(logger, "Iteration {0}", Math.PI); String expected = MessageFormat.format("Iteration {0}", new Object[] { new Double(Math.PI) }); assertEquals(expected, capture.getMessage()); } /** * Test LogMF.info with two arguments. */ public void testInfoTwoArg() { LogCapture capture = new LogCapture(Level.INFO); LogMF.info(logger, "{1}, {0}.", "World", "Hello"); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.info with three arguments. */ public void testInfoThreeArg() { LogCapture capture = new LogCapture(Level.INFO); LogMF.info(logger, "{1}{2} {0}.", "World", "Hello", ","); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.info with four arguments. */ public void testInfoFourArg() { LogCapture capture = new LogCapture(Level.INFO); LogMF.info(logger, "{1}{2} {0}{3}", "World", "Hello", ",", "."); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.info with Object[] argument. */ public void testInfoArrayArg() { LogCapture capture = new LogCapture(Level.INFO); Object[] args = new Object[] { "World", "Hello", ",", "." }; LogMF.info(logger, "{1}{2} {0}{3}", args); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.warn with null pattern. */ public void testWarnNullPattern() { LogCapture capture = new LogCapture(Level.WARN); LogMF.warn(logger, null, Math.PI); assertNull(capture.getMessage()); } /** * Test LogMF.warn with no-field pattern. */ public void testWarnNoArg() { LogCapture capture = new LogCapture(Level.WARN); LogMF.warn(logger, "Hello, World", Math.PI); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogMF.warn with malformed pattern. */ public void testWarnBadPattern() { LogCapture capture = new LogCapture(Level.WARN); LogMF.warn(logger, "Hello, {.", Math.PI); assertEquals("Hello, {.", capture.getMessage()); } /** * Test LogMF.warn with missing argument. */ public void testWarnMissingArg() { LogCapture capture = new LogCapture(Level.WARN); LogMF.warn(logger, "Hello, {0}World", new Object[0]); assertEquals("Hello, {0}World", capture.getMessage()); } /** * Test LogMF.warn with single field pattern with string argument. */ public void testWarnString() { LogCapture capture = new LogCapture(Level.WARN); LogMF.warn(logger, "Hello, {0}", "World"); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogMF.warn with single field pattern with null argument. */ public void testWarnNull() { LogCapture capture = new LogCapture(Level.WARN); LogMF.warn(logger, "Hello, {0}", (Object) null); assertEquals("Hello, null", capture.getMessage()); } /** * Test LogMF.warn with single field pattern with int argument. */ public void testWarnInt() { LogCapture capture = new LogCapture(Level.WARN); int val = 42; LogMF.warn(logger, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.warn with single field pattern with byte argument. */ public void testWarnByte() { LogCapture capture = new LogCapture(Level.WARN); byte val = 42; LogMF.warn(logger, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.warn with single field pattern with short argument. */ public void testWarnShort() { LogCapture capture = new LogCapture(Level.WARN); short val = 42; LogMF.warn(logger, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.warn with single field pattern with long argument. */ public void testWarnLong() { LogCapture capture = new LogCapture(Level.WARN); long val = 42; LogMF.warn(logger, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.warn with single field pattern with char argument. */ public void testWarnChar() { LogCapture capture = new LogCapture(Level.WARN); char val = 'C'; LogMF.warn(logger, "Iteration {0}", val); assertEquals("Iteration C", capture.getMessage()); } /** * Test LogMF.warn with single field pattern with boolean argument. */ public void testWarnBoolean() { LogCapture capture = new LogCapture(Level.WARN); boolean val = true; LogMF.warn(logger, "Iteration {0}", val); assertEquals("Iteration true", capture.getMessage()); } /** * Test LogMF.warn with single field pattern with float argument. */ public void testWarnFloat() { LogCapture capture = new LogCapture(Level.WARN); LogMF.warn(logger, "Iteration {0}", (float) Math.PI); String expected = MessageFormat.format("Iteration {0}", new Object[] { new Float(Math.PI) }); assertEquals(expected, capture.getMessage()); } /** * Test LogMF.debug with single field pattern with double argument. */ public void testWarnDouble() { LogCapture capture = new LogCapture(Level.WARN); LogMF.warn(logger, "Iteration {0}", Math.PI); String expected = MessageFormat.format("Iteration {0}", new Object[] { new Double(Math.PI) }); assertEquals(expected, capture.getMessage()); } /** * Test LogMF.warn with two arguments. */ public void testWarnTwoArg() { LogCapture capture = new LogCapture(Level.WARN); LogMF.warn(logger, "{1}, {0}.", "World", "Hello"); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.warn with three arguments. */ public void testWarnThreeArg() { LogCapture capture = new LogCapture(Level.WARN); LogMF.warn(logger, "{1}{2} {0}.", "World", "Hello", ","); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.debug with four arguments. */ public void testWarnFourArg() { LogCapture capture = new LogCapture(Level.WARN); LogMF.warn(logger, "{1}{2} {0}{3}", "World", "Hello", ",", "."); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.warn with Object[] argument. */ public void testWarnArrayArg() { LogCapture capture = new LogCapture(Level.WARN); Object[] args = new Object[] { "World", "Hello", ",", "." }; LogMF.warn(logger, "{1}{2} {0}{3}", args); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.log with null pattern. */ public void testLogNullPattern() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.log(logger, Level.ERROR, null, Math.PI); assertNull(capture.getMessage()); } /** * Test LogMF.log with no-field pattern. */ public void testLogNoArg() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.log(logger, Level.ERROR, "Hello, World", Math.PI); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogMF.log with malformed pattern. */ public void testLogBadPattern() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.log(logger, Level.ERROR, "Hello, {.", Math.PI); assertEquals("Hello, {.", capture.getMessage()); } /** * Test LogMF.log with missing argument. */ public void testLogMissingArg() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.log(logger, Level.ERROR, "Hello, {0}World", new Object[0]); assertEquals("Hello, {0}World", capture.getMessage()); } /** * Test LogMF.log with single field pattern with string argument. */ public void testLogString() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.log(logger, Level.ERROR, "Hello, {0}", "World"); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogMF.log with single field pattern with null argument. */ public void testLogNull() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.log(logger, Level.ERROR, "Hello, {0}", (Object) null); assertEquals("Hello, null", capture.getMessage()); } /** * Test LogMF.log with single field pattern with int argument. */ public void testLogInt() { LogCapture capture = new LogCapture(Level.ERROR); int val = 42; LogMF.log(logger, Level.ERROR, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.log with single field pattern with byte argument. */ public void testLogByte() { LogCapture capture = new LogCapture(Level.ERROR); byte val = 42; LogMF.log(logger, Level.ERROR, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.log with single field pattern with short argument. */ public void testLogShort() { LogCapture capture = new LogCapture(Level.ERROR); short val = 42; LogMF.log(logger, Level.ERROR, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.log with single field pattern with long argument. */ public void testLogLong() { LogCapture capture = new LogCapture(Level.ERROR); long val = 42; LogMF.log(logger, Level.ERROR, "Iteration {0}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.log with single field pattern with char argument. */ public void testLogChar() { LogCapture capture = new LogCapture(Level.ERROR); char val = 'C'; LogMF.log(logger, Level.ERROR, "Iteration {0}", val); assertEquals("Iteration C", capture.getMessage()); } /** * Test LogMF.log with single field pattern with boolean argument. */ public void testLogBoolean() { LogCapture capture = new LogCapture(Level.ERROR); boolean val = true; LogMF.log(logger, Level.ERROR, "Iteration {0}", val); assertEquals("Iteration true", capture.getMessage()); } /** * Test LogMF.log with single field pattern with float argument. */ public void testLogFloat() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.log(logger, Level.ERROR, "Iteration {0}", (float) Math.PI); String expected = MessageFormat.format("Iteration {0}", new Object[] { new Float(Math.PI) }); assertEquals(expected, capture.getMessage()); } /** * Test LogMF.log with single field pattern with double argument. */ public void testLogDouble() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.log(logger, Level.ERROR, "Iteration {0}", Math.PI); String expected = MessageFormat.format("Iteration {0}", new Object[] { new Double(Math.PI) }); assertEquals(expected, capture.getMessage()); } /** * Test LogMF.log with two arguments. */ public void testLogTwoArg() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.log(logger, Level.ERROR, "{1}, {0}.", "World", "Hello"); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.log with three arguments. */ public void testLogThreeArg() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.log(logger, Level.ERROR, "{1}{2} {0}.", "World", "Hello", ","); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.log with four arguments. */ public void testLogFourArg() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.log(logger, Level.ERROR, "{1}{2} {0}{3}", "World", "Hello", ",", "."); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.log with Object[] argument. */ public void testLogArrayArg() { LogCapture capture = new LogCapture(Level.ERROR); Object[] args = new Object[] { "World", "Hello", ",", "." }; LogMF.log(logger, Level.ERROR, "{1}{2} {0}{3}", args); assertEquals("Hello, World.", capture.getMessage()); } /** * Bundle name for resource bundle tests. */ private static final String BUNDLE_NAME = "org.apache.log4j.TestLogMFPatterns"; /** * Test LogMF.logrb with null bundle name. */ public void testLogrbNullBundle() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.logrb(logger, Level.ERROR, null, "Iteration0", Math.PI); assertEquals("Iteration0", capture.getMessage()); } /** * Test LogMF.logrb with null key. */ public void testLogrbNullKey() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.logrb(logger, Level.ERROR, BUNDLE_NAME, null, Math.PI); assertNull(capture.getMessage()); } /** * Test LogMF.logrb with no-field pattern. */ public void testLogrbNoArg() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Hello1", Math.PI); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogMF.logrb with malformed pattern. */ public void testLogrbBadPattern() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Malformed", Math.PI); assertEquals("Hello, {.", capture.getMessage()); } /** * Test LogMF.logrb with missing argument. */ public void testLogrbMissingArg() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Hello2", new Object[0]); assertEquals("Hello, {0}World", capture.getMessage()); } /** * Test LogMF.logrb with single field pattern with string argument. */ public void testLogrbString() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Hello3", "World"); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogMF.logrb with single field pattern with null argument. */ public void testLogrbNull() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Hello3", (Object) null); assertEquals("Hello, null", capture.getMessage()); } /** * Test LogMF.logrb with single field pattern with int argument. */ public void testLogrbInt() { LogCapture capture = new LogCapture(Level.ERROR); int val = 42; LogMF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Iteration0", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.logrb with single field pattern with byte argument. */ public void testLogrbByte() { LogCapture capture = new LogCapture(Level.ERROR); byte val = 42; LogMF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Iteration0", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.logrb with single field pattern with short argument. */ public void testLogrbShort() { LogCapture capture = new LogCapture(Level.ERROR); short val = 42; LogMF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Iteration0", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.logrb with single field pattern with long argument. */ public void testLogrbLong() { LogCapture capture = new LogCapture(Level.ERROR); long val = 42; LogMF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Iteration0", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogMF.logrb with single field pattern with char argument. */ public void testLogrbChar() { LogCapture capture = new LogCapture(Level.ERROR); char val = 'C'; LogMF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Iteration0", val); assertEquals("Iteration C", capture.getMessage()); } /** * Test LogMF.logrb with single field pattern with boolean argument. */ public void testLogrbBoolean() { LogCapture capture = new LogCapture(Level.ERROR); boolean val = true; LogMF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Iteration0", val); assertEquals("Iteration true", capture.getMessage()); } /** * Test LogMF.logrb with single field pattern with float argument. */ public void testLogrbFloat() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Iteration0", (float) Math.PI); String expected = MessageFormat.format("Iteration {0}", new Object[] { new Float(Math.PI) }); assertEquals(expected, capture.getMessage()); } /** * Test LogMF.logrb with single field pattern with double argument. */ public void testLogrbDouble() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Iteration0", Math.PI); String expected = MessageFormat.format("Iteration {0}", new Object[] { new Double(Math.PI) }); assertEquals(expected, capture.getMessage()); } /** * Test LogMF.logrb with two arguments. */ public void testLogrbTwoArg() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Hello4", "World", "Hello"); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.logrb with three arguments. */ public void testLogrbThreeArg() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Hello5", "World", "Hello", ","); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.logrb with four arguments. */ public void testLogrbFourArg() { LogCapture capture = new LogCapture(Level.ERROR); LogMF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Hello6", "World", "Hello", ",", "."); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.logrb with Object[] argument. */ public void testLogrbArrayArg() { LogCapture capture = new LogCapture(Level.ERROR); Object[] args = new Object[] { "World", "Hello", ",", "." }; LogMF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Hello6", args); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogMF.info with a pattern containing {9} and one argument. */ public void testInfo1ParamBrace9() { LogCapture capture = new LogCapture(Level.INFO); LogMF.info(logger, "Hello, {9}{0}", "World"); assertEquals("Hello, {9}World", capture.getMessage()); } /** * Test LogMF.info with a pattern containing {9} and two arguments. */ public void testInfo2ParamBrace9() { LogCapture capture = new LogCapture(Level.INFO); LogMF.info(logger, "{1}, {9}{0}", "World", "Hello"); assertEquals("Hello, {9}World", capture.getMessage()); } /** * Test LogMF.info with a pattern containing {9} and two arguments. */ public void testInfo10ParamBrace9() { LogCapture capture = new LogCapture(Level.INFO); LogMF.info(logger, "{1}, {9}{0}", new Object[] { "World", "Hello", null, null, null, null, null, null, null, "New " }); assertEquals("Hello, New World", capture.getMessage()); } /** * Test LogMF.info with indexes just outside of 0 to 9. */ public void testInfo1ParamBraceSlashColon() { LogCapture capture = new LogCapture(Level.INFO); String pattern = "Hello, {/}{0}{:}"; LogMF.info(logger, pattern, "World"); assertEquals(pattern, capture.getMessage()); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/EnhancedPatternLayoutTest.java0000644000175000017500000001001011751454673027636 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.spi.LoggingEvent; /** * Test for EnhancedPatternLayout. * */ public class EnhancedPatternLayoutTest extends LayoutTest { /** * Construct new instance of PatternLayoutTest. * * @param testName test name. */ public EnhancedPatternLayoutTest(final String testName) { super(testName, "text/plain", true, null, null); } /** * @{inheritDoc} */ protected Layout createLayout() { return new EnhancedPatternLayout("[%t] %p %c - %m%n"); } /** * Tests format. */ public void testFormat() { Logger logger = Logger.getLogger("org.apache.log4j.LayoutTest"); LoggingEvent event = new LoggingEvent( "org.apache.log4j.Logger", logger, Level.INFO, "Hello, World", null); EnhancedPatternLayout layout = (EnhancedPatternLayout) createLayout(); String result = layout.format(event); StringBuffer buf = new StringBuffer(100); buf.append('['); buf.append(event.getThreadName()); buf.append("] "); buf.append(event.getLevel().toString()); buf.append(' '); buf.append(event.getLoggerName()); buf.append(" - "); buf.append(event.getMessage()); buf.append(System.getProperty("line.separator")); assertEquals(buf.toString(), result); } /** * Tests getPatternFormat(). */ public void testGetPatternFormat() { EnhancedPatternLayout layout = (EnhancedPatternLayout) createLayout(); assertEquals("[%t] %p %c - %m%n", layout.getConversionPattern()); } /** * Tests DEFAULT_CONVERSION_PATTERN constant. */ public void testDefaultConversionPattern() { assertEquals("%m%n", EnhancedPatternLayout.DEFAULT_CONVERSION_PATTERN); } /** * Tests DEFAULT_CONVERSION_PATTERN constant. */ public void testTTCCConversionPattern() { assertEquals( "%r [%t] %p %c %x - %m%n", EnhancedPatternLayout.TTCC_CONVERSION_PATTERN); } /** * Tests buffer downsizing code path. */ public void testFormatResize() { Logger logger = Logger.getLogger("org.apache.log4j.xml.PatternLayoutTest"); NDC.clear(); char[] msg = new char[2000]; for (int i = 0; i < msg.length; i++) { msg[i] = 'A'; } LoggingEvent event1 = new LoggingEvent( "org.apache.log4j.Logger", logger, Level.DEBUG, new String(msg), null); EnhancedPatternLayout layout = (EnhancedPatternLayout) createLayout(); String result = layout.format(event1); LoggingEvent event2 = new LoggingEvent( "org.apache.log4j.Logger", logger, Level.WARN, "Hello, World", null); result = layout.format(event2); assertEquals("[", result.substring(0, 1)); } /** * Class to ensure that protected members are still available. */ public static final class DerivedPatternLayout extends EnhancedPatternLayout { /** * Constructs a new instance of DerivedPatternLayout. */ public DerivedPatternLayout() { } /** * Get BUF_SIZE. * @return return initial buffer size in characters. * @deprecated */ public int getBufSize() { return BUF_SIZE; } /** * Get MAX_CAPACITY. * @return maximum capacity in characters. * @deprecated */ public int getMaxCapacity() { return MAX_CAPACITY; } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/MinimumTestCase.java0000644000175000017500000001526011751454673025620 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; import org.apache.log4j.helpers.AbsoluteTimeDateFormat; import org.apache.log4j.util.*; /** A superficial but general test of log4j. */ public class MinimumTestCase extends TestCase { static String FILTERED = "output/filtered"; static String EXCEPTION1 = "java.lang.Exception: Just testing"; static String EXCEPTION2 = "\\s*at .*\\(.*\\)"; static String EXCEPTION3 = "\\s*at .*\\(Native Method\\)"; static String EXCEPTION4 = "\\s*at .*\\(.*Compiled Code\\)"; static String EXCEPTION5 = "\\s*at .*\\(.*libgcj.*\\)"; //18 fevr. 2002 20:02:41,551 [main] FATAL ERR - Message 0 static String TTCC_PAT = Filter.ABSOLUTE_DATE_AND_TIME_PAT+ " \\[main]\\ (TRACE|DEBUG|INFO|WARN|ERROR|FATAL) .* - Message \\d{1,2}"; static String TTCC2_PAT = Filter.ABSOLUTE_DATE_AND_TIME_PAT+ " \\[main]\\ (TRACE|DEBUG|INFO|WARN|ERROR|FATAL) .* - Messages should bear numbers 0 through 29\\."; //18 fvr. 2002 19:49:53,456 Logger root; Logger logger; public MinimumTestCase(String name) { super(name); } public void setUp() { root = Logger.getRootLogger(); root.removeAllAppenders(); } public void tearDown() { root.getLoggerRepository().resetConfiguration(); } public void simple() throws Exception { Layout layout = new SimpleLayout(); Appender appender = new FileAppender(layout, "output/simple", false); root.addAppender(appender); common(); Transformer.transform( "output/simple", FILTERED, new Filter[] { new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); assertTrue(Compare.compare(FILTERED, "witness/simple")); } public void ttcc() throws Exception { Layout layout = new TTCCLayout(AbsoluteTimeDateFormat.DATE_AND_TIME_DATE_FORMAT); Appender appender = new FileAppender(layout, "output/ttcc", false); root.addAppender(appender); String oldName = Thread.currentThread().getName(); Thread.currentThread().setName("main"); common(); Thread.currentThread().setName(oldName); ControlFilter cf1 = new ControlFilter(new String[]{TTCC_PAT, TTCC2_PAT, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5 }); Transformer.transform( "output/ttcc", FILTERED, new Filter[] { cf1, new LineNumberFilter(), new AbsoluteDateAndTimeFilter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); assertTrue(Compare.compare(FILTERED, "witness/ttcc")); } void common() { int i = 0; // In the lines below, the category names are chosen as an aid in // remembering their level values. In general, the category names // have no bearing to level values. Logger ERR = Logger.getLogger("ERR"); ERR.setLevel(Level.ERROR); Logger INF = Logger.getLogger("INF"); INF.setLevel(Level.INFO); Logger INF_ERR = Logger.getLogger("INF.ERR"); INF_ERR.setLevel(Level.ERROR); Logger DEB = Logger.getLogger("DEB"); DEB.setLevel(Level.DEBUG); Logger TRC = Logger.getLogger("TRC"); TRC.setLevel(Level.TRACE); // Note: categories with undefined level Logger INF_UNDEF = Logger.getLogger("INF.UNDEF"); Logger INF_ERR_UNDEF = Logger.getLogger("INF.ERR.UNDEF"); Logger UNDEF = Logger.getLogger("UNDEF"); // These should all log.---------------------------- ERR.log(Level.FATAL, "Message " + i); i++; //0 ERR.error( "Message " + i); i++; INF.log(Level.FATAL, "Message " + i); i++; // 2 INF.error( "Message " + i); i++; INF.warn ( "Message " + i); i++; INF.info ( "Message " + i); i++; INF_UNDEF.log(Level.FATAL, "Message " + i); i++; //6 INF_UNDEF.error( "Message " + i); i++; INF_UNDEF.warn ( "Message " + i); i++; INF_UNDEF.info ( "Message " + i); i++; INF_ERR.log(Level.FATAL, "Message " + i); i++; // 10 INF_ERR.error( "Message " + i); i++; INF_ERR_UNDEF.log(Level.FATAL, "Message " + i); i++; INF_ERR_UNDEF.error( "Message " + i); i++; DEB.log(Level.FATAL, "Message " + i); i++; //14 DEB.error( "Message " + i); i++; DEB.warn ( "Message " + i); i++; DEB.info ( "Message " + i); i++; DEB.debug( "Message " + i); i++; TRC.log(Level.FATAL, "Message " + i); i++; //19 TRC.error( "Message " + i); i++; TRC.warn ( "Message " + i); i++; TRC.info ( "Message " + i); i++; TRC.debug( "Message " + i); i++; TRC.trace( "Message " + i); i++; // defaultLevel=DEBUG UNDEF.log(Level.FATAL, "Message " + i); i++; // 25 UNDEF.error("Message " + i); i++; UNDEF.warn ("Message " + i); i++; UNDEF.info ("Message " + i); i++; UNDEF.debug("Message " + i, new Exception("Just testing.")); int printCount = i; i++; // ------------------------------------------------- // The following should not log ERR.warn("Message " + i); i++; ERR.info("Message " + i); i++; ERR.debug("Message " + i); i++; INF.debug("Message " + i); i++; INF_UNDEF.debug("Message " + i); i++; INF_ERR.warn("Message " + i); i++; INF_ERR.info("Message " + i); i++; INF_ERR.debug("Message " + i); i++; INF_ERR_UNDEF.warn("Message " + i); i++; INF_ERR_UNDEF.info("Message " + i); i++; INF_ERR_UNDEF.debug("Message " + i); i++; UNDEF.trace("Message " + i, new Exception("Just testing.")); i++; // ------------------------------------------------- INF.info("Messages should bear numbers 0 through "+printCount+"."); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new MinimumTestCase("simple")); suite.addTest(new MinimumTestCase("ttcc")); return suite; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/LoggerTestCase.java0000644000175000017500000003560111751454673025425 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.RootLogger; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.HierarchyEventListener; import java.util.Enumeration; import java.util.Locale; import java.util.ResourceBundle; import java.util.Vector; /** Used for internal unit testing the Logger class. @author Ceki Gülcü */ public class LoggerTestCase extends TestCase { Logger logger; Appender a1; Appender a2; ResourceBundle rbUS; ResourceBundle rbFR; ResourceBundle rbCH; // A short message. static String MSG = "M"; public LoggerTestCase(String name) { super(name); } public void setUp() { rbUS = ResourceBundle.getBundle("L7D", new Locale("en", "US")); assertNotNull(rbUS); rbFR = ResourceBundle.getBundle("L7D", new Locale("fr", "FR")); assertNotNull("Got a null resource bundle.", rbFR); rbCH = ResourceBundle.getBundle("L7D", new Locale("fr", "CH")); assertNotNull("Got a null resource bundle.", rbCH); } public void tearDown() { // Regular users should not use the clear method lightly! //Logger.getDefaultHierarchy().clear(); BasicConfigurator.resetConfiguration(); a1 = null; a2 = null; } /** Add an appender and see if it can be retrieved. */ public void testAppender1() { logger = Logger.getLogger("test"); a1 = new FileAppender(); a1.setName("testAppender1"); logger.addAppender(a1); Enumeration enumeration = logger.getAllAppenders(); Appender aHat = (Appender) enumeration.nextElement(); assertEquals(a1, aHat); } /** Add an appender X, Y, remove X and check if Y is the only remaining appender. */ public void testAppender2() { a1 = new FileAppender(); a1.setName("testAppender2.1"); a2 = new FileAppender(); a2.setName("testAppender2.2"); logger = Logger.getLogger("test"); logger.addAppender(a1); logger.addAppender(a2); logger.removeAppender("testAppender2.1"); Enumeration enumeration = logger.getAllAppenders(); Appender aHat = (Appender) enumeration.nextElement(); assertEquals(a2, aHat); assertTrue(!enumeration.hasMoreElements()); } /** Test if logger a.b inherits its appender from a. */ public void testAdditivity1() { Logger a = Logger.getLogger("a"); Logger ab = Logger.getLogger("a.b"); CountingAppender ca = new CountingAppender(); a.addAppender(ca); assertEquals(ca.counter, 0); ab.debug(MSG); assertEquals(ca.counter, 1); ab.info(MSG); assertEquals(ca.counter, 2); ab.warn(MSG); assertEquals(ca.counter, 3); ab.error(MSG); assertEquals(ca.counter, 4); } /** Test multiple additivity. */ public void testAdditivity2() { Logger a = Logger.getLogger("a"); Logger ab = Logger.getLogger("a.b"); Logger abc = Logger.getLogger("a.b.c"); Logger x = Logger.getLogger("x"); CountingAppender ca1 = new CountingAppender(); CountingAppender ca2 = new CountingAppender(); a.addAppender(ca1); abc.addAppender(ca2); assertEquals(ca1.counter, 0); assertEquals(ca2.counter, 0); ab.debug(MSG); assertEquals(ca1.counter, 1); assertEquals(ca2.counter, 0); abc.debug(MSG); assertEquals(ca1.counter, 2); assertEquals(ca2.counter, 1); x.debug(MSG); assertEquals(ca1.counter, 2); assertEquals(ca2.counter, 1); } /** Test additivity flag. */ public void testAdditivity3() { Logger root = Logger.getRootLogger(); Logger a = Logger.getLogger("a"); Logger ab = Logger.getLogger("a.b"); Logger abc = Logger.getLogger("a.b.c"); CountingAppender caRoot = new CountingAppender(); CountingAppender caA = new CountingAppender(); CountingAppender caABC = new CountingAppender(); root.addAppender(caRoot); a.addAppender(caA); abc.addAppender(caABC); assertEquals(caRoot.counter, 0); assertEquals(caA.counter, 0); assertEquals(caABC.counter, 0); ab.setAdditivity(false); a.debug(MSG); assertEquals(caRoot.counter, 1); assertEquals(caA.counter, 1); assertEquals(caABC.counter, 0); ab.debug(MSG); assertEquals(caRoot.counter, 1); assertEquals(caA.counter, 1); assertEquals(caABC.counter, 0); abc.debug(MSG); assertEquals(caRoot.counter, 1); assertEquals(caA.counter, 1); assertEquals(caABC.counter, 1); } public void testDisable1() { CountingAppender caRoot = new CountingAppender(); Logger root = Logger.getRootLogger(); root.addAppender(caRoot); LoggerRepository h = LogManager.getLoggerRepository(); //h.disableDebug(); h.setThreshold((Level) Level.INFO); assertEquals(caRoot.counter, 0); root.debug(MSG); assertEquals(caRoot.counter, 0); root.info(MSG); assertEquals(caRoot.counter, 1); root.log(Level.WARN, MSG); assertEquals(caRoot.counter, 2); root.warn(MSG); assertEquals(caRoot.counter, 3); //h.disableInfo(); h.setThreshold((Level) Level.WARN); root.debug(MSG); assertEquals(caRoot.counter, 3); root.info(MSG); assertEquals(caRoot.counter, 3); root.log(Level.WARN, MSG); assertEquals(caRoot.counter, 4); root.error(MSG); assertEquals(caRoot.counter, 5); root.log(Level.ERROR, MSG); assertEquals(caRoot.counter, 6); //h.disableAll(); h.setThreshold(Level.OFF); root.debug(MSG); assertEquals(caRoot.counter, 6); root.info(MSG); assertEquals(caRoot.counter, 6); root.log(Level.WARN, MSG); assertEquals(caRoot.counter, 6); root.error(MSG); assertEquals(caRoot.counter, 6); root.log(Level.FATAL, MSG); assertEquals(caRoot.counter, 6); root.log(Level.FATAL, MSG); assertEquals(caRoot.counter, 6); //h.disable(Level.FATAL); h.setThreshold(Level.OFF); root.debug(MSG); assertEquals(caRoot.counter, 6); root.info(MSG); assertEquals(caRoot.counter, 6); root.log(Level.WARN, MSG); assertEquals(caRoot.counter, 6); root.error(MSG); assertEquals(caRoot.counter, 6); root.log(Level.ERROR, MSG); assertEquals(caRoot.counter, 6); root.log(Level.FATAL, MSG); assertEquals(caRoot.counter, 6); } public void testRB1() { Logger root = Logger.getRootLogger(); root.setResourceBundle(rbUS); ResourceBundle t = root.getResourceBundle(); assertSame(t, rbUS); Logger x = Logger.getLogger("x"); Logger x_y = Logger.getLogger("x.y"); Logger x_y_z = Logger.getLogger("x.y.z"); t = x.getResourceBundle(); assertSame(t, rbUS); t = x_y.getResourceBundle(); assertSame(t, rbUS); t = x_y_z.getResourceBundle(); assertSame(t, rbUS); } public void testRB2() { Logger root = Logger.getRootLogger(); root.setResourceBundle(rbUS); ResourceBundle t = root.getResourceBundle(); assertSame(t, rbUS); Logger x = Logger.getLogger("x"); Logger x_y = Logger.getLogger("x.y"); Logger x_y_z = Logger.getLogger("x.y.z"); x_y.setResourceBundle(rbFR); t = x.getResourceBundle(); assertSame(t, rbUS); t = x_y.getResourceBundle(); assertSame(t, rbFR); t = x_y_z.getResourceBundle(); assertSame(t, rbFR); } public void testRB3() { Logger root = Logger.getRootLogger(); root.setResourceBundle(rbUS); ResourceBundle t = root.getResourceBundle(); assertSame(t, rbUS); Logger x = Logger.getLogger("x"); Logger x_y = Logger.getLogger("x.y"); Logger x_y_z = Logger.getLogger("x.y.z"); x_y.setResourceBundle(rbFR); x_y_z.setResourceBundle(rbCH); t = x.getResourceBundle(); assertSame(t, rbUS); t = x_y.getResourceBundle(); assertSame(t, rbFR); t = x_y_z.getResourceBundle(); assertSame(t, rbCH); } public void testExists() { Logger a = Logger.getLogger("a"); Logger a_b = Logger.getLogger("a.b"); Logger a_b_c = Logger.getLogger("a.b.c"); Logger t; t = LogManager.exists("xx"); assertNull(t); t = LogManager.exists("a"); assertSame(a, t); t = LogManager.exists("a.b"); assertSame(a_b, t); t = LogManager.exists("a.b.c"); assertSame(a_b_c, t); } public void testHierarchy1() { Hierarchy h = new Hierarchy(new RootLogger((Level) Level.ERROR)); Logger a0 = h.getLogger("a"); assertEquals("a", a0.getName()); assertNull(a0.getLevel()); assertSame(Level.ERROR, a0.getEffectiveLevel()); Logger a1 = h.getLogger("a"); assertSame(a0, a1); } /** * Tests logger.trace(Object). * @since 1.2.12 */ public void testTrace() { VectorAppender appender = new VectorAppender(); appender.activateOptions(); Logger root = Logger.getRootLogger(); root.addAppender(appender); root.setLevel(Level.INFO); Logger tracer = Logger.getLogger("com.example.Tracer"); tracer.setLevel(Level.TRACE); tracer.trace("Message 1"); root.trace("Discarded Message"); root.trace("Discarded Message"); Vector msgs = appender.getVector(); assertEquals(1, msgs.size()); LoggingEvent event = (LoggingEvent) msgs.elementAt(0); assertEquals(Level.TRACE, event.getLevel()); assertEquals("Message 1", event.getMessage()); } /** * Tests logger.trace(Object, Exception). * @since 1.2.12 */ public void testTraceWithException() { VectorAppender appender = new VectorAppender(); appender.activateOptions(); Logger root = Logger.getRootLogger(); root.addAppender(appender); root.setLevel(Level.INFO); Logger tracer = Logger.getLogger("com.example.Tracer"); tracer.setLevel(Level.TRACE); NullPointerException ex = new NullPointerException(); tracer.trace("Message 1", ex); root.trace("Discarded Message", ex); root.trace("Discarded Message", ex); Vector msgs = appender.getVector(); assertEquals(1, msgs.size()); LoggingEvent event = (LoggingEvent) msgs.elementAt(0); assertEquals(Level.TRACE, event.getLevel()); assertEquals("Message 1", event.getMessage()); } /** * Tests isTraceEnabled. * @since 1.2.12 */ public void testIsTraceEnabled() { VectorAppender appender = new VectorAppender(); appender.activateOptions(); Logger root = Logger.getRootLogger(); root.addAppender(appender); root.setLevel(Level.INFO); Logger tracer = Logger.getLogger("com.example.Tracer"); tracer.setLevel(Level.TRACE); assertTrue(tracer.isTraceEnabled()); assertFalse(root.isTraceEnabled()); } private static final class CountingHierarchyEventListener implements HierarchyEventListener { private int addEventCount; private int removeEventCount; public CountingHierarchyEventListener() { addEventCount = removeEventCount = 0; } public void addAppenderEvent(Category cat, Appender appender) { addEventCount++; } public void removeAppenderEvent(Category cat, Appender appender) { removeEventCount++; } public int getAddEventCount() { return addEventCount; } public int getRemoveEventCount() { return removeEventCount; } } public void testAppenderEvent1() { CountingHierarchyEventListener listener = new CountingHierarchyEventListener(); LogManager.getLoggerRepository().addHierarchyEventListener(listener); CountingAppender appender = new CountingAppender(); Logger root = Logger.getRootLogger(); root.addAppender(appender); assertEquals(1, listener.getAddEventCount()); assertEquals(0, listener.getRemoveEventCount()); root.removeAppender(appender); assertEquals(1, listener.getAddEventCount()); assertEquals(1, listener.getRemoveEventCount()); } public void testAppenderEvent2() { CountingHierarchyEventListener listener = new CountingHierarchyEventListener(); LogManager.getLoggerRepository().addHierarchyEventListener(listener); CountingAppender appender = new CountingAppender(); appender.setName("A1"); Logger root = Logger.getRootLogger(); root.addAppender(appender); assertEquals(1, listener.getAddEventCount()); assertEquals(0, listener.getRemoveEventCount()); root.removeAppender(appender.getName()); assertEquals(1, listener.getAddEventCount()); assertEquals(1, listener.getRemoveEventCount()); } public void testAppenderEvent3() { CountingHierarchyEventListener listener = new CountingHierarchyEventListener(); LogManager.getLoggerRepository().addHierarchyEventListener(listener); CountingAppender appender = new CountingAppender(); Logger root = Logger.getRootLogger(); root.addAppender(appender); assertEquals(1, listener.getAddEventCount()); assertEquals(0, listener.getRemoveEventCount()); root.removeAllAppenders(); assertEquals(1, listener.getAddEventCount()); assertEquals(1, listener.getRemoveEventCount()); } public void testAppenderEvent4() { CountingHierarchyEventListener listener = new CountingHierarchyEventListener(); LogManager.getLoggerRepository().addHierarchyEventListener(listener); CountingAppender appender = new CountingAppender(); Logger root = Logger.getRootLogger(); root.addAppender(appender); assertEquals(1, listener.getAddEventCount()); assertEquals(0, listener.getRemoveEventCount()); LogManager.resetConfiguration(); assertEquals(1, listener.getAddEventCount()); assertEquals(1, listener.getRemoveEventCount()); } static private class CountingAppender extends AppenderSkeleton { int counter; CountingAppender() { counter = 0; } public void close() { } public void append(LoggingEvent event) { counter++; } public boolean requiresLayout() { return true; } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/CategoryTest.java0000644000175000017500000000611511751454673025165 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; import java.lang.reflect.Method; /** * Tests of Category. * * @author Curt Arnold * @since 1.2.14 */ public class CategoryTest extends TestCase { /** * Constructs new instance of test. * @param name test name. */ public CategoryTest(final String name) { super(name); } /** * Tests Category.forcedLog. */ public void testForcedLog() { MockCategory category = new MockCategory("org.example.foo"); category.setAdditivity(false); category.addAppender(new VectorAppender()); category.info("Hello, World"); } /** * Tests that the return type of getChainedPriority is Priority. * @throws Exception thrown if Category.getChainedPriority can not be found. */ public void testGetChainedPriorityReturnType() throws Exception { Method method = Category.class.getMethod("getChainedPriority", (Class[]) null); assertTrue(method.getReturnType() == Priority.class); } /** * Tests l7dlog(Priority, String, Throwable). */ public void testL7dlog() { Logger logger = Logger.getLogger("org.example.foo"); logger.setLevel(Level.ERROR); Priority debug = Level.DEBUG; logger.l7dlog(debug, "Hello, World", null); } /** * Tests l7dlog(Priority, String, Object[], Throwable). */ public void testL7dlog4Param() { Logger logger = Logger.getLogger("org.example.foo"); logger.setLevel(Level.ERROR); Priority debug = Level.DEBUG; logger.l7dlog(debug, "Hello, World", new Object[0], null); } /** * Tests setPriority(Priority). * @deprecated */ public void testSetPriority() { Logger logger = Logger.getLogger("org.example.foo"); Priority debug = Level.DEBUG; logger.setPriority(debug); } /** * Derived category to check method signature of forcedLog. */ private static class MockCategory extends Logger { /** * Create new instance of MockCategory. * @param name category name */ public MockCategory(final String name) { super(name); repository = new Hierarchy(this); } /** * Request an info level message. * @param msg message */ public void info(final String msg) { Priority info = Level.INFO; forcedLog(MockCategory.class.toString(), info, msg, null); } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/MDCOrderFilter.java0000644000175000017500000000371411751454673025317 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.util.Filter; /** * This class switches MDC values into the order * (unreasonably) expected by the witness files. */ public class MDCOrderFilter implements Filter { /** * Unexpected orders of keys. * Note expected values are "va-one-one" and "va-one-two". */ private static final String[] patterns = new String[] { "{key2,va12}{key1,va11}", "{key2,value2}{key1,value1}" }; /** * Replacement values. */ private static final String[] replacements = new String[] { "{key1,va11}{key2,va12}", "{key1,value1}{key2,value2}" }; /** * Switch order of MDC keys when not in expected order. */ public String filter(final String in) { if (in == null) { return null; } for(int i = 0; i < patterns.length; i++) { int ipos = in.indexOf(patterns[i]); if (ipos >= 1) { return in.substring(0, ipos) + replacements[i] + in.substring(ipos + patterns[i].length()); } } return in; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/EnhancedPatternLayoutTestCase.java0000644000175000017500000005021611751454673030446 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; import org.apache.log4j.util.AbsoluteDateAndTimeFilter; import org.apache.log4j.util.AbsoluteTimeFilter; import org.apache.log4j.util.Compare; import org.apache.log4j.util.ControlFilter; import org.apache.log4j.util.Filter; import org.apache.log4j.util.ISO8601Filter; import org.apache.log4j.util.EnhancedJunitTestRunnerFilter; import org.apache.log4j.util.EnhancedLineNumberFilter; import org.apache.log4j.util.RelativeTimeFilter; import org.apache.log4j.util.SunReflectFilter; import org.apache.log4j.util.Transformer; import org.apache.log4j.MDCOrderFilter; import org.apache.log4j.spi.ThrowableInformation; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import java.io.*; public class EnhancedPatternLayoutTestCase extends TestCase { static String TEMP = "output/temp"; static String FILTERED = "output/filtered"; static String EXCEPTION1 = "java.lang.Exception: Just testing"; static String EXCEPTION2 = "\\s*at .*\\(.*\\)"; static String EXCEPTION3 = "\\s*at .*\\((Native Method|Unknown Source)\\)"; static String EXCEPTION4 = "\\s*at .*\\(.*Compiled Code\\)"; static String PAT0 = "\\[main]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - Message \\d{1,2}"; static String PAT1 = Filter.ISO8601_PAT + " " + PAT0; static String PAT2 = Filter.ABSOLUTE_DATE_AND_TIME_PAT + " " + PAT0; static String PAT3 = Filter.ABSOLUTE_TIME_PAT + " " + PAT0; static String PAT4 = Filter.RELATIVE_TIME_PAT + " " + PAT0; static String PAT5 = "\\[main]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* : Message \\d{1,2}"; static String PAT6 = "\\[main]\\ (DEBUG|INFO |WARN |ERROR|FATAL) org.apache.log4j.EnhancedPatternLayoutTestCase.common\\(EnhancedPatternLayoutTestCase.java(:\\d{1,4})?\\): Message \\d{1,2}"; static String PAT11a = "^(DEBUG|INFO |WARN |ERROR|FATAL) \\[main]\\ log4j.EnhancedPatternLayoutTest: Message \\d{1,2}"; static String PAT11b = "^(DEBUG|INFO |WARN |ERROR|FATAL) \\[main]\\ root: Message \\d{1,2}"; static String PAT12 = "^\\[main]\\ (DEBUG|INFO |WARN |ERROR|FATAL) " + "org.apache.log4j.EnhancedPatternLayoutTestCase.common\\(EnhancedPatternLayoutTestCase.java:\\d{3}\\): " + "Message \\d{1,2}"; static String PAT13 = "^\\[main]\\ (DEBUG|INFO |WARN |ERROR|FATAL) " + "apache.log4j.EnhancedPatternLayoutTestCase.common\\(EnhancedPatternLayoutTestCase.java:\\d{3}\\): " + "Message \\d{1,2}"; static String PAT14 = "^(TRACE|DEBUG| INFO| WARN|ERROR|FATAL)\\ \\d{1,2}\\ *- Message \\d{1,2}"; static String PAT_MDC_1 = ""; Logger root; Logger logger; public EnhancedPatternLayoutTestCase(final String name) { super(name); } public void setUp() { root = Logger.getRootLogger(); logger = Logger.getLogger(EnhancedPatternLayoutTest.class); } public void tearDown() { root.getLoggerRepository().resetConfiguration(); } /** * Configures log4j from a properties file resource in class loader path. * @param fileName resource name, only last element is significant. * @throws IOException if resource not found or error reading resource. */ private static void configure(final String fileName) throws IOException { PropertyConfigurator.configure(fileName); } /** * Compares actual and expected files. * @param actual file name for file generated by test * @param expected resource name containing expected output * @return true if files are the same after adjustments * @throws IOException if IO error during comparison. */ private static boolean compare(final String actual, final String expected) throws IOException { return Compare.compare(actual, expected); } public void test1() throws Exception { configure("input/pattern/enhancedPatternLayout1.properties"); common(); Transformer.transform( TEMP, FILTERED, new Filter[] { new EnhancedLineNumberFilter(), new SunReflectFilter(), new EnhancedJunitTestRunnerFilter() }); assertTrue(compare(FILTERED, "witness/pattern/enhancedPatternLayout.1")); } public void test2() throws Exception { configure("input/pattern/enhancedPatternLayout2.properties"); common(); ControlFilter cf1 = new ControlFilter( new String[] { PAT1, EXCEPTION1, EXCEPTION2, EXCEPTION3 }); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new EnhancedLineNumberFilter(), new ISO8601Filter(), new SunReflectFilter(), new EnhancedJunitTestRunnerFilter() }); assertTrue(compare(FILTERED, "witness/pattern/enhancedPatternLayout.2")); } public void test3() throws Exception { configure("input/pattern/enhancedPatternLayout3.properties"); common(); ControlFilter cf1 = new ControlFilter( new String[] { PAT1, EXCEPTION1, EXCEPTION2, EXCEPTION3 }); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new EnhancedLineNumberFilter(), new ISO8601Filter(), new SunReflectFilter(), new EnhancedJunitTestRunnerFilter() }); assertTrue(compare(FILTERED, "witness/pattern/enhancedPatternLayout.3")); } // Output format: // 06 avr. 2002 18:30:58,937 [main] DEBUG atternLayoutTest - Message 0 public void test4() throws Exception { configure("input/pattern/enhancedPatternLayout4.properties"); common(); ControlFilter cf1 = new ControlFilter( new String[] { PAT2, EXCEPTION1, EXCEPTION2, EXCEPTION3 }); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new EnhancedLineNumberFilter(), new AbsoluteDateAndTimeFilter(), new SunReflectFilter(), new EnhancedJunitTestRunnerFilter() }); assertTrue(compare(FILTERED, "witness/pattern/enhancedPatternLayout.4")); } public void test5() throws Exception { configure("input/pattern/enhancedPatternLayout5.properties"); common(); ControlFilter cf1 = new ControlFilter( new String[] { PAT2, EXCEPTION1, EXCEPTION2, EXCEPTION3 }); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new EnhancedLineNumberFilter(), new AbsoluteDateAndTimeFilter(), new SunReflectFilter(), new EnhancedJunitTestRunnerFilter() }); assertTrue(compare(FILTERED, "witness/pattern/enhancedPatternLayout.5")); } // 18:54:19,201 [main] DEBUG atternLayoutTest - Message 0 public void test6() throws Exception { configure("input/pattern/enhancedPatternLayout6.properties"); common(); ControlFilter cf1 = new ControlFilter( new String[] { PAT3, EXCEPTION1, EXCEPTION2, EXCEPTION3 }); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new EnhancedLineNumberFilter(), new AbsoluteTimeFilter(), new SunReflectFilter(), new EnhancedJunitTestRunnerFilter() }); assertTrue(compare(FILTERED, "witness/pattern/enhancedPatternLayout.6")); } public void test7() throws Exception { configure("input/pattern/enhancedPatternLayout7.properties"); common(); ControlFilter cf1 = new ControlFilter( new String[] { PAT3, EXCEPTION1, EXCEPTION2, EXCEPTION3 }); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new EnhancedLineNumberFilter(), new AbsoluteTimeFilter(), new SunReflectFilter(), new EnhancedJunitTestRunnerFilter() }); assertTrue(compare(FILTERED, "witness/pattern/enhancedPatternLayout.7")); } public void test8() throws Exception { configure("input/pattern/enhancedPatternLayout8.properties"); common(); ControlFilter cf1 = new ControlFilter( new String[] { PAT4, EXCEPTION1, EXCEPTION2, EXCEPTION3 }); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new EnhancedLineNumberFilter(), new RelativeTimeFilter(), new SunReflectFilter(), new EnhancedJunitTestRunnerFilter() }); assertTrue(compare(FILTERED, "witness/pattern/enhancedPatternLayout.8")); } public void test9() throws Exception { configure("input/pattern/enhancedPatternLayout9.properties"); common(); ControlFilter cf1 = new ControlFilter( new String[] { PAT5, EXCEPTION1, EXCEPTION2, EXCEPTION3 }); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new EnhancedLineNumberFilter(), new SunReflectFilter(), new EnhancedJunitTestRunnerFilter() }); assertTrue(compare(FILTERED, "witness/pattern/enhancedPatternLayout.9")); } public void test10() throws Exception { configure("input/pattern/enhancedPatternLayout10.properties"); common(); ControlFilter cf1 = new ControlFilter( new String[] { PAT6, EXCEPTION1, EXCEPTION2, EXCEPTION3 }); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new EnhancedLineNumberFilter(), new SunReflectFilter(), new EnhancedJunitTestRunnerFilter() }); assertTrue(compare(FILTERED, "witness/pattern/enhancedPatternLayout.10")); } public void test11() throws Exception { configure("input/pattern/enhancedPatternLayout11.properties"); common(); ControlFilter cf1 = new ControlFilter( new String[] { PAT11a, PAT11b, EXCEPTION1, EXCEPTION2, EXCEPTION3 }); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new EnhancedLineNumberFilter(), new SunReflectFilter(), new EnhancedJunitTestRunnerFilter() }); assertTrue(compare(FILTERED, "witness/pattern/enhancedPatternLayout.11")); } public void test12() throws Exception { configure("input/pattern/enhancedPatternLayout12.properties"); common(); ControlFilter cf1 = new ControlFilter( new String[] { PAT12, EXCEPTION1, EXCEPTION2, EXCEPTION3 }); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new EnhancedLineNumberFilter(), new SunReflectFilter(), new EnhancedJunitTestRunnerFilter() }); assertTrue(compare(FILTERED, "witness/pattern/enhancedPatternLayout.12")); } public void test13() throws Exception { configure("input/pattern/enhancedPatternLayout13.properties"); common(); ControlFilter cf1 = new ControlFilter( new String[] { PAT13, EXCEPTION1, EXCEPTION2, EXCEPTION3 }); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new EnhancedLineNumberFilter(), new SunReflectFilter(), new EnhancedJunitTestRunnerFilter() }); assertTrue(compare(FILTERED, "witness/pattern/enhancedPatternLayout.13")); } /** * Test of class abbreviation. * * @throws Exception */ public void test14() throws Exception { configure("input/pattern/enhancedPatternLayout14.properties"); common(); Transformer.transform( TEMP, FILTERED, new Filter[] { new EnhancedLineNumberFilter(), new SunReflectFilter(), new EnhancedJunitTestRunnerFilter() }); assertTrue(compare(FILTERED, "witness/pattern/enhancedPatternLayout.14")); } private static void clearMDC() throws Exception { java.util.Hashtable context = MDC.getContext(); if (context != null) { context.clear(); } } public void testMDC1() throws Exception { configure("input/pattern/enhancedPatternLayout.mdc.1.properties"); clearMDC(); MDC.put("key1", "va11"); MDC.put("key2", "va12"); logger.debug("Hello World"); MDC.remove("key1"); MDC.remove("key2"); Transformer.transform( TEMP, FILTERED, new Filter[] { new EnhancedLineNumberFilter(), new SunReflectFilter(), new EnhancedJunitTestRunnerFilter(), new MDCOrderFilter() }); assertTrue(compare(FILTERED, "witness/pattern/enhancedPatternLayout.mdc.1")); } /** * Tests log4j 1.2 style extension of EnhancedPatternLayout. * Was test14 in log4j 1.2. * @throws Exception */ public void test15() throws Exception { configure("input/pattern/enhancedPatternLayout15.properties"); common(); ControlFilter cf1 = new ControlFilter(new String[]{PAT14, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new EnhancedLineNumberFilter(), new SunReflectFilter(), new EnhancedJunitTestRunnerFilter() }); assertTrue(compare(FILTERED, "witness/pattern/enhancedPatternLayout.15")); } /** * Tests explicit UTC time zone in pattern. * @throws Exception */ public void test16() throws Exception { final long start = new Date().getTime(); configure("input/pattern/enhancedPatternLayout16.properties"); common(); final long end = new Date().getTime(); FileReader reader = new FileReader("output/patternLayout16.log"); char chars[] = new char[50]; reader.read(chars, 0, chars.length); reader.close(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); format.setTimeZone(TimeZone.getTimeZone("GMT+0")); String utcStr = new String(chars, 0, 19); Date utcDate = format.parse(utcStr, new ParsePosition(0)); assertTrue(utcDate.getTime() >= start - 1000 && utcDate.getTime() < end + 1000); String cstStr = new String(chars, 21, 19); format.setTimeZone(TimeZone.getTimeZone("GMT-6")); Date cstDate = format.parse(cstStr, new ParsePosition(0)); assertFalse(cstStr.equals(utcStr)); assertTrue(cstDate.getTime() >= start - 1000 && cstDate.getTime() < end + 1000); } void common() { int i = -1; logger.debug("Message " + ++i); root.debug("Message " + i); logger.info("Message " + ++i); root.info("Message " + i); logger.warn("Message " + ++i); root.warn("Message " + i); logger.error("Message " + ++i); root.error("Message " + i); logger.log(Level.FATAL, "Message " + ++i); root.log(Level.FATAL, "Message " + i); Exception e = new Exception("Just testing"); logger.debug("Message " + ++i, e); logger.info("Message " + ++i, e); logger.warn("Message " + ++i, e); logger.error("Message " + ++i, e); logger.log(Level.FATAL, "Message " + ++i, e); } /** Test case for MDC conversion pattern. */ public void testMDC2() throws Exception { String OUTPUT_FILE = "output/patternLayout.mdc.2"; String WITNESS_FILE = "witness/pattern/enhancedPatternLayout.mdc.2"; String mdcMsgPattern1 = "%m : %X%n"; String mdcMsgPattern2 = "%m : %X{key1}%n"; String mdcMsgPattern3 = "%m : %X{key2}%n"; String mdcMsgPattern4 = "%m : %X{key3}%n"; String mdcMsgPattern5 = "%m : %X{key1},%X{key2},%X{key3}%n"; // set up appender EnhancedPatternLayout layout = new EnhancedPatternLayout("%m%n"); Appender appender = new FileAppender(layout, OUTPUT_FILE, false); // set appender on root and set level to debug root.addAppender(appender); root.setLevel(Level.DEBUG); clearMDC(); // output starting message root.debug("starting mdc pattern test"); layout.setConversionPattern(mdcMsgPattern1); layout.activateOptions(); root.debug("empty mdc, no key specified in pattern"); layout.setConversionPattern(mdcMsgPattern2); layout.activateOptions(); root.debug("empty mdc, key1 in pattern"); layout.setConversionPattern(mdcMsgPattern3); layout.activateOptions(); root.debug("empty mdc, key2 in pattern"); layout.setConversionPattern(mdcMsgPattern4); layout.activateOptions(); root.debug("empty mdc, key3 in pattern"); layout.setConversionPattern(mdcMsgPattern5); layout.activateOptions(); root.debug("empty mdc, key1, key2, and key3 in pattern"); MDC.put("key1", "value1"); MDC.put("key2", "value2"); layout.setConversionPattern(mdcMsgPattern1); layout.activateOptions(); root.debug("filled mdc, no key specified in pattern"); layout.setConversionPattern(mdcMsgPattern2); layout.activateOptions(); root.debug("filled mdc, key1 in pattern"); layout.setConversionPattern(mdcMsgPattern3); layout.activateOptions(); root.debug("filled mdc, key2 in pattern"); layout.setConversionPattern(mdcMsgPattern4); layout.activateOptions(); root.debug("filled mdc, key3 in pattern"); layout.setConversionPattern(mdcMsgPattern5); layout.activateOptions(); root.debug("filled mdc, key1, key2, and key3 in pattern"); MDC.remove("key1"); MDC.remove("key2"); layout.setConversionPattern("%m%n"); layout.activateOptions(); root.debug("finished mdc pattern test"); Transformer.transform( OUTPUT_FILE, FILTERED, new Filter[] { new EnhancedLineNumberFilter(), new SunReflectFilter(), new EnhancedJunitTestRunnerFilter(), new MDCOrderFilter() }); assertTrue(compare(FILTERED, WITNESS_FILE)); } /** Test case for throwable conversion pattern. */ public void testThrowable() throws Exception { String OUTPUT_FILE = "output/patternLayout.throwable"; String WITNESS_FILE = "witness/pattern/enhancedPatternLayout.throwable"; // set up appender EnhancedPatternLayout layout = new EnhancedPatternLayout("%m%n"); Appender appender = new FileAppender(layout, OUTPUT_FILE, false); // set appender on root and set level to debug root.addAppender(appender); root.setLevel(Level.DEBUG); // output starting message root.debug("starting throwable pattern test"); Exception ex = new Exception("Test Exception"); root.debug("plain pattern, no exception"); root.debug("plain pattern, with exception", ex); layout.setConversionPattern("%m%n%throwable"); layout.activateOptions(); root.debug("%throwable, no exception"); root.debug("%throwable, with exception", ex); layout.setConversionPattern("%m%n%throwable{short}"); layout.activateOptions(); root.debug("%throwable{short}, no exception"); root.debug("%throwable{short}, with exception", ex); layout.setConversionPattern("%m%n%throwable{none}"); layout.activateOptions(); root.debug("%throwable{none}, no exception"); root.debug("%throwable{none}, with exception", ex); layout.setConversionPattern("%m%n%throwable{0}"); layout.activateOptions(); root.debug("%throwable{0}, no exception"); root.debug("%throwable{0}, with exception", ex); layout.setConversionPattern("%m%n%throwable{1}"); layout.activateOptions(); root.debug("%throwable{1}, no exception"); root.debug("%throwable{1}, with exception", ex); layout.setConversionPattern("%m%n%throwable{100}"); layout.activateOptions(); root.debug("%throwable{100}, no exception"); root.debug("%throwable{100}, with exception", ex); // // manufacture a pattern to get just the first two lines // String[] trace = new ThrowableInformation(ex).getThrowableStrRep(); layout.setConversionPattern("%m%n%throwable{" + (2 - trace.length) + "}"); layout.activateOptions(); root.debug("%throwable{-n}, no exception"); root.debug("%throwable{-n}, with exception", ex); Transformer.transform( OUTPUT_FILE, FILTERED, new Filter[] { new EnhancedLineNumberFilter(), new SunReflectFilter(), new EnhancedJunitTestRunnerFilter(), new MDCOrderFilter() }); assertTrue(compare(FILTERED, WITNESS_FILE)); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/LogManagerTest.java0000644000175000017500000000436311751454673025427 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; /** * Tests for LogManager * * @author Curt Arnold **/ public class LogManagerTest extends TestCase { /** * Create new instance of LogManagerTest. * @param testName test name */ public LogManagerTest(final String testName) { super(testName); } /** * Check value of DEFAULT_CONFIGURATION_FILE. * @deprecated since constant is deprecated */ public void testDefaultConfigurationFile() { assertEquals("log4j.properties", LogManager.DEFAULT_CONFIGURATION_FILE); } /** * Check value of DEFAULT_XML_CONFIGURATION_FILE. */ public void testDefaultXmlConfigurationFile() { assertEquals("log4j.xml", LogManager.DEFAULT_XML_CONFIGURATION_FILE); } /** * Check value of DEFAULT_CONFIGURATION_KEY. * @deprecated since constant is deprecated */ public void testDefaultConfigurationKey() { assertEquals("log4j.configuration", LogManager.DEFAULT_CONFIGURATION_KEY); } /** * Check value of CONFIGURATOR_CLASS_KEY. * @deprecated since constant is deprecated */ public void testConfiguratorClassKey() { assertEquals("log4j.configuratorClass", LogManager.CONFIGURATOR_CLASS_KEY); } /** * Check value of DEFAULT_INIT_OVERRIDE_KEY. * @deprecated since constant is deprecated */ public void testDefaultInitOverrideKey() { assertEquals("log4j.defaultInitOverride", LogManager.DEFAULT_INIT_OVERRIDE_KEY); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/spi/0000755000175000017500000000000012126647422022466 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/spi/LocationInfoTest.java0000644000175000017500000000562111751454671026566 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; import junit.framework.TestCase; /** * Tests for LocationInfo. */ public class LocationInfoTest extends TestCase { /** * Tests four parameter constructor. */ public void testFourParamConstructor() { final String className = LocationInfoTest.class.getName(); final String methodName = "testFourParamConstructor"; final String fileName = "LocationInfoTest.java"; final String lineNumber = "41"; LocationInfo li = new LocationInfo(fileName, className, methodName, lineNumber); assertEquals(className, li.getClassName()); assertEquals(methodName, li.getMethodName()); assertEquals(fileName, li.getFileName()); assertEquals(lineNumber, li.getLineNumber()); assertEquals(className + "." + methodName + "(" + fileName + ":" + lineNumber + ")", li.fullInfo); } /** * Class with name that is a substring of its caller. */ private static class NameSubstring { /** * Construct a LocationInfo. Location should be immediate caller of this method. * @return location info. */ public static LocationInfo getInfo() { return new LocationInfo(new Throwable(), NameSubstring.class.getName()); } } /** * Class whose name is contains the name of the class that obtains the LocationInfo. */ private static class NameSubstringCaller { /** * Construct a locationInfo. Location should be this location. * @return location info. */ public static LocationInfo getInfo() { return NameSubstring.getInfo(); } } /** * Tests creation of location info when the logger class name * is a substring of one of the other classes in the stack trace. * See bug 44888. */ public void testLocationInfo() { LocationInfo li = NameSubstringCaller.getInfo(); assertEquals(NameSubstringCaller.class.getName(), li.getClassName()); assertEquals("getInfo", li.getMethodName()); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/spi/LoggingEventTest.java0000644000175000017500000002024211751454671026566 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.MDC; import org.apache.log4j.NDC; import org.apache.log4j.util.SerializationTestHelper; import org.apache.log4j.Priority; import org.apache.log4j.Category; /** * Tests LoggingEvent. * * @author Curt Arnold */ public class LoggingEventTest extends TestCase { /** * Create LoggingEventTest. * * @param name test name. */ public LoggingEventTest(final String name) { super(name); } /** * Serialize a simple logging event and check it against * a witness. * @throws Exception if exception during test. */ public void testSerializationSimple() throws Exception { Logger root = Logger.getRootLogger(); LoggingEvent event = new LoggingEvent( root.getClass().getName(), root, Level.INFO, "Hello, world.", null); // event.prepareForDeferredProcessing(); int[] skip = new int[] { 352, 353, 354, 355, 356 }; SerializationTestHelper.assertSerializationEquals( "witness/serialization/simple.bin", event, skip, 237); } /** * Serialize a logging event with an exception and check it against * a witness. * @throws Exception if exception during test. * */ public void testSerializationWithException() throws Exception { Logger root = Logger.getRootLogger(); Exception ex = new Exception("Don't panic"); LoggingEvent event = new LoggingEvent( root.getClass().getName(), root, Level.INFO, "Hello, world.", ex); // event.prepareForDeferredProcessing(); int[] skip = new int[] { 352, 353, 354, 355, 356 }; SerializationTestHelper.assertSerializationEquals( "witness/serialization/exception.bin", event, skip, 237); } /** * Serialize a logging event with an exception and check it against * a witness. * @throws Exception if exception during test. * */ public void testSerializationWithLocation() throws Exception { Logger root = Logger.getRootLogger(); LoggingEvent event = new LoggingEvent( root.getClass().getName(), root, Level.INFO, "Hello, world.", null); event.getLocationInformation(); // event.prepareForDeferredProcessing(); int[] skip = new int[] { 352, 353, 354, 355, 356 }; SerializationTestHelper.assertSerializationEquals( "witness/serialization/location.bin", event, skip, 237); } /** * Serialize a logging event with ndc. * @throws Exception if exception during test. * */ public void testSerializationNDC() throws Exception { Logger root = Logger.getRootLogger(); NDC.push("ndc test"); LoggingEvent event = new LoggingEvent( root.getClass().getName(), root, Level.INFO, "Hello, world.", null); // event.prepareForDeferredProcessing(); int[] skip = new int[] { 352, 353, 354, 355, 356 }; SerializationTestHelper.assertSerializationEquals( "witness/serialization/ndc.bin", event, skip, 237); } /** * Serialize a logging event with mdc. * @throws Exception if exception during test. * */ public void testSerializationMDC() throws Exception { Logger root = Logger.getRootLogger(); MDC.put("mdckey", "mdcvalue"); LoggingEvent event = new LoggingEvent( root.getClass().getName(), root, Level.INFO, "Hello, world.", null); // event.prepareForDeferredProcessing(); int[] skip = new int[] { 352, 353, 354, 355, 356 }; SerializationTestHelper.assertSerializationEquals( "witness/serialization/mdc.bin", event, skip, 237); } /** * Deserialize a simple logging event. * @throws Exception if exception during test. * */ public void testDeserializationSimple() throws Exception { Object obj = SerializationTestHelper.deserializeStream( "witness/serialization/simple.bin"); assertTrue(obj instanceof LoggingEvent); LoggingEvent event = (LoggingEvent) obj; assertEquals("Hello, world.", event.getMessage()); assertEquals(Level.INFO, event.getLevel()); } /** * Deserialize a logging event with an exception. * @throws Exception if exception during test. * */ public void testDeserializationWithException() throws Exception { Object obj = SerializationTestHelper.deserializeStream( "witness/serialization/exception.bin"); assertTrue(obj instanceof LoggingEvent); LoggingEvent event = (LoggingEvent) obj; assertEquals("Hello, world.", event.getMessage()); assertEquals(Level.INFO, event.getLevel()); } /** * Deserialize a logging event with an exception. * @throws Exception if exception during test. * */ public void testDeserializationWithLocation() throws Exception { Object obj = SerializationTestHelper.deserializeStream( "witness/serialization/location.bin"); assertTrue(obj instanceof LoggingEvent); LoggingEvent event = (LoggingEvent) obj; assertEquals("Hello, world.", event.getMessage()); assertEquals(Level.INFO, event.getLevel()); } /** * Tests LoggingEvent.fqnOfCategoryClass. */ public void testFQNOfCategoryClass() { Category root = Logger.getRootLogger(); Priority info = Level.INFO; String catName = Logger.class.toString(); LoggingEvent event = new LoggingEvent( catName, root, info, "Hello, world.", null); assertEquals(catName, event.fqnOfCategoryClass); } /** * Tests LoggingEvent.level. * @deprecated */ public void testLevel() { Category root = Logger.getRootLogger(); Priority info = Level.INFO; String catName = Logger.class.toString(); LoggingEvent event = new LoggingEvent( catName, root, 0L, info, "Hello, world.", null); Priority error = Level.ERROR; event.level = error; assertEquals(Level.ERROR, event.level); } /** * Tests LoggingEvent.getLocationInfo() when no FQCN is specified. * See bug 41186. */ public void testLocationInfoNoFQCN() { Category root = Logger.getRootLogger(); Priority level = Level.INFO; LoggingEvent event = new LoggingEvent( null, root, 0L, level, "Hello, world.", null); LocationInfo info = event.getLocationInformation(); // // log4j 1.2 returns an object, its layout doesn't check for nulls. // log4j 1.3 returns a null. // assertNotNull(info); if (info != null) { assertEquals("?", info.getLineNumber()); assertEquals("?", info.getClassName()); assertEquals("?", info.getFileName()); assertEquals("?", info.getMethodName()); } } /** * Message object that throws a RuntimeException on toString(). * See bug 37182. */ private static class BadMessage { public BadMessage() { } public String toString() { throw new RuntimeException(); } } /** * Tests that an runtime exception or error during toString * on the message parameter does not propagate to caller. * See bug 37182. */ public void testBadMessage() { Category root = Logger.getRootLogger(); Priority info = Level.INFO; String catName = Logger.class.toString(); BadMessage msg = new BadMessage(); LoggingEvent event = new LoggingEvent( catName, root, 0L, info, msg, null); // would result in exception in earlier versions event.getRenderedMessage(); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/spi/ThrowableInformationTest.java0000644000175000017500000002524011751454671030336 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; import junit.framework.TestCase; import java.io.PrintWriter; /** * Unit tests for ThrowableInformation. */ public class ThrowableInformationTest extends TestCase { /** * Create ThrowableInformationTest. * * @param name test name. */ public ThrowableInformationTest(final String name) { super(name); } /** * Custom throwable that only calls methods * overridden by VectorWriter in log4j 1.2.14 and earlier. */ private static final class OverriddenThrowable extends Throwable { private static final long serialVersionUID = 1L; /** * Create new instance. */ public OverriddenThrowable() { } /** * Print stack trace. * * @param s print writer. */ public void printStackTrace(final PrintWriter s) { s.print((Object) "print(Object)"); s.print("print(char[])".toCharArray()); s.print("print(String)"); s.println((Object) "println(Object)"); s.println("println(char[])".toCharArray()); s.println("println(String)"); s.write("write(char[])".toCharArray()); s.write("write(char[], int, int)".toCharArray(), 2, 8); s.write("write(String, int, int)", 2, 8); } } /** * Test capturing stack trace from a throwable that only uses the * PrintWriter methods overridden in log4j 1.2.14 and earlier. */ public void testOverriddenBehavior() { ThrowableInformation ti = new ThrowableInformation(new OverriddenThrowable()); String[] rep = ti.getThrowableStrRep(); assertEquals(4, rep.length); assertEquals("print(Object)print(char[])print(String)println(Object)", rep[0]); assertEquals("println(char[])", rep[1]); assertEquals("println(String)", rep[2]); assertEquals("write(char[])ite(charite(Stri", rep[3]); } /** * Custom throwable that calls methods * not overridden by VectorWriter in log4j 1.2.14 and earlier. */ private static final class NotOverriddenThrowable extends Throwable { private static final long serialVersionUID = 1L; /** * Create new instance. */ public NotOverriddenThrowable() { } /** * Print stack trace. * * @param s print writer. */ public void printStackTrace(final PrintWriter s) { s.print(true); s.print('a'); s.print(1); s.print(2L); s.print(Float.MAX_VALUE); s.print(Double.MIN_VALUE); s.println(true); s.println('a'); s.println(1); s.println(2L); s.println(Float.MAX_VALUE); s.println(Double.MIN_VALUE); s.write('C'); } } /** * Test capturing stack trace from a throwable that uses the * PrintWriter methods not overridden in log4j 1.2.14 and earlier. */ public void testNotOverriddenBehavior() { ThrowableInformation ti = new ThrowableInformation(new NotOverriddenThrowable()); String[] rep = ti.getThrowableStrRep(); assertEquals(7, rep.length); StringBuffer buf = new StringBuffer(String.valueOf(true)); buf.append('a'); buf.append(String.valueOf(1)); buf.append(String.valueOf(2L)); buf.append(String.valueOf(Float.MAX_VALUE)); buf.append(String.valueOf(Double.MIN_VALUE)); buf.append(String.valueOf(true)); assertEquals(buf.toString(), rep[0]); assertEquals("a", rep[1]); assertEquals(String.valueOf(1), rep[2]); assertEquals(String.valueOf(2L), rep[3]); assertEquals(String.valueOf(Float.MAX_VALUE), rep[4]); assertEquals(String.valueOf(Double.MIN_VALUE), rep[5]); assertEquals("C", rep[6]); } /** * Custom throwable that calls methods of VectorWriter * with null. */ private static final class NullThrowable extends Throwable { private static final long serialVersionUID = 1L; /** * Create new instance. */ public NullThrowable() { } /** * Print stack trace. * * @param s print writer. */ public void printStackTrace(final PrintWriter s) { s.print((Object) null); s.print((String) null); s.println((Object) null); s.println((String) null); } } /** * Test capturing stack trace from a throwable that passes * null to PrintWriter methods. */ public void testNull() { ThrowableInformation ti = new ThrowableInformation(new NullThrowable()); String[] rep = ti.getThrowableStrRep(); assertEquals(2, rep.length); String nullStr = String.valueOf((Object) null); assertEquals(nullStr + nullStr + nullStr, rep[0]); assertEquals(nullStr, rep[1]); } /** * Custom throwable that does nothing in printStackTrace. */ private static final class EmptyThrowable extends Throwable { private static final long serialVersionUID = 1L; /** * Create new instance. */ public EmptyThrowable() { } /** * Print stack trace. * * @param s print writer. */ public void printStackTrace(final PrintWriter s) { } } /** * Test capturing stack trace from a throwable that * does nothing on a call to printStackTrace. */ public void testEmpty() { ThrowableInformation ti = new ThrowableInformation(new EmptyThrowable()); String[] rep = ti.getThrowableStrRep(); assertEquals(0, rep.length); } /** * Custom throwable that emits a specified string in printStackTrace. */ private static final class StringThrowable extends Throwable { private static final long serialVersionUID = 1L; /** * Stack trace. */ private final String stackTrace; /** * Create new instance. * @param trace stack trace. */ public StringThrowable(final String trace) { stackTrace = trace; } /** * Print stack trace. * * @param s print writer. */ public void printStackTrace(final PrintWriter s) { s.print(stackTrace); } } /** * Test capturing stack trace from throwable that just has a line feed. */ public void testLineFeed() { ThrowableInformation ti = new ThrowableInformation(new StringThrowable("\n")); String[] rep = ti.getThrowableStrRep(); assertEquals(1, rep.length); assertEquals("", rep[0]); } /** * Test capturing stack trace from throwable that just has a carriage return. */ public void testCarriageReturn() { ThrowableInformation ti = new ThrowableInformation(new StringThrowable("\r")); String[] rep = ti.getThrowableStrRep(); assertEquals(1, rep.length); assertEquals("", rep[0]); } /** * Test parsing of line breaks. */ public void testParsing() { ThrowableInformation ti = new ThrowableInformation( new StringThrowable("Line1\rLine2\nLine3\r\nLine4\n\rLine6")); String[] rep = ti.getThrowableStrRep(); assertEquals(6, rep.length); assertEquals("Line1", rep[0]); assertEquals("Line2", rep[1]); assertEquals("Line3", rep[2]); assertEquals("Line4", rep[3]); assertEquals("", rep[4]); assertEquals("Line6", rep[5]); } /** * Test capturing stack trace from throwable that a line feed followed by blank. */ public void testLineFeedBlank() { ThrowableInformation ti = new ThrowableInformation(new StringThrowable("\n ")); String[] rep = ti.getThrowableStrRep(); assertEquals(2, rep.length); assertEquals("", rep[0]); assertEquals(" ", rep[1]); } /** * Test that getThrowable returns the throwable provided to the constructor. */ public void testGetThrowable() { Throwable t = new StringThrowable("Hello, World"); ThrowableInformation ti = new ThrowableInformation(t); assertSame(t, ti.getThrowable()); } /** * Tests isolation of returned string representation * from internal state of ThrowableInformation. * log4j 1.2.15 and earlier did not isolate initial call. * See bug 44032. */ public void testIsolation() { ThrowableInformation ti = new ThrowableInformation( new StringThrowable("Hello, World")); String[] rep = ti.getThrowableStrRep(); assertEquals("Hello, World", rep[0]); rep[0] = "Bonjour, Monde"; String[] rep2 = ti.getThrowableStrRep(); assertEquals("Hello, World", rep2[0]); } /** * Custom throwable that throws a runtime exception * when printStackTrace is called. */ private static final class NastyThrowable extends Throwable { private static final long serialVersionUID = 1L; /** * Create new instance. */ public NastyThrowable() { } /** * Print stack trace. * * @param s print writer. */ public void printStackTrace(final PrintWriter s) { s.print("NastyException"); throw new RuntimeException("Intentional exception"); } } /** * Tests that a failure in printStackTrace * does not percolate out of getThrowableStrRep(). * */ public void testNastyException() { ThrowableInformation ti = new ThrowableInformation( new NastyThrowable()); String[] rep = ti.getThrowableStrRep(); assertEquals("NastyException", rep[0]); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/TestLogSF.java0000755000175000017500000011220711751454673024365 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; import java.io.CharArrayWriter; /** * Unit test for LogSF. */ public class TestLogSF extends TestCase { /** * Trace level. */ private static final Level TRACE = getTraceLevel(); /** * Gets Trace level. * Trace level was not defined prior to log4j 1.2.12. * @return trace level */ private static Level getTraceLevel() { try { return (Level) Level.class.getField("TRACE").get(null); } catch(Exception ex) { return new Level(5000, "TRACE", 7); } } /** * Logger. */ private final Logger logger = Logger.getLogger( "org.apache.log4j.formatter.TestLogSF"); /** * Create the test case * * @param testName name of the test case */ public TestLogSF(String testName) { super(testName); } /** * Post test clean up. */ public void tearDown() { LogManager.resetConfiguration(); } /** * Test class name when logging through LogSF. */ public void testClassName() { CharArrayWriter writer = new CharArrayWriter(); PatternLayout layout = new PatternLayout("%C"); WriterAppender appender = new WriterAppender(layout, writer); appender.activateOptions(); Logger.getRootLogger().addAppender(appender); LogSF.debug(logger, null, Math.PI); assertEquals(TestLogSF.class.getName(), writer.toString()); } /** * Test LogSF.trace with null pattern. */ public void testTraceNullPattern() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); LogSF.trace(logger, null, Math.PI); assertNull(capture.getMessage()); } /** * Test LogSF.trace with no-field pattern. */ public void testTraceNoArg() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); LogSF.trace(logger, "Hello, World", Math.PI); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogSF.trace with malformed pattern. */ public void testTraceBadPattern() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); LogSF.trace(logger, "Hello, {.", Math.PI); assertEquals("Hello, {.", capture.getMessage()); } /** * Test LogSF.trace with missing argument. */ public void testTraceMissingArg() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); LogSF.trace(logger, "Hello, {}World", new Object[0]); assertEquals("Hello, {}World", capture.getMessage()); } /** * Test LogSF.trace with single field pattern with string argument. */ public void testTraceString() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); LogSF.trace(logger, "Hello, {}", "World"); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogSF.trace with single field pattern with null argument. */ public void testTraceNull() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); LogSF.trace(logger, "Hello, {}", (Object) null); assertEquals("Hello, null", capture.getMessage()); } /** * Test LogSF.trace with single field pattern with int argument. */ public void testTraceInt() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); int val = 42; LogSF.trace(logger, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.trace with single field pattern with byte argument. */ public void testTraceByte() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); byte val = 42; LogSF.trace(logger, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.trace with single field pattern with short argument. */ public void testTraceShort() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); short val = 42; LogSF.trace(logger, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.trace with single field pattern with long argument. */ public void testTraceLong() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); long val = 42; LogSF.trace(logger, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.trace with single field pattern with char argument. */ public void testTraceChar() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); char val = 'C'; LogSF.trace(logger, "Iteration {}", val); assertEquals("Iteration C", capture.getMessage()); } /** * Test LogSF.trace with single field pattern with boolean argument. */ public void testTraceBoolean() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); boolean val = true; LogSF.trace(logger, "Iteration {}", val); assertEquals("Iteration true", capture.getMessage()); } /** * Test LogSF.trace with single field pattern with float argument. */ public void testTraceFloat() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); float val = 3.14f; LogSF.trace(logger, "Iteration {}", val); assertEquals("Iteration " + String.valueOf(val), capture.getMessage()); } /** * Test LogSF.trace with single field pattern with double argument. */ public void testTraceDouble() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); double val = 3.14; LogSF.trace(logger, "Iteration {}", val); assertEquals("Iteration " + String.valueOf(val), capture.getMessage()); } /** * Test LogSF.trace with two arguments. */ public void testTraceTwoArg() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); LogSF.trace(logger, "{}, {}.", "Hello", "World"); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.trace with three arguments. */ public void testTraceThreeArg() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); LogSF.trace(logger, "{}{} {}.", "Hello", ",", "World"); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.trace with Object[] argument. */ public void testTraceFourArg() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); LogSF.trace(logger, "{}{} {}{}", "Hello", ",", "World", "."); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.trace with Object[] argument. */ public void testTraceArrayArg() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); Object[] args = new Object[] { "Hello", ",", "World", "." }; LogSF.trace(logger, "{}{} {}{}", args); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.trace with null Object[] argument. */ public void testTraceNullArrayArg() { LogCapture capture = new LogCapture(TRACE); logger.setLevel(TRACE); Object[] args = null; LogSF.trace(logger, "{}{} {}{}", args); assertEquals("{}{} {}{}", capture.getMessage()); } /** * Test LogSF.debug with null pattern. */ public void testDebugNullPattern() { LogCapture capture = new LogCapture(Level.DEBUG); LogSF.debug(logger, null, Math.PI); assertNull(capture.getMessage()); } /** * Test LogSF.debug with no-field pattern. */ public void testDebugNoArg() { LogCapture capture = new LogCapture(Level.DEBUG); LogSF.debug(logger, "Hello, World", Math.PI); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogSF.debug with malformed pattern. */ public void testDebugBadPattern() { LogCapture capture = new LogCapture(Level.DEBUG); LogSF.debug(logger, "Hello, {.", Math.PI); assertEquals("Hello, {.", capture.getMessage()); } /** * Test LogSF.debug with missing argument. */ public void testDebugMissingArg() { LogCapture capture = new LogCapture(Level.DEBUG); LogSF.debug(logger, "Hello, {}World", new Object[0]); assertEquals("Hello, {}World", capture.getMessage()); } /** * Test LogSF.debug with single field pattern with string argument. */ public void testDebugString() { LogCapture capture = new LogCapture(Level.DEBUG); LogSF.debug(logger, "Hello, {}", "World"); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogSF.debug with single field pattern with null argument. */ public void testDebugNull() { LogCapture capture = new LogCapture(Level.DEBUG); LogSF.debug(logger, "Hello, {}", (Object) null); assertEquals("Hello, null", capture.getMessage()); } /** * Test LogSF.debug with single field pattern with int argument. */ public void testDebugInt() { LogCapture capture = new LogCapture(Level.DEBUG); int val = 42; LogSF.debug(logger, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.debug with single field pattern with byte argument. */ public void testDebugByte() { LogCapture capture = new LogCapture(Level.DEBUG); byte val = 42; LogSF.debug(logger, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.debug with single field pattern with short argument. */ public void testDebugShort() { LogCapture capture = new LogCapture(Level.DEBUG); short val = 42; LogSF.debug(logger, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.debug with single field pattern with long argument. */ public void testDebugLong() { LogCapture capture = new LogCapture(Level.DEBUG); long val = 42; LogSF.debug(logger, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.debug with single field pattern with char argument. */ public void testDebugChar() { LogCapture capture = new LogCapture(Level.DEBUG); char val = 'C'; LogSF.debug(logger, "Iteration {}", val); assertEquals("Iteration C", capture.getMessage()); } /** * Test LogSF.debug with single field pattern with boolean argument. */ public void testDebugBoolean() { LogCapture capture = new LogCapture(Level.DEBUG); boolean val = true; LogSF.debug(logger, "Iteration {}", val); assertEquals("Iteration true", capture.getMessage()); } /** * Test LogSF.debug with single field pattern with float argument. */ public void testDebugFloat() { LogCapture capture = new LogCapture(Level.DEBUG); float val = 3.14f; LogSF.debug(logger, "Iteration {}", val); assertEquals("Iteration " + String.valueOf(val), capture.getMessage()); } /** * Test LogSF.debug with single field pattern with double argument. */ public void testDebugDouble() { LogCapture capture = new LogCapture(Level.DEBUG); double val = 3.14; LogSF.debug(logger, "Iteration {}", val); assertEquals("Iteration " + String.valueOf(val), capture.getMessage()); } /** * Test LogSF.debug with two arguments. */ public void testDebugTwoArg() { LogCapture capture = new LogCapture(Level.DEBUG); LogSF.debug(logger, "{}, {}.", "Hello", "World"); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.debug with three arguments. */ public void testDebugThreeArg() { LogCapture capture = new LogCapture(Level.DEBUG); LogSF.debug(logger, "{}{} {}.", "Hello", ",", "World"); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.debug with four arguments. */ public void testDebugFourArg() { LogCapture capture = new LogCapture(Level.DEBUG); LogSF.debug(logger, "{}{} {}{}", "Hello", ",", "World", "."); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.debug with Object[] argument. */ public void testDebugArrayArg() { LogCapture capture = new LogCapture(Level.DEBUG); Object[] args = new Object[] { "Hello", ",", "World", "." }; LogSF.debug(logger, "{}{} {}{}", args); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.debug with null Object[] argument. */ public void testDebugNullArrayArg() { LogCapture capture = new LogCapture(Level.DEBUG); Object[] args = null; LogSF.debug(logger, "{}{} {}{}", args); assertEquals("{}{} {}{}", capture.getMessage()); } /** * Test LogSF.info with null pattern. */ public void testInfoNullPattern() { LogCapture capture = new LogCapture(Level.INFO); LogSF.info(logger, null, Math.PI); assertNull(capture.getMessage()); } /** * Test LogSF.info with no-field pattern. */ public void testInfoNoArg() { LogCapture capture = new LogCapture(Level.INFO); LogSF.info(logger, "Hello, World", Math.PI); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogSF.info with malformed pattern. */ public void testInfoBadPattern() { LogCapture capture = new LogCapture(Level.INFO); LogSF.info(logger, "Hello, {.", Math.PI); assertEquals("Hello, {.", capture.getMessage()); } /** * Test LogSF.info with missing argument. */ public void testInfoMissingArg() { LogCapture capture = new LogCapture(Level.INFO); LogSF.info(logger, "Hello, {}World", new Object[0]); assertEquals("Hello, {}World", capture.getMessage()); } /** * Test LogSF.info with single field pattern with string argument. */ public void testInfoString() { LogCapture capture = new LogCapture(Level.INFO); LogSF.info(logger, "Hello, {}", "World"); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogSF.info with single field pattern with null argument. */ public void testInfoNull() { LogCapture capture = new LogCapture(Level.INFO); LogSF.info(logger, "Hello, {}", (Object) null); assertEquals("Hello, null", capture.getMessage()); } /** * Test LogSF.info with single field pattern with int argument. */ public void testInfoInt() { LogCapture capture = new LogCapture(Level.INFO); int val = 42; LogSF.info(logger, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.info with single field pattern with byte argument. */ public void testInfoByte() { LogCapture capture = new LogCapture(Level.INFO); byte val = 42; LogSF.info(logger, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.info with single field pattern with short argument. */ public void testInfoShort() { LogCapture capture = new LogCapture(Level.INFO); short val = 42; LogSF.info(logger, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.info with single field pattern with long argument. */ public void testInfoLong() { LogCapture capture = new LogCapture(Level.INFO); long val = 42; LogSF.info(logger, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.info with single field pattern with char argument. */ public void testInfoChar() { LogCapture capture = new LogCapture(Level.INFO); char val = 'C'; LogSF.info(logger, "Iteration {}", val); assertEquals("Iteration C", capture.getMessage()); } /** * Test LogSF.info with single field pattern with boolean argument. */ public void testInfoBoolean() { LogCapture capture = new LogCapture(Level.INFO); boolean val = true; LogSF.info(logger, "Iteration {}", val); assertEquals("Iteration true", capture.getMessage()); } /** * Test LogSF.info with single field pattern with float argument. */ public void testInfoFloat() { LogCapture capture = new LogCapture(Level.INFO); float val = 3.14f; LogSF.info(logger, "Iteration {}", val); assertEquals("Iteration " + String.valueOf(val), capture.getMessage()); } /** * Test LogSF.info with single field pattern with double argument. */ public void testInfoDouble() { LogCapture capture = new LogCapture(Level.INFO); double val = 3.14; LogSF.info(logger, "Iteration {}", val); assertEquals("Iteration " + String.valueOf(val), capture.getMessage()); } /** * Test LogSF.info with two arguments. */ public void testInfoTwoArg() { LogCapture capture = new LogCapture(Level.INFO); LogSF.info(logger, "{}, {}.", "Hello", "World"); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.info with three arguments. */ public void testInfoThreeArg() { LogCapture capture = new LogCapture(Level.INFO); LogSF.info(logger, "{}{} {}.", "Hello", ",", "World"); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.info with Object[] argument. */ public void testInfoArrayArg() { LogCapture capture = new LogCapture(Level.INFO); Object[] args = new Object[] { "Hello", ",", "World", "." }; LogSF.info(logger, "{}{} {}{}", args); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.warn with null pattern. */ public void testWarnNullPattern() { LogCapture capture = new LogCapture(Level.WARN); LogSF.warn(logger, null, Math.PI); assertNull(capture.getMessage()); } /** * Test LogSF.warn with no-field pattern. */ public void testWarnNoArg() { LogCapture capture = new LogCapture(Level.WARN); LogSF.warn(logger, "Hello, World", Math.PI); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogSF.warn with malformed pattern. */ public void testWarnBadPattern() { LogCapture capture = new LogCapture(Level.WARN); LogSF.warn(logger, "Hello, {.", Math.PI); assertEquals("Hello, {.", capture.getMessage()); } /** * Test LogSF.warn with missing argument. */ public void testWarnMissingArg() { LogCapture capture = new LogCapture(Level.WARN); LogSF.warn(logger, "Hello, {}World", new Object[0]); assertEquals("Hello, {}World", capture.getMessage()); } /** * Test LogSF.warn with single field pattern with string argument. */ public void testWarnString() { LogCapture capture = new LogCapture(Level.WARN); LogSF.warn(logger, "Hello, {}", "World"); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogSF.warn with single field pattern with null argument. */ public void testWarnNull() { LogCapture capture = new LogCapture(Level.WARN); LogSF.warn(logger, "Hello, {}", (Object) null); assertEquals("Hello, null", capture.getMessage()); } /** * Test LogSF.warn with single field pattern with int argument. */ public void testWarnInt() { LogCapture capture = new LogCapture(Level.WARN); int val = 42; LogSF.warn(logger, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.warn with single field pattern with byte argument. */ public void testWarnByte() { LogCapture capture = new LogCapture(Level.WARN); byte val = 42; LogSF.warn(logger, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.warn with single field pattern with short argument. */ public void testWarnShort() { LogCapture capture = new LogCapture(Level.WARN); short val = 42; LogSF.warn(logger, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.warn with single field pattern with long argument. */ public void testWarnLong() { LogCapture capture = new LogCapture(Level.WARN); long val = 42; LogSF.warn(logger, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.warn with single field pattern with char argument. */ public void testWarnChar() { LogCapture capture = new LogCapture(Level.WARN); char val = 'C'; LogSF.warn(logger, "Iteration {}", val); assertEquals("Iteration C", capture.getMessage()); } /** * Test LogSF.warn with single field pattern with boolean argument. */ public void testWarnBoolean() { LogCapture capture = new LogCapture(Level.WARN); boolean val = true; LogSF.warn(logger, "Iteration {}", val); assertEquals("Iteration true", capture.getMessage()); } /** * Test LogSF.warn with single field pattern with float argument. */ public void testWarnFloat() { LogCapture capture = new LogCapture(Level.WARN); float val = 3.14f; LogSF.warn(logger, "Iteration {}", val); assertEquals("Iteration " + String.valueOf(val), capture.getMessage()); } /** * Test LogSF.warn with single field pattern with double argument. */ public void testWarnDouble() { LogCapture capture = new LogCapture(Level.WARN); double val = 3.14; LogSF.warn(logger, "Iteration {}", val); assertEquals("Iteration " + String.valueOf(val), capture.getMessage()); } /** * Test LogSF.warn with two arguments. */ public void testWarnTwoArg() { LogCapture capture = new LogCapture(Level.WARN); LogSF.warn(logger, "{}, {}.", "Hello", "World"); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.warn with three arguments. */ public void testWarnThreeArg() { LogCapture capture = new LogCapture(Level.WARN); LogSF.warn(logger, "{}{} {}.", "Hello", ",", "World"); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.warn with Object[] argument. */ public void testWarnFourArg() { LogCapture capture = new LogCapture(Level.WARN); LogSF.warn(logger, "{}{} {}{}", "Hello", ",", "World", "." ); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.warn with Object[] argument. */ public void testWarnArrayArg() { LogCapture capture = new LogCapture(Level.WARN); Object[] args = new Object[] { "Hello", ",", "World", "." }; LogSF.warn(logger, "{}{} {}{}", args); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.log with null pattern. */ public void testLogNullPattern() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.log(logger, Level.ERROR, null, Math.PI); assertNull(capture.getMessage()); } /** * Test LogSF.log with no-field pattern. */ public void testLogNoArg() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.log(logger, Level.ERROR, "Hello, World", Math.PI); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogSF.log with malformed pattern. */ public void testLogBadPattern() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.log(logger, Level.ERROR, "Hello, {.", Math.PI); assertEquals("Hello, {.", capture.getMessage()); } /** * Test LogSF.log with missing argument. */ public void testLogMissingArg() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.log(logger, Level.ERROR, "Hello, {}World", new Object[0]); assertEquals("Hello, {}World", capture.getMessage()); } /** * Test LogSF.log with single field pattern with string argument. */ public void testLogString() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.log(logger, Level.ERROR, "Hello, {}", "World"); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogSF.log with single field pattern with null argument. */ public void testLogNull() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.log(logger, Level.ERROR, "Hello, {}", (Object) null); assertEquals("Hello, null", capture.getMessage()); } /** * Test LogSF.log with single field pattern with int argument. */ public void testLogInt() { LogCapture capture = new LogCapture(Level.ERROR); int val = 42; LogSF.log(logger, Level.ERROR, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.log with single field pattern with byte argument. */ public void testLogByte() { LogCapture capture = new LogCapture(Level.ERROR); byte val = 42; LogSF.log(logger, Level.ERROR, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.log with single field pattern with short argument. */ public void testLogShort() { LogCapture capture = new LogCapture(Level.ERROR); short val = 42; LogSF.log(logger, Level.ERROR, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.log with single field pattern with long argument. */ public void testLogLong() { LogCapture capture = new LogCapture(Level.ERROR); long val = 42; LogSF.log(logger, Level.ERROR, "Iteration {}", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.log with single field pattern with char argument. */ public void testLogChar() { LogCapture capture = new LogCapture(Level.ERROR); char val = 'C'; LogSF.log(logger, Level.ERROR, "Iteration {}", val); assertEquals("Iteration C", capture.getMessage()); } /** * Test LogSF.log with single field pattern with boolean argument. */ public void testLogBoolean() { LogCapture capture = new LogCapture(Level.ERROR); boolean val = true; LogSF.log(logger, Level.ERROR, "Iteration {}", val); assertEquals("Iteration true", capture.getMessage()); } /** * Test LogSF.log with single field pattern with float argument. */ public void testLogFloat() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.log(logger, Level.ERROR, "Iteration {}", (float) Math.PI); String expected = "Iteration " + String.valueOf(new Float(Math.PI)); assertEquals(expected, capture.getMessage()); } /** * Test LogSF.log with single field pattern with double argument. */ public void testLogDouble() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.log(logger, Level.ERROR, "Iteration {}", Math.PI); String expected = "Iteration " + String.valueOf(new Double(Math.PI)); assertEquals(expected, capture.getMessage()); } /** * Test LogSF.log with two arguments. */ public void testLogTwoArg() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.log(logger, Level.ERROR, "{}, {}.", "Hello", "World"); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.log with three arguments. */ public void testLogThreeArg() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.log(logger, Level.ERROR, "{}{} {}.", "Hello", ",", "World"); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.log with four arguments. */ public void testLogFourArg() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.log(logger, Level.ERROR, "{}{} {}{}", "Hello", ",", "World", "."); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.log with Object[] argument. */ public void testLogArrayArg() { LogCapture capture = new LogCapture(Level.ERROR); Object[] args = new Object[] { "Hello", ",", "World", "." }; LogSF.log(logger, Level.ERROR, "{}{} {}{}", args); assertEquals("Hello, World.", capture.getMessage()); } /** * Bundle name for resource bundle tests. */ private static final String BUNDLE_NAME = "org.apache.log4j.TestLogSFPatterns"; /** * Test LogSF.logrb with null bundle name. */ public void testLogrbNullBundle() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.logrb(logger, Level.ERROR, null, "Iteration0", Math.PI); assertEquals("Iteration0", capture.getMessage()); } /** * Test LogSF.logrb with null key. */ public void testLogrbNullKey() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.logrb(logger, Level.ERROR, BUNDLE_NAME, null, Math.PI); assertNull(capture.getMessage()); } /** * Test LogSF.logrb with no-field pattern. */ public void testLogrbNoArg() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Hello1", Math.PI); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogSF.logrb with malformed pattern. */ public void testLogrbBadPattern() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Malformed", Math.PI); assertEquals("Hello, {.", capture.getMessage()); } /** * Test LogSF.logrb with missing argument. */ public void testLogrbMissingArg() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Hello2", new Object[0]); assertEquals("Hello, {}World", capture.getMessage()); } /** * Test LogSF.logrb with single field pattern with string argument. */ public void testLogrbString() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Hello3", "World"); assertEquals("Hello, World", capture.getMessage()); } /** * Test LogSF.logrb with single field pattern with null argument. */ public void testLogrbNull() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Hello3", (Object) null); assertEquals("Hello, null", capture.getMessage()); } /** * Test LogSF.logrb with single field pattern with int argument. */ public void testLogrbInt() { LogCapture capture = new LogCapture(Level.ERROR); int val = 42; LogSF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Iteration0", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.logrb with single field pattern with byte argument. */ public void testLogrbByte() { LogCapture capture = new LogCapture(Level.ERROR); byte val = 42; LogSF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Iteration0", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.logrb with single field pattern with short argument. */ public void testLogrbShort() { LogCapture capture = new LogCapture(Level.ERROR); short val = 42; LogSF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Iteration0", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.logrb with single field pattern with long argument. */ public void testLogrbLong() { LogCapture capture = new LogCapture(Level.ERROR); long val = 42; LogSF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Iteration0", val); assertEquals("Iteration 42", capture.getMessage()); } /** * Test LogSF.logrb with single field pattern with char argument. */ public void testLogrbChar() { LogCapture capture = new LogCapture(Level.ERROR); char val = 'C'; LogSF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Iteration0", val); assertEquals("Iteration C", capture.getMessage()); } /** * Test LogSF.logrb with single field pattern with boolean argument. */ public void testLogrbBoolean() { LogCapture capture = new LogCapture(Level.ERROR); boolean val = true; LogSF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Iteration0", val); assertEquals("Iteration true", capture.getMessage()); } /** * Test LogSF.logrb with single field pattern with float argument. */ public void testLogrbFloat() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Iteration0", (float) Math.PI); String expected = "Iteration " + String.valueOf(new Float(Math.PI)); assertEquals(expected, capture.getMessage()); } /** * Test LogSF.logrb with single field pattern with double argument. */ public void testLogrbDouble() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Iteration0", Math.PI); String expected = "Iteration " + String.valueOf(new Double(Math.PI)); assertEquals(expected, capture.getMessage()); } /** * Test LogSF.logrb with two arguments. */ public void testLogrbTwoArg() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Hello4", "Hello", "World"); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.logrb with three arguments. */ public void testLogrbThreeArg() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Hello5", "Hello", ",", "World"); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.logrb with four arguments. */ public void testLogrbFourArg() { LogCapture capture = new LogCapture(Level.ERROR); LogSF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Hello6", "Hello", ",", "World", "."); assertEquals("Hello, World.", capture.getMessage()); } /** * Test LogSF.logrb with Object[] argument. */ public void testLogrbArrayArg() { LogCapture capture = new LogCapture(Level.ERROR); Object[] args = new Object[] { "Hello", ",", "World", "." }; LogSF.logrb(logger, Level.ERROR, BUNDLE_NAME, "Hello6", args); assertEquals("Hello, World.", capture.getMessage()); } /** * Test \\{ escape sequence when only one parameter is present. * */ public void testEscapeOneParam() { LogCapture capture = new LogCapture(Level.INFO); LogSF.info(logger, "\\{}\\{{}}, World}\\{","Hello"); assertEquals("{}{Hello}, World}{", capture.getMessage()); } /** * Test \\{ escape sequence when more than one parameter is present. * */ public void testEscapeTwoParam() { LogCapture capture = new LogCapture(Level.INFO); LogSF.info(logger, "\\{}\\{{}}, {}}{}\\{","Hello", "World"); assertEquals("{}{Hello}, World}{}{", capture.getMessage()); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/stressCategory.pl0000644000175000017500000000331111751454673025256 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This perl script all combinations of tree structures based on the "args" # array. # For example, if args = ("a", "b", "c"), it will output: # # stressTest a b c # stressTest a b a.c # stressTest a b b.c # stressTest a a.b c # stressTest a a.b a.c # stressTest a a.b a.b.c $prefix = "stressTest"; @tree = (""); @args = ("a", "b"); permute(0, @tree); @args = ("a", "b", "c"); permute(0, @tree); @args = ("a", "b", "c", "d"); permute(0, @tree); @args = ("a", "b", "c", "d", "e"); permute(0, @tree); @args = ("a", "b", "c", "d", "e", "f"); permute(0, @tree); sub permute() { my ($i, @t) = @_; #print "Tree is @t\n"; #print "i is $i \n"; if($i == $#args + 1) { print "$prefix @t\n"; return; } foreach $j (@t) { #print "J is $j \n"; #print "args[$i]=$args[$i]\n"; if($j eq "") { $next = "$args[$i]"; } else { $next = "$j.$args[$i]"; } permute($i+1, (@t, $next)); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/StressCategory.java0000644000175000017500000001365311751454673025536 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.Level; import org.apache.log4j.Logger; import java.util.Random; /* Stress test the Logger class. */ class StressCategory { static Level[] level = new Level[] {Level.DEBUG, Level.INFO, Level.WARN, Level.ERROR, Level.FATAL}; static Level defaultLevel = Logger.getRootLogger().getLevel(); static int LENGTH; static String[] names; static Logger[] cat; static CT[] ct; static Random random = new Random(10); public static void main(String[] args) { LENGTH = args.length; if(LENGTH == 0) { System.err.println( "Usage: java " + StressCategory.class.getName() + " name1 ... nameN\n."); System.exit(1); } if(LENGTH >= 7) { System.err.println( "This stress test suffers from combinatorial explosion.\n"+ "Invoking with seven arguments takes about 90 minutes even on fast machines"); } names = new String[LENGTH]; for(int i=0; i < LENGTH; i++) { names[i] = args[i]; } cat = new Logger[LENGTH]; ct = new CT[LENGTH]; permute(0); // If did not exit, then passed all tests. } // Loop through all permutations of names[]. // On each possible permutation call createLoop static void permute(int n) { if(n == LENGTH) createLoop(0); else for(int i = n; i < LENGTH; i++) { swap(names, n, i); permute(n+1); swap(names, n, i); } } static void swap(String[] names, int i, int j) { String t = names[i]; names[i] = names[j]; names[j] = t; } public static void permutationDump() { System.out.print("Current permutation is - "); for(int i = 0; i < LENGTH; i++) { System.out.print(names[i] + " "); } System.out.println(); } // Loop through all possible 3^n combinations of not instantiating, // instantiating and setting/not setting a level. static void createLoop(int n) { if(n == LENGTH) { //System.out.println("..............Creating cat[]..........."); for(int i = 0; i < LENGTH; i++) { if(ct[i] == null) cat[i] = null; else { cat[i] = Logger.getLogger(ct[i].catstr); cat[i].setLevel(ct[i].level); } } test(); // Clear hash table for next round Hierarchy h = (Hierarchy) LogManager.getLoggerRepository(); h.clear(); } else { ct[n] = null; createLoop(n+1); ct[n] = new CT(names[n], null); createLoop(n+1); int r = random.nextInt(); if(r < 0) r = -r; ct[n] = new CT(names[n], level[r%5]); createLoop(n+1); } } static void test() { //System.out.println("++++++++++++TEST called+++++++++++++"); //permutationDump(); //catDump(); for(int i = 0; i < LENGTH; i++) { if(!checkCorrectness(i)) { System.out.println("Failed stress test."); permutationDump(); //Hierarchy._default.fullDump(); ctDump(); catDump(); System.exit(1); } } } static void ctDump() { for(int j = 0; j < LENGTH; j++) { if(ct[j] != null) System.out.println("ct [" + j + "] = ("+ct[j].catstr+"," + ct[j].level + ")"); else System.out.println("ct [" + j + "] = undefined"); } } static void catDump() { for(int j = 0; j < LENGTH; j++) { if(cat[j] != null) System.out.println("cat[" + j + "] = (" + cat[j].name + "," + cat[j].getLevel() + ")"); else System.out.println("cat[" + j + "] = undefined"); } } // static //void provisionNodesDump() { //for (Enumeration e = CategoryFactory.ht.keys(); e.hasMoreElements() ;) { // CategoryKey key = (CategoryKey) e.nextElement(); // Object c = CategoryFactory.ht.get(key); // if(c instanceof ProvisionNode) //((ProvisionNode) c).dump(key.name); //} //} static boolean checkCorrectness(int i) { CT localCT = ct[i]; // Can't perform test if logger is not instantiated if(localCT == null) return true; // find expected level Level expected = getExpectedPrioriy(localCT); Level purported = cat[i].getEffectiveLevel(); if(expected != purported) { System.out.println("Expected level for " + localCT.catstr + " is " + expected); System.out.println("Purported level for "+ cat[i].name + " is "+purported); return false; } return true; } static Level getExpectedPrioriy(CT ctParam) { Level level = ctParam.level; if(level != null) return level; String catstr = ctParam.catstr; for(int i = catstr.lastIndexOf('.', catstr.length()-1); i >= 0; i = catstr.lastIndexOf('.', i-1)) { String substr = catstr.substring(0, i); // find the level of ct corresponding to substr for(int j = 0; j < LENGTH; j++) { if(ct[j] != null && substr.equals(ct[j].catstr)) { Level p = ct[j].level; if(p != null) return p; } } } return defaultLevel; } static class CT { public String catstr; public Level level; CT(String catstr, Level level) { this.catstr = catstr; this.level = level; } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/helpers/0000755000175000017500000000000012126647422023335 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/helpers/CyclicBufferTestCase.java0000644000175000017500000001034011751454671030177 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // // Log4j uses the JUnit framework for internal unit testing. JUnit // available from // // http://www.junit.org package org.apache.log4j.helpers; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.Logger; import org.apache.log4j.Level; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; /** Unit test the {@link CyclicBuffer}. @author Ceki Gülcü */ public class CyclicBufferTestCase extends TestCase { static Logger cat = Logger.getLogger("x"); static int MAX = 1000; static LoggingEvent[] e = new LoggingEvent[MAX]; { for (int i = 0; i < MAX; i++) { e[i] = new LoggingEvent("", cat, Level.DEBUG, "e"+i, null); } } public CyclicBufferTestCase(String name) { super(name); } public void setUp() { } public void test0() { int size = 2; CyclicBuffer cb = new CyclicBuffer(size); assertEquals(cb.getMaxSize(), size); cb.add(e[0]); assertEquals(cb.length(), 1); assertEquals(cb.get(), e[0]); assertEquals(cb.length(), 0); assertNull(cb.get()); assertEquals(cb.length(), 0); cb = new CyclicBuffer(size); cb.add(e[0]); cb.add(e[1]); assertEquals(cb.length(), 2); assertEquals(cb.get(), e[0]); assertEquals(cb.length(), 1); assertEquals(cb.get(), e[1]); assertEquals(cb.length(), 0); assertNull(cb.get()); assertEquals(cb.length(), 0); } /** Test a buffer of size 1,2,4,8,..,128 */ public void test1() { for(int bufSize = 1; bufSize <= 128; bufSize *=2) doTest1(bufSize); } void doTest1(int size) { //System.out.println("Doing test with size = "+size); CyclicBuffer cb = new CyclicBuffer(size); assertEquals(cb.getMaxSize(), size); for(int i = -(size+10); i < (size+10); i++) { assertNull(cb.get(i)); } for(int i = 0; i < MAX; i++) { cb.add(e[i]); int limit = i < size-1 ? i : size-1; //System.out.println("\nLimit is " + limit + ", i="+i); for(int j = limit; j >= 0; j--) { //System.out.println("i= "+i+", j="+j); assertEquals(cb.get(j), e[i-(limit-j)]); } assertNull(cb.get(-1)); assertNull(cb.get(limit+1)); } } public void testResize() { for(int isize = 1; isize <= 128; isize *=2) { doTestResize(isize, isize/2+1, isize/2+1); doTestResize(isize, isize/2+1, isize+10); doTestResize(isize, isize+10, isize/2+1); doTestResize(isize, isize+10, isize+10); } } void doTestResize(int initialSize, int numberOfAdds, int newSize) { //System.out.println("initialSize = "+initialSize+", numberOfAdds=" // +numberOfAdds+", newSize="+newSize); CyclicBuffer cb = new CyclicBuffer(initialSize); for(int i = 0; i < numberOfAdds; i++) { cb.add(e[i]); } cb.resize(newSize); int offset = numberOfAdds - initialSize; if(offset< 0) offset = 0; int len = newSize < numberOfAdds ? newSize : numberOfAdds; len = len < initialSize ? len : initialSize; //System.out.println("Len = "+len+", offset="+offset); for(int j = 0; j < len; j++) { assertEquals(cb.get(j), e[offset+j]); } } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new CyclicBufferTestCase("test0")); suite.addTest(new CyclicBufferTestCase("test1")); suite.addTest(new CyclicBufferTestCase("testResize")); return suite; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/helpers/UtilLoggingLevelTest.java0000644000175000017500000000245311751454671030265 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import junit.framework.*; /** * Unit tests for UtilLoggingLevel. */ public class UtilLoggingLevelTest extends TestCase { /** * Create new instance of test. * * @param testName test name */ public UtilLoggingLevelTest(final String testName) { super(testName); } /** * Test toLevel("fiNeSt"). */ public void testToLevelFINEST() { assertSame(UtilLoggingLevel.FINEST, UtilLoggingLevel.toLevel("fiNeSt")); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/helpers/OptionConverterTestCase.java0000644000175000017500000001271611751454671031010 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Log4j uses the JUnit framework for internal unit testing. JUnit // is available from "http://www.junit.org". package org.apache.log4j.helpers; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.PropertyConfiguratorTest; import org.apache.log4j.xml.XLevel; /** Test variable substitution code. @author Ceki Gülcü @since 1.0 */ public class OptionConverterTestCase extends TestCase { Properties props; public OptionConverterTestCase(String name) { super(name); } public void setUp() { props = new Properties(); props.put("TOTO", "wonderful"); props.put("key1", "value1"); props.put("key2", "value2"); // Log4J will NPE without this: props.put("line.separator", System.getProperty("line.separator")); // Log4J will throw an Error without this: props.put("java.home", System.getProperty("java.home")); System.setProperties(props); } public void tearDown() { props = null; LogManager.resetConfiguration(); } public void varSubstTest1() { String r; r = OptionConverter.substVars("hello world.", null); assertEquals("hello world.", r); r = OptionConverter.substVars("hello ${TOTO} world.", null); assertEquals("hello wonderful world.", r); } public void varSubstTest2() { String r; r = OptionConverter.substVars("Test2 ${key1} mid ${key2} end.", null); assertEquals("Test2 value1 mid value2 end.", r); } public void varSubstTest3() { String r; r = OptionConverter.substVars( "Test3 ${unset} mid ${key1} end.", null); assertEquals("Test3 mid value1 end.", r); } public void varSubstTest4() { String val = "Test4 ${incomplete "; try { OptionConverter.substVars(val, null); } catch(IllegalArgumentException e) { String errorMsg = e.getMessage(); //System.out.println('['+errorMsg+']'); assertEquals('"'+val + "\" has no closing brace. Opening brace at position 6.", errorMsg); } } public void varSubstTest5() { Properties props = new Properties(); props.put("p1", "x1"); props.put("p2", "${p1}"); String res = OptionConverter.substVars("${p2}", props); System.out.println("Result is ["+res+"]."); assertEquals(res, "x1"); } /** * Tests configuring Log4J from an InputStream. * * @since 1.2.17 */ public void testInputStream() throws IOException { File file = new File("input/filter1.properties"); assertTrue(file.exists()); FileInputStream inputStream = new FileInputStream(file); try { OptionConverter.selectAndConfigure(inputStream, null, LogManager.getLoggerRepository()); } finally { inputStream.close(); } new PropertyConfiguratorTest(this.getClass().getName()).validateNested(); } public void toLevelTest1() { String val = "INFO"; Level p = OptionConverter.toLevel(val, null); assertEquals(p, Level.INFO); } public void toLevelTest2() { String val = "INFO#org.apache.log4j.xml.XLevel"; Level p = OptionConverter.toLevel(val, null); assertEquals(p, Level.INFO); } public void toLevelTest3() { String val = "TRACE#org.apache.log4j.xml.XLevel"; Level p = OptionConverter.toLevel(val, null); assertEquals(p, XLevel.TRACE); } public void toLevelTest4() { String val = "TR#org.apache.log4j.xml.XLevel"; Level p = OptionConverter.toLevel(val, null); assertEquals(p, null); } public void toLevelTest5() { String val = "INFO#org.apache.log4j.xml.TOTO"; Level p = OptionConverter.toLevel(val, null); assertEquals(p, null); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new OptionConverterTestCase("varSubstTest5")); suite.addTest(new OptionConverterTestCase("varSubstTest1")); suite.addTest(new OptionConverterTestCase("varSubstTest2")); suite.addTest(new OptionConverterTestCase("varSubstTest3")); suite.addTest(new OptionConverterTestCase("varSubstTest4")); suite.addTest(new OptionConverterTestCase("testInputStream")); suite.addTest(new OptionConverterTestCase("toLevelTest1")); suite.addTest(new OptionConverterTestCase("toLevelTest2")); suite.addTest(new OptionConverterTestCase("toLevelTest3")); suite.addTest(new OptionConverterTestCase("toLevelTest4")); suite.addTest(new OptionConverterTestCase("toLevelTest5")); return suite; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/helpers/PatternParserTestCase.java0000644000175000017500000001017111751454671030433 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; import org.apache.log4j.Logger; import org.apache.log4j.Level; import org.apache.log4j.Appender; import org.apache.log4j.FileAppender; import org.apache.log4j.PatternLayout; import org.apache.log4j.MDC; import org.apache.log4j.util.Compare; /** Test case for helpers/PatternParser.java. Tests the various conversion patterns supported by PatternParser. This test class tests PatternParser via the PatternLayout class which uses it. */ public class PatternParserTestCase extends TestCase { static String OUTPUT_FILE = "output/PatternParser"; static String WITNESS_FILE = "witness/PatternParser"; static String msgPattern = "%m%n"; Logger root; Logger logger; public PatternParserTestCase(String name) { super(name); } public void setUp() { root = Logger.getRootLogger(); root.removeAllAppenders(); } public void tearDown() { root.getLoggerRepository().resetConfiguration(); } /** Test case for MDC conversion pattern. */ public void mdcPattern() throws Exception { String mdcMsgPattern1 = "%m : %X%n"; String mdcMsgPattern2 = "%m : %X{key1}%n"; String mdcMsgPattern3 = "%m : %X{key2}%n"; String mdcMsgPattern4 = "%m : %X{key3}%n"; String mdcMsgPattern5 = "%m : %X{key1},%X{key2},%X{key3}%n"; // set up appender PatternLayout layout = new PatternLayout(msgPattern); Appender appender = new FileAppender(layout, OUTPUT_FILE+"_mdc", false); // set appender on root and set level to debug root.addAppender(appender); root.setLevel(Level.DEBUG); // output starting message root.debug("starting mdc pattern test"); layout.setConversionPattern(mdcMsgPattern1); root.debug("empty mdc, no key specified in pattern"); layout.setConversionPattern(mdcMsgPattern2); root.debug("empty mdc, key1 in pattern"); layout.setConversionPattern(mdcMsgPattern3); root.debug("empty mdc, key2 in pattern"); layout.setConversionPattern(mdcMsgPattern4); root.debug("empty mdc, key3 in pattern"); layout.setConversionPattern(mdcMsgPattern5); root.debug("empty mdc, key1, key2, and key3 in pattern"); MDC.put("key1", "value1"); MDC.put("key2", "value2"); layout.setConversionPattern(mdcMsgPattern1); root.debug("filled mdc, no key specified in pattern"); layout.setConversionPattern(mdcMsgPattern2); root.debug("filled mdc, key1 in pattern"); layout.setConversionPattern(mdcMsgPattern3); root.debug("filled mdc, key2 in pattern"); layout.setConversionPattern(mdcMsgPattern4); root.debug("filled mdc, key3 in pattern"); layout.setConversionPattern(mdcMsgPattern5); root.debug("filled mdc, key1, key2, and key3 in pattern"); MDC.remove("key1"); MDC.remove("key2"); layout.setConversionPattern(msgPattern); root.debug("finished mdc pattern test"); assertTrue(Compare.compare(OUTPUT_FILE+"_mdc", WITNESS_FILE+"_mdc")); } public static Test suite() { TestSuite suite = new TestSuite(); // // MDC requires JDK 1.2+ // if (!System.getProperty("java.version").startsWith("1.1.")) { suite.addTest(new PatternParserTestCase("mdcPattern")); } return suite; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/helpers/LogLogTest.java0000644000175000017500000000267211751454671026237 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import junit.framework.TestCase; /** * Tests for LogLog. * * @author Curt Arnold **/ public class LogLogTest extends TestCase { /** * Create new instance of LogLogTest. * @param testName test name */ public LogLogTest(final String testName) { super(testName); } /** * Check value of DEBUG_KEY. */ public void testDebugKey() { assertEquals("log4j.debug", LogLog.DEBUG_KEY); } /** * Check value of CONFIG_DEBUG_KEY. * @deprecated since constant is deprecated */ public void testConfigDebugKey() { assertEquals("log4j.configDebug", LogLog.CONFIG_DEBUG_KEY); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/helpers/BoundedFIFOTestCase.java0000644000175000017500000001263611751454671027675 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // // Log4j uses the JUnit framework for internal unit testing. JUnit // available from // // http://www.junit.org package org.apache.log4j.helpers; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.Logger; import org.apache.log4j.Level; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; /** Unit test the {@link BoundedFIFO}. @author Ceki Gülcü @since 0.9.1 */ public class BoundedFIFOTestCase extends TestCase { static Logger cat = Logger.getLogger("x"); static int MAX = 1000; static LoggingEvent[] e = new LoggingEvent[MAX]; { for (int i = 0; i < MAX; i++) { e[i] = new LoggingEvent("", cat, Level.DEBUG, "e"+i, null); } } public BoundedFIFOTestCase(String name) { super(name); } public void setUp() { } /** Pattern: +++++..-----.. */ public void test1() { for(int size = 1; size <= 128; size *=2) { BoundedFIFO bf = new BoundedFIFO(size); assertEquals(bf.getMaxSize(), size); assertNull(bf.get()); int i; int j; int k; for(i = 1; i < 2*size; i++) { for(j = 0; j < i; j++) { //System.out.println("Putting "+e[j]); bf.put(e[j]); assertEquals(bf.length(), j < size ? j+1 : size); } int max = size < j ? size : j; j--; for(k = 0; k <= j; k++) { //System.out.println("max="+max+", j="+j+", k="+k); assertEquals(bf.length(), max - k > 0 ? max - k : 0); Object r = bf.get(); //System.out.println("Got "+r); if(k >= size) assertNull(r); else assertEquals(r, e[k]); } } //System.out.println("Passed size="+size); } } /** Pattern: ++++--++--++ */ public void test2() { int size = 3; BoundedFIFO bf = new BoundedFIFO(size); bf.put(e[0]); assertEquals(bf.get(), e[0]); assertNull(bf.get()); bf.put(e[1]); assertEquals(bf.length(), 1); bf.put(e[2]); assertEquals(bf.length(), 2); bf.put(e[3]); assertEquals(bf.length(), 3); assertEquals(bf.get(), e[1]); assertEquals(bf.length(), 2); assertEquals(bf.get(), e[2]); assertEquals(bf.length(), 1); assertEquals(bf.get(), e[3]); assertEquals(bf.length(), 0); assertNull(bf.get()); assertEquals(bf.length(), 0); } int min(int a, int b) { return a < b ? a : b; } /** Pattern ++++++++++++++++++++ (insert only); */ public void testResize1() { int size = 10; for(int n = 1; n < size*2; n++) { for(int i = 0; i < size*2; i++) { BoundedFIFO bf = new BoundedFIFO(size); for(int f = 0; f < i; f++) { bf.put(e[f]); } bf.resize(n); int expectedSize = min(n, min(i, size)); assertEquals(bf.length(), expectedSize); for(int c = 0; c < expectedSize; c++) { assertEquals(bf.get(), e[c]); } } } } /** Pattern ++...+ --...- */ public void testResize2() { int size = 10; for(int n = 1; n < size*2; n++) { for(int i = 0; i < size*2; i++) { for(int d = 0; d < min(i,size); d++) { BoundedFIFO bf = new BoundedFIFO(size); for(int p = 0; p < i; p++) { bf.put(e[p]); } for(int g = 0; g < d; g++) { bf.get(); } // x = the number of elems in int x = bf.length(); bf.resize(n); int expectedSize = min(n, x); assertEquals(bf.length(), expectedSize); for(int c = 0; c < expectedSize; c++) { assertEquals(bf.get(), e[c+d]); } assertNull(bf.get()); } } } } /** Pattern: i inserts, d deletes, r inserts */ public void testResize3() { int size = 10; for(int n = 1; n < size*2; n++) { for(int i = 0; i < size; i++) { for(int d = 0; d < i; d++) { for(int r = 0; r < d; r++) { BoundedFIFO bf = new BoundedFIFO(size); for(int p0 = 0; p0 < i; p0++) bf.put(e[p0]); for(int g = 0; g < d; g++) bf.get(); for(int p1 = 0; p1 < r; p1++) bf.put(e[i+p1]); int x = bf.length(); bf.resize(n); int expectedSize = min(n, x); assertEquals(bf.length(), expectedSize); for(int c = 0; c < expectedSize; c++) { assertEquals(bf.get(), e[c+d]); } //assertNull(bf.get()); } } } } } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new BoundedFIFOTestCase("test1")); suite.addTest(new BoundedFIFOTestCase("test2")); suite.addTest(new BoundedFIFOTestCase("testResize1")); suite.addTest(new BoundedFIFOTestCase("testResize2")); suite.addTest(new BoundedFIFOTestCase("testResize3")); return suite; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/helpers/DateLayoutTest.java0000644000175000017500000001726311751454671027131 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import org.apache.log4j.Layout; import org.apache.log4j.LayoutTest; import org.apache.log4j.spi.LoggingEvent; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.TimeZone; import java.util.Calendar; /** * Tests for DateLayout. * */ public class DateLayoutTest extends LayoutTest { /** * Construct a new instance of LayoutTest. * @param testName test name. */ public DateLayoutTest(final String testName) { super(testName); } /** * Constructor for use by derived tests. * @param testName name of test. * @param expectedContentType expected value for getContentType(). * @param expectedIgnoresThrowable expected value for ignoresThrowable(). * @param expectedHeader expected value for getHeader(). * @param expectedFooter expected value for getFooter(). */ protected DateLayoutTest( final String testName, final String expectedContentType, final boolean expectedIgnoresThrowable, final String expectedHeader, final String expectedFooter) { super( testName, expectedContentType, expectedIgnoresThrowable, expectedHeader, expectedFooter); } /** * @{inheritDoc} */ protected Layout createLayout() { return new MockLayout(); } /** * Tests DateLayout.NULL_DATE_FORMAT constant. */ public void testNullDateFormat() { assertEquals("NULL", DateLayout.NULL_DATE_FORMAT); } /** * Tests DateLayout.RELATIVE constant. */ public void testRelativeTimeDateFormat() { assertEquals("RELATIVE", DateLayout.RELATIVE_TIME_DATE_FORMAT); } /** * Tests DateLayout.DATE_FORMAT_OPTION constant. * @deprecated since constant is deprecated */ public void testDateFormatOption() { assertEquals("DateFormat", DateLayout.DATE_FORMAT_OPTION); } /** * Tests DateLayout.TIMEZONE_OPTION constant. * @deprecated since constant is deprecated */ public void testTimeZoneOption() { assertEquals("TimeZone", DateLayout.TIMEZONE_OPTION); } /** * Tests getOptionStrings(). * @deprecated since getOptionStrings is deprecated. * */ public void testGetOptionStrings() { String[] options = ((DateLayout) createLayout()).getOptionStrings(); assertEquals(2, options.length); } /** * Tests setting DateFormat through setOption method. * @deprecated since setOption is deprecated. */ public void testSetOptionDateFormat() { DateLayout layout = (DateLayout) createLayout(); layout.setOption("dAtefOrmat", "foobar"); assertEquals("FOOBAR", layout.getDateFormat()); } /** * Tests setting TimeZone through setOption method. * @deprecated since setOption is deprecated. */ public void testSetOptionTimeZone() { DateLayout layout = (DateLayout) createLayout(); layout.setOption("tImezOne", "+05:00"); assertEquals("+05:00", layout.getTimeZone()); } /** * Tests setDateFormat. */ public void testSetDateFormat() { DateLayout layout = (DateLayout) createLayout(); layout.setDateFormat("ABSOLUTE"); assertEquals("ABSOLUTE", layout.getDateFormat()); } /** * Tests setTimeZone. */ public void testSetTimeZone() { DateLayout layout = (DateLayout) createLayout(); layout.setTimeZone("+05:00"); assertEquals("+05:00", layout.getTimeZone()); } /** * Tests 2 parameter setDateFormat with null. */ public void testSetDateFormatNull() { DateLayout layout = (DateLayout) createLayout(); layout.setDateFormat((String) null, null); } /** * Tests 2 parameter setDateFormat with "NULL". */ public void testSetDateFormatNullString() { DateLayout layout = (DateLayout) createLayout(); layout.setDateFormat("NuLL", null); } /** * Tests 2 parameter setDateFormat with "RELATIVE". */ public void testSetDateFormatRelative() { DateLayout layout = (DateLayout) createLayout(); layout.setDateFormat("rElatIve", TimeZone.getDefault()); } /** * Tests 2 parameter setDateFormat with "ABSOLUTE". */ public void testSetDateFormatAbsolute() { DateLayout layout = (DateLayout) createLayout(); layout.setDateFormat("aBsolUte", TimeZone.getDefault()); } /** * Tests 2 parameter setDateFormat with "DATETIME". */ public void testSetDateFormatDateTime() { DateLayout layout = (DateLayout) createLayout(); layout.setDateFormat("dAte", TimeZone.getDefault()); } /** * Tests 2 parameter setDateFormat with "ISO8601". */ public void testSetDateFormatISO8601() { DateLayout layout = (DateLayout) createLayout(); layout.setDateFormat("iSo8601", TimeZone.getDefault()); } /** * Tests 2 parameter setDateFormat with "HH:mm:ss". */ public void testSetDateFormatSimple() { DateLayout layout = (DateLayout) createLayout(); layout.setDateFormat("HH:mm:ss", TimeZone.getDefault()); } /** * Tests activateOptions. */ public void testActivateOptions() { DateLayout layout = (DateLayout) createLayout(); layout.setDateFormat("HH:mm:ss"); layout.setTimeZone("+05:00"); layout.activateOptions(); } /** * Tests setDateFormat(DateFormat, TimeZone). */ public void testSetDateFormatWithFormat() { DateFormat format = new SimpleDateFormat("HH:mm"); DateLayout layout = (DateLayout) createLayout(); layout.setDateFormat(format, TimeZone.getDefault()); } /** * Tests IS08601DateFormat class. * @deprecated since ISO8601DateFormat is deprecated */ public void testISO8601Format() { DateFormat format = new ISO8601DateFormat(); Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(1970, 0, 1, 0, 0, 0); String actual = format.format(calendar.getTime()); assertEquals("1970-01-01 00:00:00,000", actual); } /** * Tests DateTimeDateFormat class. * @deprecated since DateTimeDateFormat is deprecated */ public void testDateTimeFormat() { DateFormat format = new DateTimeDateFormat(); Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(1970, 0, 1, 0, 0, 0); String actual = format.format(calendar.getTime()); SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm:ss,SSS"); String expected = df.format(calendar.getTime()); assertEquals(expected, actual); } /** * Concrete Layout class for tests. */ private static final class MockLayout extends DateLayout { /** * Create new instance of MockLayout. */ public MockLayout() { // // checks that protected fields are properly initialized assertNotNull(pos); assertNotNull(date); assertNull(dateFormat); } /** * @{inheritDoc} */ public String format(final LoggingEvent event) { return "Mock"; } /** * @{inheritDoc} */ public void activateOptions() { } /** * @{inheritDoc} */ public boolean ignoresThrowable() { return true; } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/EnhancedThrowableRendererTest.java0000644000175000017500000000307511751454673030456 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; import org.apache.log4j.spi.ThrowableRenderer; /** * Test for EnhancedThrowableRenderer. * */ public class EnhancedThrowableRendererTest extends TestCase { /** * Construct new instance. * @param name test name. */ public EnhancedThrowableRendererTest(final String name) { super(name); } /** * Render simple exception. */ public void testEnhancedRender() { ThrowableRenderer r = new EnhancedThrowableRenderer(); Exception ex = new Exception(); String[] strRep = r.doRender(ex); assertNotNull(strRep); assertTrue(strRep.length > 0); for(int i = 0; i < strRep.length; i++) { assertNotNull(strRep[i]); } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/stressCategory0000644000175000017500000007311511751454673024655 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ==================================================== function stressTest { java org.apache.log4j.StressCategory $* if [ "$?" = "0" ] then echo "Passed category stress test $index." index=$index+1 else echo "Failed stress test with arguments [$*]" exit fi } # ==================================================== declare -i index index=1 stressTest a b stressTest a a.b # stressTest a b c stressTest a b a.c stressTest a b b.c stressTest a a.b c stressTest a a.b a.c stressTest a a.b a.b.c # stressTest a b c d stressTest a b c a.d stressTest a b c b.d stressTest a b c c.d stressTest a b a.c d stressTest a b a.c a.d stressTest a b a.c b.d stressTest a b a.c a.c.d stressTest a b b.c d stressTest a b b.c a.d stressTest a b b.c b.d stressTest a b b.c b.c.d stressTest a a.b c d stressTest a a.b c a.d stressTest a a.b c a.b.d stressTest a a.b c c.d stressTest a a.b a.c d stressTest a a.b a.c a.d stressTest a a.b a.c a.b.d stressTest a a.b a.c a.c.d stressTest a a.b a.b.c d stressTest a a.b a.b.c a.d stressTest a a.b a.b.c a.b.d stressTest a a.b a.b.c a.b.c.d # stressTest a b c d e stressTest a b c d a.e stressTest a b c d b.e stressTest a b c d c.e stressTest a b c d d.e stressTest a b c a.d e stressTest a b c a.d a.e stressTest a b c a.d b.e stressTest a b c a.d c.e stressTest a b c a.d a.d.e stressTest a b c b.d e stressTest a b c b.d a.e stressTest a b c b.d b.e stressTest a b c b.d c.e stressTest a b c b.d b.d.e stressTest a b c c.d e stressTest a b c c.d a.e stressTest a b c c.d b.e stressTest a b c c.d c.e stressTest a b c c.d c.d.e stressTest a b a.c d e stressTest a b a.c d a.e stressTest a b a.c d b.e stressTest a b a.c d a.c.e stressTest a b a.c d d.e stressTest a b a.c a.d e stressTest a b a.c a.d a.e stressTest a b a.c a.d b.e stressTest a b a.c a.d a.c.e stressTest a b a.c a.d a.d.e stressTest a b a.c b.d e stressTest a b a.c b.d a.e stressTest a b a.c b.d b.e stressTest a b a.c b.d a.c.e stressTest a b a.c b.d b.d.e stressTest a b a.c a.c.d e stressTest a b a.c a.c.d a.e stressTest a b a.c a.c.d b.e stressTest a b a.c a.c.d a.c.e stressTest a b a.c a.c.d a.c.d.e stressTest a b b.c d e stressTest a b b.c d a.e stressTest a b b.c d b.e stressTest a b b.c d b.c.e stressTest a b b.c d d.e stressTest a b b.c a.d e stressTest a b b.c a.d a.e stressTest a b b.c a.d b.e stressTest a b b.c a.d b.c.e stressTest a b b.c a.d a.d.e stressTest a b b.c b.d e stressTest a b b.c b.d a.e stressTest a b b.c b.d b.e stressTest a b b.c b.d b.c.e stressTest a b b.c b.d b.d.e stressTest a b b.c b.c.d e stressTest a b b.c b.c.d a.e stressTest a b b.c b.c.d b.e stressTest a b b.c b.c.d b.c.e stressTest a b b.c b.c.d b.c.d.e stressTest a a.b c d e stressTest a a.b c d a.e stressTest a a.b c d a.b.e stressTest a a.b c d c.e stressTest a a.b c d d.e stressTest a a.b c a.d e stressTest a a.b c a.d a.e stressTest a a.b c a.d a.b.e stressTest a a.b c a.d c.e stressTest a a.b c a.d a.d.e stressTest a a.b c a.b.d e stressTest a a.b c a.b.d a.e stressTest a a.b c a.b.d a.b.e stressTest a a.b c a.b.d c.e stressTest a a.b c a.b.d a.b.d.e stressTest a a.b c c.d e stressTest a a.b c c.d a.e stressTest a a.b c c.d a.b.e stressTest a a.b c c.d c.e stressTest a a.b c c.d c.d.e stressTest a a.b a.c d e stressTest a a.b a.c d a.e stressTest a a.b a.c d a.b.e stressTest a a.b a.c d a.c.e stressTest a a.b a.c d d.e stressTest a a.b a.c a.d e stressTest a a.b a.c a.d a.e stressTest a a.b a.c a.d a.b.e stressTest a a.b a.c a.d a.c.e stressTest a a.b a.c a.d a.d.e stressTest a a.b a.c a.b.d e stressTest a a.b a.c a.b.d a.e stressTest a a.b a.c a.b.d a.b.e stressTest a a.b a.c a.b.d a.c.e stressTest a a.b a.c a.b.d a.b.d.e stressTest a a.b a.c a.c.d e stressTest a a.b a.c a.c.d a.e stressTest a a.b a.c a.c.d a.b.e stressTest a a.b a.c a.c.d a.c.e stressTest a a.b a.c a.c.d a.c.d.e stressTest a a.b a.b.c d e stressTest a a.b a.b.c d a.e stressTest a a.b a.b.c d a.b.e stressTest a a.b a.b.c d a.b.c.e stressTest a a.b a.b.c d d.e stressTest a a.b a.b.c a.d e stressTest a a.b a.b.c a.d a.e stressTest a a.b a.b.c a.d a.b.e stressTest a a.b a.b.c a.d a.b.c.e stressTest a a.b a.b.c a.d a.d.e stressTest a a.b a.b.c a.b.d e stressTest a a.b a.b.c a.b.d a.e stressTest a a.b a.b.c a.b.d a.b.e stressTest a a.b a.b.c a.b.d a.b.c.e stressTest a a.b a.b.c a.b.d a.b.d.e stressTest a a.b a.b.c a.b.c.d e stressTest a a.b a.b.c a.b.c.d a.e stressTest a a.b a.b.c a.b.c.d a.b.e stressTest a a.b a.b.c a.b.c.d a.b.c.e stressTest a a.b a.b.c a.b.c.d a.b.c.d.e # stressTest a b c d e f stressTest a b c d e a.f stressTest a b c d e b.f stressTest a b c d e c.f stressTest a b c d e d.f stressTest a b c d e e.f stressTest a b c d a.e f stressTest a b c d a.e a.f stressTest a b c d a.e b.f stressTest a b c d a.e c.f stressTest a b c d a.e d.f stressTest a b c d a.e a.e.f stressTest a b c d b.e f stressTest a b c d b.e a.f stressTest a b c d b.e b.f stressTest a b c d b.e c.f stressTest a b c d b.e d.f stressTest a b c d b.e b.e.f stressTest a b c d c.e f stressTest a b c d c.e a.f stressTest a b c d c.e b.f stressTest a b c d c.e c.f stressTest a b c d c.e d.f stressTest a b c d c.e c.e.f stressTest a b c d d.e f stressTest a b c d d.e a.f stressTest a b c d d.e b.f stressTest a b c d d.e c.f stressTest a b c d d.e d.f stressTest a b c d d.e d.e.f stressTest a b c a.d e f stressTest a b c a.d e a.f stressTest a b c a.d e b.f stressTest a b c a.d e c.f stressTest a b c a.d e a.d.f stressTest a b c a.d e e.f stressTest a b c a.d a.e f stressTest a b c a.d a.e a.f stressTest a b c a.d a.e b.f stressTest a b c a.d a.e c.f stressTest a b c a.d a.e a.d.f stressTest a b c a.d a.e a.e.f stressTest a b c a.d b.e f stressTest a b c a.d b.e a.f stressTest a b c a.d b.e b.f stressTest a b c a.d b.e c.f stressTest a b c a.d b.e a.d.f stressTest a b c a.d b.e b.e.f stressTest a b c a.d c.e f stressTest a b c a.d c.e a.f stressTest a b c a.d c.e b.f stressTest a b c a.d c.e c.f stressTest a b c a.d c.e a.d.f stressTest a b c a.d c.e c.e.f stressTest a b c a.d a.d.e f stressTest a b c a.d a.d.e a.f stressTest a b c a.d a.d.e b.f stressTest a b c a.d a.d.e c.f stressTest a b c a.d a.d.e a.d.f stressTest a b c a.d a.d.e a.d.e.f stressTest a b c b.d e f stressTest a b c b.d e a.f stressTest a b c b.d e b.f stressTest a b c b.d e c.f stressTest a b c b.d e b.d.f stressTest a b c b.d e e.f stressTest a b c b.d a.e f stressTest a b c b.d a.e a.f stressTest a b c b.d a.e b.f stressTest a b c b.d a.e c.f stressTest a b c b.d a.e b.d.f stressTest a b c b.d a.e a.e.f stressTest a b c b.d b.e f stressTest a b c b.d b.e a.f stressTest a b c b.d b.e b.f stressTest a b c b.d b.e c.f stressTest a b c b.d b.e b.d.f stressTest a b c b.d b.e b.e.f stressTest a b c b.d c.e f stressTest a b c b.d c.e a.f stressTest a b c b.d c.e b.f stressTest a b c b.d c.e c.f stressTest a b c b.d c.e b.d.f stressTest a b c b.d c.e c.e.f stressTest a b c b.d b.d.e f stressTest a b c b.d b.d.e a.f stressTest a b c b.d b.d.e b.f stressTest a b c b.d b.d.e c.f stressTest a b c b.d b.d.e b.d.f stressTest a b c b.d b.d.e b.d.e.f stressTest a b c c.d e f stressTest a b c c.d e a.f stressTest a b c c.d e b.f stressTest a b c c.d e c.f stressTest a b c c.d e c.d.f stressTest a b c c.d e e.f stressTest a b c c.d a.e f stressTest a b c c.d a.e a.f stressTest a b c c.d a.e b.f stressTest a b c c.d a.e c.f stressTest a b c c.d a.e c.d.f stressTest a b c c.d a.e a.e.f stressTest a b c c.d b.e f stressTest a b c c.d b.e a.f stressTest a b c c.d b.e b.f stressTest a b c c.d b.e c.f stressTest a b c c.d b.e c.d.f stressTest a b c c.d b.e b.e.f stressTest a b c c.d c.e f stressTest a b c c.d c.e a.f stressTest a b c c.d c.e b.f stressTest a b c c.d c.e c.f stressTest a b c c.d c.e c.d.f stressTest a b c c.d c.e c.e.f stressTest a b c c.d c.d.e f stressTest a b c c.d c.d.e a.f stressTest a b c c.d c.d.e b.f stressTest a b c c.d c.d.e c.f stressTest a b c c.d c.d.e c.d.f stressTest a b c c.d c.d.e c.d.e.f stressTest a b a.c d e f stressTest a b a.c d e a.f stressTest a b a.c d e b.f stressTest a b a.c d e a.c.f stressTest a b a.c d e d.f stressTest a b a.c d e e.f stressTest a b a.c d a.e f stressTest a b a.c d a.e a.f stressTest a b a.c d a.e b.f stressTest a b a.c d a.e a.c.f stressTest a b a.c d a.e d.f stressTest a b a.c d a.e a.e.f stressTest a b a.c d b.e f stressTest a b a.c d b.e a.f stressTest a b a.c d b.e b.f stressTest a b a.c d b.e a.c.f stressTest a b a.c d b.e d.f stressTest a b a.c d b.e b.e.f stressTest a b a.c d a.c.e f stressTest a b a.c d a.c.e a.f stressTest a b a.c d a.c.e b.f stressTest a b a.c d a.c.e a.c.f stressTest a b a.c d a.c.e d.f stressTest a b a.c d a.c.e a.c.e.f stressTest a b a.c d d.e f stressTest a b a.c d d.e a.f stressTest a b a.c d d.e b.f stressTest a b a.c d d.e a.c.f stressTest a b a.c d d.e d.f stressTest a b a.c d d.e d.e.f stressTest a b a.c a.d e f stressTest a b a.c a.d e a.f stressTest a b a.c a.d e b.f stressTest a b a.c a.d e a.c.f stressTest a b a.c a.d e a.d.f stressTest a b a.c a.d e e.f stressTest a b a.c a.d a.e f stressTest a b a.c a.d a.e a.f stressTest a b a.c a.d a.e b.f stressTest a b a.c a.d a.e a.c.f stressTest a b a.c a.d a.e a.d.f stressTest a b a.c a.d a.e a.e.f stressTest a b a.c a.d b.e f stressTest a b a.c a.d b.e a.f stressTest a b a.c a.d b.e b.f stressTest a b a.c a.d b.e a.c.f stressTest a b a.c a.d b.e a.d.f stressTest a b a.c a.d b.e b.e.f stressTest a b a.c a.d a.c.e f stressTest a b a.c a.d a.c.e a.f stressTest a b a.c a.d a.c.e b.f stressTest a b a.c a.d a.c.e a.c.f stressTest a b a.c a.d a.c.e a.d.f stressTest a b a.c a.d a.c.e a.c.e.f stressTest a b a.c a.d a.d.e f stressTest a b a.c a.d a.d.e a.f stressTest a b a.c a.d a.d.e b.f stressTest a b a.c a.d a.d.e a.c.f stressTest a b a.c a.d a.d.e a.d.f stressTest a b a.c a.d a.d.e a.d.e.f stressTest a b a.c b.d e f stressTest a b a.c b.d e a.f stressTest a b a.c b.d e b.f stressTest a b a.c b.d e a.c.f stressTest a b a.c b.d e b.d.f stressTest a b a.c b.d e e.f stressTest a b a.c b.d a.e f stressTest a b a.c b.d a.e a.f stressTest a b a.c b.d a.e b.f stressTest a b a.c b.d a.e a.c.f stressTest a b a.c b.d a.e b.d.f stressTest a b a.c b.d a.e a.e.f stressTest a b a.c b.d b.e f stressTest a b a.c b.d b.e a.f stressTest a b a.c b.d b.e b.f stressTest a b a.c b.d b.e a.c.f stressTest a b a.c b.d b.e b.d.f stressTest a b a.c b.d b.e b.e.f stressTest a b a.c b.d a.c.e f stressTest a b a.c b.d a.c.e a.f stressTest a b a.c b.d a.c.e b.f stressTest a b a.c b.d a.c.e a.c.f stressTest a b a.c b.d a.c.e b.d.f stressTest a b a.c b.d a.c.e a.c.e.f stressTest a b a.c b.d b.d.e f stressTest a b a.c b.d b.d.e a.f stressTest a b a.c b.d b.d.e b.f stressTest a b a.c b.d b.d.e a.c.f stressTest a b a.c b.d b.d.e b.d.f stressTest a b a.c b.d b.d.e b.d.e.f stressTest a b a.c a.c.d e f stressTest a b a.c a.c.d e a.f stressTest a b a.c a.c.d e b.f stressTest a b a.c a.c.d e a.c.f stressTest a b a.c a.c.d e a.c.d.f stressTest a b a.c a.c.d e e.f stressTest a b a.c a.c.d a.e f stressTest a b a.c a.c.d a.e a.f stressTest a b a.c a.c.d a.e b.f stressTest a b a.c a.c.d a.e a.c.f stressTest a b a.c a.c.d a.e a.c.d.f stressTest a b a.c a.c.d a.e a.e.f stressTest a b a.c a.c.d b.e f stressTest a b a.c a.c.d b.e a.f stressTest a b a.c a.c.d b.e b.f stressTest a b a.c a.c.d b.e a.c.f stressTest a b a.c a.c.d b.e a.c.d.f stressTest a b a.c a.c.d b.e b.e.f stressTest a b a.c a.c.d a.c.e f stressTest a b a.c a.c.d a.c.e a.f stressTest a b a.c a.c.d a.c.e b.f stressTest a b a.c a.c.d a.c.e a.c.f stressTest a b a.c a.c.d a.c.e a.c.d.f stressTest a b a.c a.c.d a.c.e a.c.e.f stressTest a b a.c a.c.d a.c.d.e f stressTest a b a.c a.c.d a.c.d.e a.f stressTest a b a.c a.c.d a.c.d.e b.f stressTest a b a.c a.c.d a.c.d.e a.c.f stressTest a b a.c a.c.d a.c.d.e a.c.d.f stressTest a b a.c a.c.d a.c.d.e a.c.d.e.f stressTest a b b.c d e f stressTest a b b.c d e a.f stressTest a b b.c d e b.f stressTest a b b.c d e b.c.f stressTest a b b.c d e d.f stressTest a b b.c d e e.f stressTest a b b.c d a.e f stressTest a b b.c d a.e a.f stressTest a b b.c d a.e b.f stressTest a b b.c d a.e b.c.f stressTest a b b.c d a.e d.f stressTest a b b.c d a.e a.e.f stressTest a b b.c d b.e f stressTest a b b.c d b.e a.f stressTest a b b.c d b.e b.f stressTest a b b.c d b.e b.c.f stressTest a b b.c d b.e d.f stressTest a b b.c d b.e b.e.f stressTest a b b.c d b.c.e f stressTest a b b.c d b.c.e a.f stressTest a b b.c d b.c.e b.f stressTest a b b.c d b.c.e b.c.f stressTest a b b.c d b.c.e d.f stressTest a b b.c d b.c.e b.c.e.f stressTest a b b.c d d.e f stressTest a b b.c d d.e a.f stressTest a b b.c d d.e b.f stressTest a b b.c d d.e b.c.f stressTest a b b.c d d.e d.f stressTest a b b.c d d.e d.e.f stressTest a b b.c a.d e f stressTest a b b.c a.d e a.f stressTest a b b.c a.d e b.f stressTest a b b.c a.d e b.c.f stressTest a b b.c a.d e a.d.f stressTest a b b.c a.d e e.f stressTest a b b.c a.d a.e f stressTest a b b.c a.d a.e a.f stressTest a b b.c a.d a.e b.f stressTest a b b.c a.d a.e b.c.f stressTest a b b.c a.d a.e a.d.f stressTest a b b.c a.d a.e a.e.f stressTest a b b.c a.d b.e f stressTest a b b.c a.d b.e a.f stressTest a b b.c a.d b.e b.f stressTest a b b.c a.d b.e b.c.f stressTest a b b.c a.d b.e a.d.f stressTest a b b.c a.d b.e b.e.f stressTest a b b.c a.d b.c.e f stressTest a b b.c a.d b.c.e a.f stressTest a b b.c a.d b.c.e b.f stressTest a b b.c a.d b.c.e b.c.f stressTest a b b.c a.d b.c.e a.d.f stressTest a b b.c a.d b.c.e b.c.e.f stressTest a b b.c a.d a.d.e f stressTest a b b.c a.d a.d.e a.f stressTest a b b.c a.d a.d.e b.f stressTest a b b.c a.d a.d.e b.c.f stressTest a b b.c a.d a.d.e a.d.f stressTest a b b.c a.d a.d.e a.d.e.f stressTest a b b.c b.d e f stressTest a b b.c b.d e a.f stressTest a b b.c b.d e b.f stressTest a b b.c b.d e b.c.f stressTest a b b.c b.d e b.d.f stressTest a b b.c b.d e e.f stressTest a b b.c b.d a.e f stressTest a b b.c b.d a.e a.f stressTest a b b.c b.d a.e b.f stressTest a b b.c b.d a.e b.c.f stressTest a b b.c b.d a.e b.d.f stressTest a b b.c b.d a.e a.e.f stressTest a b b.c b.d b.e f stressTest a b b.c b.d b.e a.f stressTest a b b.c b.d b.e b.f stressTest a b b.c b.d b.e b.c.f stressTest a b b.c b.d b.e b.d.f stressTest a b b.c b.d b.e b.e.f stressTest a b b.c b.d b.c.e f stressTest a b b.c b.d b.c.e a.f stressTest a b b.c b.d b.c.e b.f stressTest a b b.c b.d b.c.e b.c.f stressTest a b b.c b.d b.c.e b.d.f stressTest a b b.c b.d b.c.e b.c.e.f stressTest a b b.c b.d b.d.e f stressTest a b b.c b.d b.d.e a.f stressTest a b b.c b.d b.d.e b.f stressTest a b b.c b.d b.d.e b.c.f stressTest a b b.c b.d b.d.e b.d.f stressTest a b b.c b.d b.d.e b.d.e.f stressTest a b b.c b.c.d e f stressTest a b b.c b.c.d e a.f stressTest a b b.c b.c.d e b.f stressTest a b b.c b.c.d e b.c.f stressTest a b b.c b.c.d e b.c.d.f stressTest a b b.c b.c.d e e.f stressTest a b b.c b.c.d a.e f stressTest a b b.c b.c.d a.e a.f stressTest a b b.c b.c.d a.e b.f stressTest a b b.c b.c.d a.e b.c.f stressTest a b b.c b.c.d a.e b.c.d.f stressTest a b b.c b.c.d a.e a.e.f stressTest a b b.c b.c.d b.e f stressTest a b b.c b.c.d b.e a.f stressTest a b b.c b.c.d b.e b.f stressTest a b b.c b.c.d b.e b.c.f stressTest a b b.c b.c.d b.e b.c.d.f stressTest a b b.c b.c.d b.e b.e.f stressTest a b b.c b.c.d b.c.e f stressTest a b b.c b.c.d b.c.e a.f stressTest a b b.c b.c.d b.c.e b.f stressTest a b b.c b.c.d b.c.e b.c.f stressTest a b b.c b.c.d b.c.e b.c.d.f stressTest a b b.c b.c.d b.c.e b.c.e.f stressTest a b b.c b.c.d b.c.d.e f stressTest a b b.c b.c.d b.c.d.e a.f stressTest a b b.c b.c.d b.c.d.e b.f stressTest a b b.c b.c.d b.c.d.e b.c.f stressTest a b b.c b.c.d b.c.d.e b.c.d.f stressTest a b b.c b.c.d b.c.d.e b.c.d.e.f stressTest a a.b c d e f stressTest a a.b c d e a.f stressTest a a.b c d e a.b.f stressTest a a.b c d e c.f stressTest a a.b c d e d.f stressTest a a.b c d e e.f stressTest a a.b c d a.e f stressTest a a.b c d a.e a.f stressTest a a.b c d a.e a.b.f stressTest a a.b c d a.e c.f stressTest a a.b c d a.e d.f stressTest a a.b c d a.e a.e.f stressTest a a.b c d a.b.e f stressTest a a.b c d a.b.e a.f stressTest a a.b c d a.b.e a.b.f stressTest a a.b c d a.b.e c.f stressTest a a.b c d a.b.e d.f stressTest a a.b c d a.b.e a.b.e.f stressTest a a.b c d c.e f stressTest a a.b c d c.e a.f stressTest a a.b c d c.e a.b.f stressTest a a.b c d c.e c.f stressTest a a.b c d c.e d.f stressTest a a.b c d c.e c.e.f stressTest a a.b c d d.e f stressTest a a.b c d d.e a.f stressTest a a.b c d d.e a.b.f stressTest a a.b c d d.e c.f stressTest a a.b c d d.e d.f stressTest a a.b c d d.e d.e.f stressTest a a.b c a.d e f stressTest a a.b c a.d e a.f stressTest a a.b c a.d e a.b.f stressTest a a.b c a.d e c.f stressTest a a.b c a.d e a.d.f stressTest a a.b c a.d e e.f stressTest a a.b c a.d a.e f stressTest a a.b c a.d a.e a.f stressTest a a.b c a.d a.e a.b.f stressTest a a.b c a.d a.e c.f stressTest a a.b c a.d a.e a.d.f stressTest a a.b c a.d a.e a.e.f stressTest a a.b c a.d a.b.e f stressTest a a.b c a.d a.b.e a.f stressTest a a.b c a.d a.b.e a.b.f stressTest a a.b c a.d a.b.e c.f stressTest a a.b c a.d a.b.e a.d.f stressTest a a.b c a.d a.b.e a.b.e.f stressTest a a.b c a.d c.e f stressTest a a.b c a.d c.e a.f stressTest a a.b c a.d c.e a.b.f stressTest a a.b c a.d c.e c.f stressTest a a.b c a.d c.e a.d.f stressTest a a.b c a.d c.e c.e.f stressTest a a.b c a.d a.d.e f stressTest a a.b c a.d a.d.e a.f stressTest a a.b c a.d a.d.e a.b.f stressTest a a.b c a.d a.d.e c.f stressTest a a.b c a.d a.d.e a.d.f stressTest a a.b c a.d a.d.e a.d.e.f stressTest a a.b c a.b.d e f stressTest a a.b c a.b.d e a.f stressTest a a.b c a.b.d e a.b.f stressTest a a.b c a.b.d e c.f stressTest a a.b c a.b.d e a.b.d.f stressTest a a.b c a.b.d e e.f stressTest a a.b c a.b.d a.e f stressTest a a.b c a.b.d a.e a.f stressTest a a.b c a.b.d a.e a.b.f stressTest a a.b c a.b.d a.e c.f stressTest a a.b c a.b.d a.e a.b.d.f stressTest a a.b c a.b.d a.e a.e.f stressTest a a.b c a.b.d a.b.e f stressTest a a.b c a.b.d a.b.e a.f stressTest a a.b c a.b.d a.b.e a.b.f stressTest a a.b c a.b.d a.b.e c.f stressTest a a.b c a.b.d a.b.e a.b.d.f stressTest a a.b c a.b.d a.b.e a.b.e.f stressTest a a.b c a.b.d c.e f stressTest a a.b c a.b.d c.e a.f stressTest a a.b c a.b.d c.e a.b.f stressTest a a.b c a.b.d c.e c.f stressTest a a.b c a.b.d c.e a.b.d.f stressTest a a.b c a.b.d c.e c.e.f stressTest a a.b c a.b.d a.b.d.e f stressTest a a.b c a.b.d a.b.d.e a.f stressTest a a.b c a.b.d a.b.d.e a.b.f stressTest a a.b c a.b.d a.b.d.e c.f stressTest a a.b c a.b.d a.b.d.e a.b.d.f stressTest a a.b c a.b.d a.b.d.e a.b.d.e.f stressTest a a.b c c.d e f stressTest a a.b c c.d e a.f stressTest a a.b c c.d e a.b.f stressTest a a.b c c.d e c.f stressTest a a.b c c.d e c.d.f stressTest a a.b c c.d e e.f stressTest a a.b c c.d a.e f stressTest a a.b c c.d a.e a.f stressTest a a.b c c.d a.e a.b.f stressTest a a.b c c.d a.e c.f stressTest a a.b c c.d a.e c.d.f stressTest a a.b c c.d a.e a.e.f stressTest a a.b c c.d a.b.e f stressTest a a.b c c.d a.b.e a.f stressTest a a.b c c.d a.b.e a.b.f stressTest a a.b c c.d a.b.e c.f stressTest a a.b c c.d a.b.e c.d.f stressTest a a.b c c.d a.b.e a.b.e.f stressTest a a.b c c.d c.e f stressTest a a.b c c.d c.e a.f stressTest a a.b c c.d c.e a.b.f stressTest a a.b c c.d c.e c.f stressTest a a.b c c.d c.e c.d.f stressTest a a.b c c.d c.e c.e.f stressTest a a.b c c.d c.d.e f stressTest a a.b c c.d c.d.e a.f stressTest a a.b c c.d c.d.e a.b.f stressTest a a.b c c.d c.d.e c.f stressTest a a.b c c.d c.d.e c.d.f stressTest a a.b c c.d c.d.e c.d.e.f stressTest a a.b a.c d e f stressTest a a.b a.c d e a.f stressTest a a.b a.c d e a.b.f stressTest a a.b a.c d e a.c.f stressTest a a.b a.c d e d.f stressTest a a.b a.c d e e.f stressTest a a.b a.c d a.e f stressTest a a.b a.c d a.e a.f stressTest a a.b a.c d a.e a.b.f stressTest a a.b a.c d a.e a.c.f stressTest a a.b a.c d a.e d.f stressTest a a.b a.c d a.e a.e.f stressTest a a.b a.c d a.b.e f stressTest a a.b a.c d a.b.e a.f stressTest a a.b a.c d a.b.e a.b.f stressTest a a.b a.c d a.b.e a.c.f stressTest a a.b a.c d a.b.e d.f stressTest a a.b a.c d a.b.e a.b.e.f stressTest a a.b a.c d a.c.e f stressTest a a.b a.c d a.c.e a.f stressTest a a.b a.c d a.c.e a.b.f stressTest a a.b a.c d a.c.e a.c.f stressTest a a.b a.c d a.c.e d.f stressTest a a.b a.c d a.c.e a.c.e.f stressTest a a.b a.c d d.e f stressTest a a.b a.c d d.e a.f stressTest a a.b a.c d d.e a.b.f stressTest a a.b a.c d d.e a.c.f stressTest a a.b a.c d d.e d.f stressTest a a.b a.c d d.e d.e.f stressTest a a.b a.c a.d e f stressTest a a.b a.c a.d e a.f stressTest a a.b a.c a.d e a.b.f stressTest a a.b a.c a.d e a.c.f stressTest a a.b a.c a.d e a.d.f stressTest a a.b a.c a.d e e.f stressTest a a.b a.c a.d a.e f stressTest a a.b a.c a.d a.e a.f stressTest a a.b a.c a.d a.e a.b.f stressTest a a.b a.c a.d a.e a.c.f stressTest a a.b a.c a.d a.e a.d.f stressTest a a.b a.c a.d a.e a.e.f stressTest a a.b a.c a.d a.b.e f stressTest a a.b a.c a.d a.b.e a.f stressTest a a.b a.c a.d a.b.e a.b.f stressTest a a.b a.c a.d a.b.e a.c.f stressTest a a.b a.c a.d a.b.e a.d.f stressTest a a.b a.c a.d a.b.e a.b.e.f stressTest a a.b a.c a.d a.c.e f stressTest a a.b a.c a.d a.c.e a.f stressTest a a.b a.c a.d a.c.e a.b.f stressTest a a.b a.c a.d a.c.e a.c.f stressTest a a.b a.c a.d a.c.e a.d.f stressTest a a.b a.c a.d a.c.e a.c.e.f stressTest a a.b a.c a.d a.d.e f stressTest a a.b a.c a.d a.d.e a.f stressTest a a.b a.c a.d a.d.e a.b.f stressTest a a.b a.c a.d a.d.e a.c.f stressTest a a.b a.c a.d a.d.e a.d.f stressTest a a.b a.c a.d a.d.e a.d.e.f stressTest a a.b a.c a.b.d e f stressTest a a.b a.c a.b.d e a.f stressTest a a.b a.c a.b.d e a.b.f stressTest a a.b a.c a.b.d e a.c.f stressTest a a.b a.c a.b.d e a.b.d.f stressTest a a.b a.c a.b.d e e.f stressTest a a.b a.c a.b.d a.e f stressTest a a.b a.c a.b.d a.e a.f stressTest a a.b a.c a.b.d a.e a.b.f stressTest a a.b a.c a.b.d a.e a.c.f stressTest a a.b a.c a.b.d a.e a.b.d.f stressTest a a.b a.c a.b.d a.e a.e.f stressTest a a.b a.c a.b.d a.b.e f stressTest a a.b a.c a.b.d a.b.e a.f stressTest a a.b a.c a.b.d a.b.e a.b.f stressTest a a.b a.c a.b.d a.b.e a.c.f stressTest a a.b a.c a.b.d a.b.e a.b.d.f stressTest a a.b a.c a.b.d a.b.e a.b.e.f stressTest a a.b a.c a.b.d a.c.e f stressTest a a.b a.c a.b.d a.c.e a.f stressTest a a.b a.c a.b.d a.c.e a.b.f stressTest a a.b a.c a.b.d a.c.e a.c.f stressTest a a.b a.c a.b.d a.c.e a.b.d.f stressTest a a.b a.c a.b.d a.c.e a.c.e.f stressTest a a.b a.c a.b.d a.b.d.e f stressTest a a.b a.c a.b.d a.b.d.e a.f stressTest a a.b a.c a.b.d a.b.d.e a.b.f stressTest a a.b a.c a.b.d a.b.d.e a.c.f stressTest a a.b a.c a.b.d a.b.d.e a.b.d.f stressTest a a.b a.c a.b.d a.b.d.e a.b.d.e.f stressTest a a.b a.c a.c.d e f stressTest a a.b a.c a.c.d e a.f stressTest a a.b a.c a.c.d e a.b.f stressTest a a.b a.c a.c.d e a.c.f stressTest a a.b a.c a.c.d e a.c.d.f stressTest a a.b a.c a.c.d e e.f stressTest a a.b a.c a.c.d a.e f stressTest a a.b a.c a.c.d a.e a.f stressTest a a.b a.c a.c.d a.e a.b.f stressTest a a.b a.c a.c.d a.e a.c.f stressTest a a.b a.c a.c.d a.e a.c.d.f stressTest a a.b a.c a.c.d a.e a.e.f stressTest a a.b a.c a.c.d a.b.e f stressTest a a.b a.c a.c.d a.b.e a.f stressTest a a.b a.c a.c.d a.b.e a.b.f stressTest a a.b a.c a.c.d a.b.e a.c.f stressTest a a.b a.c a.c.d a.b.e a.c.d.f stressTest a a.b a.c a.c.d a.b.e a.b.e.f stressTest a a.b a.c a.c.d a.c.e f stressTest a a.b a.c a.c.d a.c.e a.f stressTest a a.b a.c a.c.d a.c.e a.b.f stressTest a a.b a.c a.c.d a.c.e a.c.f stressTest a a.b a.c a.c.d a.c.e a.c.d.f stressTest a a.b a.c a.c.d a.c.e a.c.e.f stressTest a a.b a.c a.c.d a.c.d.e f stressTest a a.b a.c a.c.d a.c.d.e a.f stressTest a a.b a.c a.c.d a.c.d.e a.b.f stressTest a a.b a.c a.c.d a.c.d.e a.c.f stressTest a a.b a.c a.c.d a.c.d.e a.c.d.f stressTest a a.b a.c a.c.d a.c.d.e a.c.d.e.f stressTest a a.b a.b.c d e f stressTest a a.b a.b.c d e a.f stressTest a a.b a.b.c d e a.b.f stressTest a a.b a.b.c d e a.b.c.f stressTest a a.b a.b.c d e d.f stressTest a a.b a.b.c d e e.f stressTest a a.b a.b.c d a.e f stressTest a a.b a.b.c d a.e a.f stressTest a a.b a.b.c d a.e a.b.f stressTest a a.b a.b.c d a.e a.b.c.f stressTest a a.b a.b.c d a.e d.f stressTest a a.b a.b.c d a.e a.e.f stressTest a a.b a.b.c d a.b.e f stressTest a a.b a.b.c d a.b.e a.f stressTest a a.b a.b.c d a.b.e a.b.f stressTest a a.b a.b.c d a.b.e a.b.c.f stressTest a a.b a.b.c d a.b.e d.f stressTest a a.b a.b.c d a.b.e a.b.e.f stressTest a a.b a.b.c d a.b.c.e f stressTest a a.b a.b.c d a.b.c.e a.f stressTest a a.b a.b.c d a.b.c.e a.b.f stressTest a a.b a.b.c d a.b.c.e a.b.c.f stressTest a a.b a.b.c d a.b.c.e d.f stressTest a a.b a.b.c d a.b.c.e a.b.c.e.f stressTest a a.b a.b.c d d.e f stressTest a a.b a.b.c d d.e a.f stressTest a a.b a.b.c d d.e a.b.f stressTest a a.b a.b.c d d.e a.b.c.f stressTest a a.b a.b.c d d.e d.f stressTest a a.b a.b.c d d.e d.e.f stressTest a a.b a.b.c a.d e f stressTest a a.b a.b.c a.d e a.f stressTest a a.b a.b.c a.d e a.b.f stressTest a a.b a.b.c a.d e a.b.c.f stressTest a a.b a.b.c a.d e a.d.f stressTest a a.b a.b.c a.d e e.f stressTest a a.b a.b.c a.d a.e f stressTest a a.b a.b.c a.d a.e a.f stressTest a a.b a.b.c a.d a.e a.b.f stressTest a a.b a.b.c a.d a.e a.b.c.f stressTest a a.b a.b.c a.d a.e a.d.f stressTest a a.b a.b.c a.d a.e a.e.f stressTest a a.b a.b.c a.d a.b.e f stressTest a a.b a.b.c a.d a.b.e a.f stressTest a a.b a.b.c a.d a.b.e a.b.f stressTest a a.b a.b.c a.d a.b.e a.b.c.f stressTest a a.b a.b.c a.d a.b.e a.d.f stressTest a a.b a.b.c a.d a.b.e a.b.e.f stressTest a a.b a.b.c a.d a.b.c.e f stressTest a a.b a.b.c a.d a.b.c.e a.f stressTest a a.b a.b.c a.d a.b.c.e a.b.f stressTest a a.b a.b.c a.d a.b.c.e a.b.c.f stressTest a a.b a.b.c a.d a.b.c.e a.d.f stressTest a a.b a.b.c a.d a.b.c.e a.b.c.e.f stressTest a a.b a.b.c a.d a.d.e f stressTest a a.b a.b.c a.d a.d.e a.f stressTest a a.b a.b.c a.d a.d.e a.b.f stressTest a a.b a.b.c a.d a.d.e a.b.c.f stressTest a a.b a.b.c a.d a.d.e a.d.f stressTest a a.b a.b.c a.d a.d.e a.d.e.f stressTest a a.b a.b.c a.b.d e f stressTest a a.b a.b.c a.b.d e a.f stressTest a a.b a.b.c a.b.d e a.b.f stressTest a a.b a.b.c a.b.d e a.b.c.f stressTest a a.b a.b.c a.b.d e a.b.d.f stressTest a a.b a.b.c a.b.d e e.f stressTest a a.b a.b.c a.b.d a.e f stressTest a a.b a.b.c a.b.d a.e a.f stressTest a a.b a.b.c a.b.d a.e a.b.f stressTest a a.b a.b.c a.b.d a.e a.b.c.f stressTest a a.b a.b.c a.b.d a.e a.b.d.f stressTest a a.b a.b.c a.b.d a.e a.e.f stressTest a a.b a.b.c a.b.d a.b.e f stressTest a a.b a.b.c a.b.d a.b.e a.f stressTest a a.b a.b.c a.b.d a.b.e a.b.f stressTest a a.b a.b.c a.b.d a.b.e a.b.c.f stressTest a a.b a.b.c a.b.d a.b.e a.b.d.f stressTest a a.b a.b.c a.b.d a.b.e a.b.e.f stressTest a a.b a.b.c a.b.d a.b.c.e f stressTest a a.b a.b.c a.b.d a.b.c.e a.f stressTest a a.b a.b.c a.b.d a.b.c.e a.b.f stressTest a a.b a.b.c a.b.d a.b.c.e a.b.c.f stressTest a a.b a.b.c a.b.d a.b.c.e a.b.d.f stressTest a a.b a.b.c a.b.d a.b.c.e a.b.c.e.f stressTest a a.b a.b.c a.b.d a.b.d.e f stressTest a a.b a.b.c a.b.d a.b.d.e a.f stressTest a a.b a.b.c a.b.d a.b.d.e a.b.f stressTest a a.b a.b.c a.b.d a.b.d.e a.b.c.f stressTest a a.b a.b.c a.b.d a.b.d.e a.b.d.f stressTest a a.b a.b.c a.b.d a.b.d.e a.b.d.e.f stressTest a a.b a.b.c a.b.c.d e f stressTest a a.b a.b.c a.b.c.d e a.f stressTest a a.b a.b.c a.b.c.d e a.b.f stressTest a a.b a.b.c a.b.c.d e a.b.c.f stressTest a a.b a.b.c a.b.c.d e a.b.c.d.f stressTest a a.b a.b.c a.b.c.d e e.f stressTest a a.b a.b.c a.b.c.d a.e f stressTest a a.b a.b.c a.b.c.d a.e a.f stressTest a a.b a.b.c a.b.c.d a.e a.b.f stressTest a a.b a.b.c a.b.c.d a.e a.b.c.f stressTest a a.b a.b.c a.b.c.d a.e a.b.c.d.f stressTest a a.b a.b.c a.b.c.d a.e a.e.f stressTest a a.b a.b.c a.b.c.d a.b.e f stressTest a a.b a.b.c a.b.c.d a.b.e a.f stressTest a a.b a.b.c a.b.c.d a.b.e a.b.f stressTest a a.b a.b.c a.b.c.d a.b.e a.b.c.f stressTest a a.b a.b.c a.b.c.d a.b.e a.b.c.d.f stressTest a a.b a.b.c a.b.c.d a.b.e a.b.e.f stressTest a a.b a.b.c a.b.c.d a.b.c.e f stressTest a a.b a.b.c a.b.c.d a.b.c.e a.f stressTest a a.b a.b.c a.b.c.d a.b.c.e a.b.f stressTest a a.b a.b.c a.b.c.d a.b.c.e a.b.c.f stressTest a a.b a.b.c a.b.c.d a.b.c.e a.b.c.d.f stressTest a a.b a.b.c a.b.c.d a.b.c.e a.b.c.e.f stressTest a a.b a.b.c a.b.c.d a.b.c.d.e f stressTest a a.b a.b.c a.b.c.d a.b.c.d.e a.f stressTest a a.b a.b.c a.b.c.d a.b.c.d.e a.b.f stressTest a a.b a.b.c a.b.c.d a.b.c.d.e a.b.c.f stressTest a a.b a.b.c a.b.c.d a.b.c.d.e a.b.c.d.f stressTest a a.b a.b.c a.b.c.d a.b.c.d.e a.b.c.d.e.f # stressTest a a.b a.b.c1 a.b.c1.d1 a.b.c1.d2 a.b.c1.d3 a.b.c2 stressTest a a.b a.b.c a.b.c.d a.b.c.d.e a.b.c.d.e.f a.b.c.d.e.f.g apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/customLogger/0000755000175000017500000000000012126647422024345 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/customLogger/XLoggerTestCase.java0000644000175000017500000000453111751454671030223 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.customLogger; import org.apache.log4j.xml.DOMConfigurator; import org.apache.log4j.util.*; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; /** Tests handling of custom loggers. @author Ceki Gülcü */ public class XLoggerTestCase extends TestCase { static String FILTERED = "output/filtered"; static XLogger logger = (XLogger) XLogger.getLogger(XLoggerTestCase.class); public XLoggerTestCase(String name){ super(name); } public void tearDown() { logger.getLoggerRepository().resetConfiguration(); } public void test1() throws Exception { common(1); } public void test2() throws Exception { common(2); } void common(int number) throws Exception { DOMConfigurator.configure("input/xml/customLogger"+number+".xml"); int i = -1; logger.trace("Message " + ++i); logger.debug("Message " + ++i); logger.warn ("Message " + ++i); logger.error("Message " + ++i); logger.fatal("Message " + ++i); Exception e = new Exception("Just testing"); logger.debug("Message " + ++i, e); Transformer.transform( "output/temp", FILTERED, new Filter[] { new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); assertTrue(Compare.compare(FILTERED, "witness/customLogger."+number)); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new XLoggerTestCase("test1")); suite.addTest(new XLoggerTestCase("test2")); return suite; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/customLogger/XLogger.java0000644000175000017500000000777411751454671026603 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.customLogger; import org.apache.log4j.*; import org.apache.log4j.spi.OptionHandler; import org.apache.log4j.spi.LoggerFactory; import org.apache.log4j.xml.XLevel; /** A simple example showing Logger sub-classing. It shows the minimum steps necessary to implement one's {@link LoggerFactory}. Note that sub-classes follow the hierarchy even if its loggers belong to different classes. */ public class XLogger extends Logger implements OptionHandler { // It's usually a good idea to add a dot suffix to the fully // qualified class name. This makes caller localization to work // properly even from classes that have almost the same fully // qualified class name as XLogger, such as XLogegoryTest. private static String FQCN = XLogger.class.getName() + "."; // It's enough to instantiate a factory once and for all. private static XFactory factory = new XFactory(); String suffix = ""; /** Just calls the parent constuctor. */ protected XLogger(String name) { super(name); } /** Nothing to activate. */ public void activateOptions() { } /** Overrides the standard debug method by appending the value of suffix variable to each message. */ public void debug(String message) { super.log(FQCN, Level.DEBUG, message + " " + suffix, null); } /** We introduce a new printing method in order to support {@link XLevel#LETHAL}. */ public void lethal(String message, Throwable t) { if(repository.isDisabled(XLevel.LETHAL_INT)) return; if(XLevel.LETHAL.isGreaterOrEqual(this.getEffectiveLevel())) forcedLog(FQCN, XLevel.LETHAL, message, t); } /** We introduce a new printing method in order to support {@link XLevel#LETHAL}. */ public void lethal(String message) { if(repository.isDisabled(XLevel.LETHAL_INT)) return; if(XLevel.LETHAL.isGreaterOrEqual(this.getEffectiveLevel())) forcedLog(FQCN, XLevel.LETHAL, message, null); } static public Logger getLogger(String name) { return LogManager.getLogger(name, factory); } static public Logger getLogger(Class clazz) { return XLogger.getLogger(clazz.getName()); } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } /** We introduce a new printing method that takes the TRACE level. */ public void trace(String message, Throwable t) { if(repository.isDisabled(XLevel.TRACE_INT)) return; if(XLevel.TRACE.isGreaterOrEqual(this.getEffectiveLevel())) forcedLog(FQCN, XLevel.TRACE, message, t); } /** We introduce a new printing method that takes the TRACE level. */ public void trace(String message) { if(repository.isDisabled(XLevel.TRACE_INT)) return; if(XLevel.TRACE.isGreaterOrEqual(this.getEffectiveLevel())) forcedLog(FQCN, XLevel.TRACE, message, null); } // Any sub-class of Logger must also have its own implementation of // CategoryFactory. public static class XFactory implements LoggerFactory { public XFactory() { } public Logger makeNewLoggerInstance(String name) { return new XLogger(name); } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/or/0000755000175000017500000000000012126647422022313 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/or/ORTestCase.java0000644000175000017500000001244011751454671025140 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // // Log4j uses the JUnit framework for internal unit testing. JUnit // available from // // http://www.junit.org package org.apache.log4j.or; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; import java.io.Serializable; /** Unit test the {@link ObjectRenderer}. @author Ceki Gülcü @since 1.0 */ public class ORTestCase extends TestCase { static UTObjectRenderer aor; static UTObjectRenderer bor; static UTObjectRenderer xor; static UTObjectRenderer yor; static UTObjectRenderer oor; static UTObjectRenderer nor; static UTObjectRenderer ior; static UTObjectRenderer cor; static UTObjectRenderer sor; public ORTestCase(String name) { super(name); } public void setUp() { aor = new UTObjectRenderer("A"); bor = new UTObjectRenderer("B"); xor = new UTObjectRenderer("X"); yor = new UTObjectRenderer("Y"); oor = new UTObjectRenderer("Object"); nor = new UTObjectRenderer("Number"); ior = new UTObjectRenderer("Integer"); cor = new UTObjectRenderer("Comparable"); sor = new UTObjectRenderer("Serializable"); } // Add: no renderer // Expect: defaultRenderer public void test1() { RendererMap map = new RendererMap(); ObjectRenderer dr = map.getDefaultRenderer(); ObjectRenderer r = map.get(Integer.class); assertEquals(r, dr); } // Add: Integer renderer // Expect: Integer renderer public void test2() { RendererMap map = new RendererMap(); map.put(Integer.class, ior); ObjectRenderer r = map.get(Integer.class); assertEquals(r, ior); } // Add: Number renderer // Expect: Number public void test3() { RendererMap map = new RendererMap(); map.put(Number.class, ior); ObjectRenderer r = map.get(Integer.class); assertEquals(r, ior); } // Add: Object renderer // Result: Object public void test4() { RendererMap map = new RendererMap(); map.put(Object.class, oor); ObjectRenderer r = map.get(Integer.class); assertEquals(r, oor); } // Add: Object, Number, Integer // Expect: Integer public void test5() { RendererMap map = new RendererMap(); map.put(Object.class, oor); map.put(Number.class, nor); map.put(Integer.class, ior); ObjectRenderer r = map.get(Integer.class); assertEquals(r, ior); } // Add: Object, Number // Expect: Number public void test6() { RendererMap map = new RendererMap(); map.put(Object.class, oor); map.put(Number.class, nor); ObjectRenderer r = map.get(Integer.class); assertEquals(r, nor); } // Add: Comparable // Expect: Comparable public void test7() throws Exception { RendererMap map = new RendererMap(); Class comparable = null; try { comparable = Class.forName("java.lang.Comparable"); } catch(Exception ex) { // likely JDK 1.1 return; } map.put(comparable, cor); ObjectRenderer r = map.get(Integer.class); assertEquals(r, cor); } // Add: Serializable // Expect: Serializablee public void test8() { RendererMap map = new RendererMap(); map.put(Serializable.class, sor); ObjectRenderer r = map.get(Integer.class); assertEquals(r, sor); } // Add: Y // Expect: Y public void test9() { RendererMap map = new RendererMap(); map.put(Y.class, yor); ObjectRenderer r = map.get(B.class); assertEquals(r, yor); } // Add: X // Expect: X public void test10() { RendererMap map = new RendererMap(); map.put(X.class, xor); ObjectRenderer r = map.get(B.class); assertEquals(r, xor); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new ORTestCase("test1")); suite.addTest(new ORTestCase("test2")); suite.addTest(new ORTestCase("test3")); suite.addTest(new ORTestCase("test4")); suite.addTest(new ORTestCase("test5")); suite.addTest(new ORTestCase("test6")); suite.addTest(new ORTestCase("test7")); suite.addTest(new ORTestCase("test8")); suite.addTest(new ORTestCase("test9")); suite.addTest(new ORTestCase("test10")); return suite; } } class UTObjectRenderer implements ObjectRenderer { String name; UTObjectRenderer(String name) { this.name = name; } public String doRender(Object o) { return name; } public String toString() { return("UTObjectRenderer: "+name); } } interface X { } interface Y extends X { } class A implements Y { } class B extends A { } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/util/0000755000175000017500000000000012126647422022650 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/util/AbsoluteTimeFilter.java0000644000175000017500000000227411751454673027272 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.util; import org.apache.oro.text.perl.Perl5Util; public class AbsoluteTimeFilter implements Filter { Perl5Util util = new Perl5Util(); public String filter(String in) { String pat = "/"+Filter.ABSOLUTE_TIME_PAT+"/"; if(util.match(pat, in)) { return util.substitute("s/"+Filter.ABSOLUTE_TIME_PAT+"//", in); } else { return in; } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/util/ControlFilter.java0000644000175000017500000000273611751454673026320 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.util; import org.apache.oro.text.perl.Perl5Util; public class ControlFilter implements Filter { Perl5Util util = new Perl5Util(); String[] allowedPatterns; public ControlFilter(String[] allowedPatterns) { this.allowedPatterns = allowedPatterns; } public String filter(String in) throws UnexpectedFormatException{ int len = allowedPatterns.length; for(int i = 0; i < len; i++) { //System.out.println("["+allowedPatterns[i]+"]"); if(util.match("/"+allowedPatterns[i]+"/", in)) { //System.out.println("["+in+"] matched ["+allowedPatterns[i]); return in; } } throw new UnexpectedFormatException("["+in+"]"); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/util/SunReflectFilter.java0000644000175000017500000000320311751454673026740 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.util; import org.apache.oro.text.perl.Perl5Util; /** * The sun.reflect.* and java.lang.reflect.* lines are not present in all JDKs. * * @author Ceki Gulcu */ public class SunReflectFilter implements Filter { Perl5Util util = new Perl5Util(); public String filter(String in) { if(in == null) { return null; } if (util.match("/at sun.reflect/", in)) { return null; } if (in.indexOf("at java.lang.reflect.") >= 0) { return null; } if (in.indexOf("Compiled Code") >= 0) { if(in.indexOf("junit.framework.TestSuite") >= 0) { return util.substitute("s/Compiled Code/TestSuite.java:XXX/", in); } } if (util.match("/\\(Method.java:.*\\)/", in)) { return util.substitute("s/\\(Method.java:.*\\)/(Native Method)/", in); } return in; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/util/AbsoluteDateAndTimeFilter.java0000644000175000017500000000232511751454673030510 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.util; import org.apache.oro.text.perl.Perl5Util; public class AbsoluteDateAndTimeFilter implements Filter { Perl5Util util = new Perl5Util(); public String filter(String in) { String pat = "/"+Filter.ABSOLUTE_DATE_AND_TIME_PAT+"/"; if(util.match(pat, in)) { return util.substitute("s/"+Filter.ABSOLUTE_DATE_AND_TIME_PAT+"//", in); } else { return in; } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/util/RelativeTimeFilter.java0000644000175000017500000000240411751454673027262 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.util; import org.apache.oro.text.perl.Perl5Util; public class RelativeTimeFilter implements Filter { Perl5Util util = new Perl5Util(); public String filter(String in) { String pat = "/"+Filter.RELATIVE_TIME_PAT+"/"; if(util.match(pat, in)) { //System.out.println("Removing relative time from line ["+in+"]"); return util.substitute("s/"+Filter.RELATIVE_TIME_PAT+"//", in); } else { return in; } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/util/SerializationTestHelper.java0000644000175000017500000001146011751454673030341 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.util; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * Utiities for serialization tests. * * @author Curt Arnold */ public class SerializationTestHelper { /** * Private constructor. */ private SerializationTestHelper() { } /** * Creates a clone by serializing object and * deserializing byte stream. * @param obj object to serialize and deserialize. * @return clone * @throws IOException on IO error. * @throws ClassNotFoundException if class not found. */ public static Object serializeClone(final Object obj) throws IOException, ClassNotFoundException { ByteArrayOutputStream memOut = new ByteArrayOutputStream(); ObjectOutputStream objOut = new ObjectOutputStream(memOut); objOut.writeObject(obj); objOut.close(); ByteArrayInputStream src = new ByteArrayInputStream(memOut.toByteArray()); ObjectInputStream objIs = new ObjectInputStream(src); return objIs.readObject(); } /** * Deserializes a specified file. * @param witness serialization file, may not be null. * @return deserialized object. * @throws Exception thrown on IO or deserialization exception. */ public static Object deserializeStream(final String witness) throws Exception { FileInputStream fileIs = new FileInputStream(witness); ObjectInputStream objIs = new ObjectInputStream(fileIs); return objIs.readObject(); } /** * Checks the serialization of an object against an file * containing the expected serialization. * * @param witness name of file containing expected serialization. * @param obj object to be serialized. * @param skip positions in serialized stream that should not be compared. * @param endCompare position to stop comparison. * @throws Exception thrown on IO or serialization exception. */ public static void assertSerializationEquals( final String witness, final Object obj, final int[] skip, final int endCompare) throws Exception { ByteArrayOutputStream memOut = new ByteArrayOutputStream(); ObjectOutputStream objOut = new ObjectOutputStream(memOut); objOut.writeObject(obj); objOut.close(); assertStreamEquals(witness, memOut.toByteArray(), skip, endCompare); } /** * Asserts the serialized form of an object. * @param witness file name of expected serialization. * @param actual byte array of actual serialization. * @param skip positions to skip comparison. * @param endCompare position to stop comparison. * @throws IOException thrown on IO or serialization exception. */ public static void assertStreamEquals( final String witness, final byte[] actual, final int[] skip, final int endCompare) throws IOException { File witnessFile = new File(witness); if (witnessFile.exists()) { int skipIndex = 0; byte[] expected = new byte[actual.length]; FileInputStream is = new FileInputStream(witnessFile); int bytesRead = is.read(expected); is.close(); if(bytesRead < endCompare) { TestCase.assertEquals(bytesRead, actual.length); } int endScan = actual.length; if (endScan > endCompare) { endScan = endCompare; } for (int i = 0; i < endScan; i++) { if ((skipIndex < skip.length) && (skip[skipIndex] == i)) { skipIndex++; } else { if (expected[i] != actual[i]) { TestCase.assertEquals( "Difference at offset " + i, expected[i], actual[i]); } } } } else { // // if the file doesn't exist then // assume that we are setting up and need to write it FileOutputStream os = new FileOutputStream(witnessFile); os.write(actual); os.close(); TestCase.fail("Writing witness file " + witness); } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/util/EnhancedLineNumberFilter.java0000644000175000017500000000265611751454673030367 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.util; import java.util.regex.Pattern; public class EnhancedLineNumberFilter implements Filter { private Pattern linePattern; private Pattern nativePattern; public EnhancedLineNumberFilter() { linePattern = Pattern.compile("\\(.*:\\d{1,4}\\)"); nativePattern = Pattern.compile("\\(Native Method\\)"); } public String filter(final String in) { if (linePattern.matcher(in).find()) { return linePattern.matcher(in).replaceAll("(X)"); } else if (nativePattern.matcher(in).find()) { return nativePattern.matcher(in).replaceAll("(X)"); } else { return in; } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/util/XMLTimestampFilter.java0000644000175000017500000000224711751454673027221 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.util; import org.apache.oro.text.perl.Perl5Util; public class XMLTimestampFilter implements Filter { Perl5Util util = new Perl5Util(); public String filter(String in) { if(util.match("/timestamp=\"\\d{10,13}\"/", in)) { return util.substitute("s/timestamp=\"\\d{10,13}\"/timestamp=\"XXX\"/", in); } else { return in; } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/util/Transformer.java0000644000175000017500000000416511751454673026032 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.util; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; public class Transformer { public static void transform(String in, String out, Filter[] filters) throws IOException, UnexpectedFormatException { String line; BufferedReader input = new BufferedReader(new FileReader(in)); PrintStream output = new PrintStream(new FileOutputStream(out, false)); // Initialization of input and output omitted while((line = input.readLine()) != null) { // apply all filters for(int i = 0; i < filters.length; i++) { line = filters[i].filter(line); } if(line != null) { output.println(line); } } } public static void transform(String in, String out, Filter filter) throws IOException, UnexpectedFormatException { String line; BufferedReader input = new BufferedReader(new FileReader(in)); PrintStream output = new PrintStream(new FileOutputStream(out)); // Initialization of input and output omitted while((line = input.readLine()) != null) { line = filter.filter(line); output.println(line); } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/util/XMLLineAttributeFilter.java0000644000175000017500000000240411751454673030024 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.util; import org.apache.oro.text.perl.Perl5Util; public class XMLLineAttributeFilter implements Filter { Perl5Util util = new Perl5Util(); public String filter(String in) { if(util.match("/line=\"\\d{1,3}\"/", in)) { return util.substitute("s/line=\"\\d{1,3}\"/line=\"X\"/", in); } else if(util.match("/line=\"?\"/", in)) { return util.substitute("s/line=\"?\"/line=\"X\"/", in); } else { return in; } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/util/LineNumberFilter.java0000644000175000017500000000237511751454673026737 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.util; import org.apache.oro.text.perl.Perl5Util; public class LineNumberFilter implements Filter { Perl5Util util = new Perl5Util(); public String filter(String in) { if(util.match("/\\(.*:\\d{1,4}\\)/", in)) { return util.substitute("s/:\\d{1,4}\\)/:XXX)/", in); } else { if(in.indexOf(", Compiled Code") >= 0) { return util.substitute("s/, Compiled Code/:XXX/", in); } return in; } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/util/UnexpectedFormatException.java0000644000175000017500000000201711751454673030656 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.util; public class UnexpectedFormatException extends Exception { private static final long serialVersionUID = 1787725660780924147L; public UnexpectedFormatException(String msg) { super(msg); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/util/Compare.java0000644000175000017500000001162611751454673025116 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.util; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.File; public class Compare { static final int B1_NULL = -1; static final int B2_NULL = -2; static public boolean compare(String file1, String file2) throws FileNotFoundException, IOException { BufferedReader in1 = new BufferedReader(new FileReader(file1)); BufferedReader in2 = new BufferedReader(new FileReader(file2)); String s1; int lineCounter = 0; while((s1 = in1.readLine()) != null) { lineCounter++; String s2 = in2.readLine(); if(!s1.equals(s2)) { System.out.println("Files ["+file1+"] and ["+file2+"] differ on line " +lineCounter); System.out.println("One reads: ["+s1+"]."); System.out.println("Other reads:["+s2+"]."); return false; } } // the second file is longer if(in2.read() != -1) { System.out.println("File ["+file2+"] longer than file ["+file1+"]."); return false; } return true; } private static final InputStream open( final Class testClass, final String fileName) throws IOException { String resourceName = fileName; if (fileName.startsWith("witness/")) { resourceName = fileName.substring(fileName.lastIndexOf('/') + 1); } InputStream is = testClass.getResourceAsStream(resourceName); if (is == null) { File file = new File(fileName); if (file.exists()) { is = new FileInputStream(file); } else { throw new FileNotFoundException("Resource " + resourceName + " not found"); } } return is; } public static boolean compare(Class testClass, final String file1, final String file2) throws IOException { BufferedReader in1 = new BufferedReader(new FileReader(file1)); BufferedReader in2 = new BufferedReader(new InputStreamReader( open(testClass, file2))); try { return compare(testClass, file1, file2, in1, in2); } finally { in1.close(); in2.close(); } } public static boolean compare( Class testClass, String file1, String file2, BufferedReader in1, BufferedReader in2) throws IOException { String s1; int lineCounter = 0; while ((s1 = in1.readLine()) != null) { lineCounter++; String s2 = in2.readLine(); if (!s1.equals(s2)) { System.out.println( "Files [" + file1 + "] and [" + file2 + "] differ on line " + lineCounter); System.out.println("One reads: [" + s1 + "]."); System.out.println("Other reads:[" + s2 + "]."); outputFile(testClass, file1); outputFile(testClass, file2); return false; } } // the second file is longer if (in2.read() != -1) { System.out.println( "File [" + file2 + "] longer than file [" + file1 + "]."); outputFile(testClass, file1); outputFile(testClass, file2); return false; } return true; } /** * * Prints file on the console. * */ private static void outputFile(Class testClass, String file) throws IOException { InputStream is = open(testClass, file); BufferedReader in1 = new BufferedReader(new InputStreamReader(is)); String s1; int lineCounter = 0; System.out.println("--------------------------------"); System.out.println("Contents of " + file + ":"); while ((s1 = in1.readLine()) != null) { lineCounter++; System.out.print(lineCounter); if (lineCounter < 10) { System.out.print(" : "); } else if (lineCounter < 100) { System.out.print(" : "); } else if (lineCounter < 1000) { System.out.print(" : "); } else { System.out.print(": "); } System.out.println(s1); } in1.close(); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/util/JunitTestRunnerFilter.java0000644000175000017500000000365711751454673030026 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.util; import org.apache.oro.text.perl.Perl5Util; public class JunitTestRunnerFilter implements Filter { Perl5Util util = new Perl5Util(); /** * Filter out stack trace lines coming from the various JUnit TestRunners. */ public String filter(String in) { if (in == null) { return null; } if ( util.match( "/at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner/", in)) { return null; } else if ( util.match( "/at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner/", in)) { return null; } else if ( util.match( "/at com.intellij/", in)) { return null; } else if (in.indexOf("at junit.") >= 0 && in.indexOf("ui.TestRunner") >= 0) { return null; } else if (in.indexOf("org.apache.maven") >= 0) { return null; } else if(in.indexOf("junit.internal") >= 0) { return null; } else if(in.indexOf("JUnit4TestAdapter") >= 0) { return null; } else if (util.match("/\\sat /", in)) { return "\t" + in.trim(); } else { return in; } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/util/ISO8601Filter.java0000644000175000017500000000223511751454673025643 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.util; import org.apache.oro.text.perl.Perl5Util; public class ISO8601Filter implements Filter { Perl5Util util = new Perl5Util(); public String filter(String in) { String pat = "/"+ISO8601_PAT +"/"; if(util.match(pat, in)) { return util.substitute("s/"+ISO8601_PAT+"//", in); } else { return in; } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/util/Filter.java0000644000175000017500000000272111751454673024751 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.util; public interface Filter { final String BASIC_PAT = "\\[main\\] (FATAL|ERROR|WARN|INFO|DEBUG)"; final String ISO8601_PAT = "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3}"; // 06 avr. 2002 18:36:32,036 // 18 fevr. 2002 20:05:36,222 static public final String ABSOLUTE_DATE_AND_TIME_PAT = "^\\d{1,2} .{2,6}\\.? 2\\d{3} \\d{2}:\\d{2}:\\d{2},\\d{3}"; // 18:54:19,201 static public final String ABSOLUTE_TIME_PAT = "^\\d{2}:\\d{2}:\\d{2},\\d{3}"; static public final String RELATIVE_TIME_PAT = "^\\d{1,10}"; String filter(String in) throws UnexpectedFormatException; } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/util/EnhancedJunitTestRunnerFilter.java0000644000175000017500000000411611751454673031443 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.util; import org.apache.oro.text.perl.Perl5Util; public class EnhancedJunitTestRunnerFilter implements Filter { private Perl5Util util = new Perl5Util(); private static final String[] PATTERNS = { "at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner", "at org.apache.tools.ant", "at junit.textui.TestRunner", "at com.intellij.rt.execution.junit", "at java.lang.reflect.Method.invoke", "at org.apache.maven.", "at org.codehaus.", "at org.junit.internal.runners.", "at junit.framework.JUnit4TestAdapter" }; public EnhancedJunitTestRunnerFilter() { } /** * Filter out stack trace lines coming from the various JUnit TestRunners. */ public String filter(String in) { if (in == null) { return null; } // // restore the one instance of Method.invoke that we actually want // if (in.indexOf("at junit.framework.TestCase.runTest") != -1) { return "\tat java.lang.reflect.Method.invoke(X)\n\t" + in.trim(); } for (int i = 0; i < PATTERNS.length; i++) { if(in.indexOf(PATTERNS[i]) != -1) { return null; } } if (util.match("/\\sat /", in)) { return "\t" + in.trim(); } return in; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/AsyncAppenderTestCase.java0000644000175000017500000002447011751454673026744 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; import java.util.Vector; import org.apache.log4j.spi.LoggingEvent; /** A superficial but general test of log4j. */ public class AsyncAppenderTestCase extends TestCase { public AsyncAppenderTestCase(String name) { super(name); } public void setUp() { } public void tearDown() { LogManager.shutdown(); } // this test checks whether it is possible to write to a closed AsyncAppender public void closeTest() throws Exception { Logger root = Logger.getRootLogger(); VectorAppender vectorAppender = new VectorAppender(); AsyncAppender asyncAppender = new AsyncAppender(); asyncAppender.setName("async-CloseTest"); asyncAppender.addAppender(vectorAppender); root.addAppender(asyncAppender); root.debug("m1"); asyncAppender.close(); root.debug("m2"); Vector v = vectorAppender.getVector(); assertEquals(v.size(), 1); } // this test checks whether appenders embedded within an AsyncAppender are also // closed public void test2() { Logger root = Logger.getRootLogger(); VectorAppender vectorAppender = new VectorAppender(); AsyncAppender asyncAppender = new AsyncAppender(); asyncAppender.setName("async-test2"); asyncAppender.addAppender(vectorAppender); root.addAppender(asyncAppender); root.debug("m1"); asyncAppender.close(); root.debug("m2"); Vector v = vectorAppender.getVector(); assertEquals(v.size(), 1); assertTrue(vectorAppender.isClosed()); } // this test checks whether appenders embedded within an AsyncAppender are also // closed public void test3() { int LEN = 200; Logger root = Logger.getRootLogger(); VectorAppender vectorAppender = new VectorAppender(); AsyncAppender asyncAppender = new AsyncAppender(); asyncAppender.setName("async-test3"); asyncAppender.addAppender(vectorAppender); root.addAppender(asyncAppender); for(int i = 0; i < LEN; i++) { root.debug("message"+i); } System.out.println("Done loop."); System.out.flush(); asyncAppender.close(); root.debug("m2"); Vector v = vectorAppender.getVector(); assertEquals(v.size(), LEN); assertTrue(vectorAppender.isClosed()); } private static class NullPointerAppender extends AppenderSkeleton { public NullPointerAppender() { } /** This method is called by the {@link org.apache.log4j.AppenderSkeleton#doAppend} method. */ public void append(org.apache.log4j.spi.LoggingEvent event) { throw new NullPointerException(); } public void close() { } public boolean requiresLayout() { return false; } } /** * Tests that a bad appender will switch async back to sync. * See bug 23021 * @since 1.2.12 * @throws Exception thrown if Thread.sleep is interrupted */ public void testBadAppender() throws Exception { Appender nullPointerAppender = new NullPointerAppender(); AsyncAppender asyncAppender = new AsyncAppender(); asyncAppender.addAppender(nullPointerAppender); asyncAppender.setBufferSize(5); asyncAppender.activateOptions(); Logger root = Logger.getRootLogger(); root.addAppender(nullPointerAppender); try { root.info("Message"); Thread.sleep(10); root.info("Message"); fail("Should have thrown exception"); } catch(NullPointerException ex) { } } /** * Tests location processing when buffer is full and locationInfo=true. * See bug 41186. */ public void testLocationInfoTrue() { BlockableVectorAppender blockableAppender = new BlockableVectorAppender(); AsyncAppender async = new AsyncAppender(); async.addAppender(blockableAppender); async.setBufferSize(5); async.setLocationInfo(true); async.setBlocking(false); async.activateOptions(); Logger rootLogger = Logger.getRootLogger(); rootLogger.addAppender(async); Greeter greeter = new Greeter(rootLogger, 100); synchronized(blockableAppender.getMonitor()) { greeter.run(); rootLogger.error("That's all folks."); } async.close(); Vector events = blockableAppender.getVector(); LoggingEvent initialEvent = (LoggingEvent) events.get(0); LoggingEvent discardEvent = (LoggingEvent) events.get(events.size() - 1); PatternLayout layout = new PatternLayout(); layout.setConversionPattern("%C:%L %m%n"); layout.activateOptions(); String initialStr = layout.format(initialEvent); assertEquals(AsyncAppenderTestCase.class.getName(), initialStr.substring(0, AsyncAppenderTestCase.class.getName().length())); String discardStr = layout.format(discardEvent); assertEquals("?:? ", discardStr.substring(0, 4)); } /** * Tests location processing when buffer is full and locationInfo=false. * See bug 41186. */ public void testLocationInfoFalse() { BlockableVectorAppender blockableAppender = new BlockableVectorAppender(); AsyncAppender async = new AsyncAppender(); async.addAppender(blockableAppender); async.setBufferSize(5); async.setLocationInfo(false); async.setBlocking(false); async.activateOptions(); Logger rootLogger = Logger.getRootLogger(); rootLogger.addAppender(async); Greeter greeter = new Greeter(rootLogger, 100); synchronized(blockableAppender.getMonitor()) { greeter.run(); rootLogger.error("That's all folks."); } async.close(); Vector events = blockableAppender.getVector(); LoggingEvent initialEvent = (LoggingEvent) events.get(0); LoggingEvent discardEvent = (LoggingEvent) events.get(events.size() - 1); PatternLayout layout = new PatternLayout(); layout.setConversionPattern("%C:%L %m%n"); layout.activateOptions(); String initialStr = layout.format(initialEvent); assertEquals("?:? ", initialStr.substring(0, 4)); String discardStr = layout.format(discardEvent); assertEquals("?:? ", discardStr.substring(0, 4)); } /** * Logging request runnable. */ private static final class Greeter implements Runnable { /** * Logger. */ private final Logger logger; /** * Repetitions. */ private final int repetitions; /** * Create new instance. * @param logger logger, may not be null. * @param repetitions repetitions. */ public Greeter(final Logger logger, final int repetitions) { if (logger == null) { throw new IllegalArgumentException("logger"); } this.logger = logger; this.repetitions = repetitions; } /** * {@inheritDoc} */ public void run() { try { for (int i = 0; i < repetitions; i++) { logger.info("Hello, World"); Thread.sleep(1); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } /** * Vector appender that can be explicitly blocked. */ private static final class BlockableVectorAppender extends VectorAppender { /** * Monitor object used to block appender. */ private final Object monitor = new Object(); /** * Create new instance. */ public BlockableVectorAppender() { super(); } /** * {@inheritDoc} */ public void append(final LoggingEvent event) { synchronized (monitor) { super.append(event); // // if fatal, echo messages for testLoggingInDispatcher // if (event.getLevel() == Level.FATAL) { Logger logger = Logger.getLogger(event.getLoggerName()); logger.error(event.getMessage().toString()); logger.warn(event.getMessage().toString()); logger.info(event.getMessage().toString()); logger.debug(event.getMessage().toString()); } } } /** * Get monitor object. * @return monitor. */ public Object getMonitor() { return monitor; } } /** * Test that a mutable message object is evaluated before * being placed in the async queue. * See bug 43559. */ public void testMutableMessage() { BlockableVectorAppender blockableAppender = new BlockableVectorAppender(); AsyncAppender async = new AsyncAppender(); async.addAppender(blockableAppender); async.setBufferSize(5); async.setLocationInfo(false); async.activateOptions(); Logger rootLogger = Logger.getRootLogger(); rootLogger.addAppender(async); StringBuffer buf = new StringBuffer("Hello"); synchronized(blockableAppender.getMonitor()) { rootLogger.info(buf); buf.append(", World."); } async.close(); Vector events = blockableAppender.getVector(); LoggingEvent event = (LoggingEvent) events.get(0); PatternLayout layout = new PatternLayout(); layout.setConversionPattern("%m"); layout.activateOptions(); String msg = layout.format(event); assertEquals("Hello", msg); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/pattern/0000755000175000017500000000000012126647422023350 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/pattern/Num343PatternConverter.java0000644000175000017500000000246511751454672030447 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.spi.LoggingEvent; public class Num343PatternConverter extends LoggingEventPatternConverter { private Num343PatternConverter() { super("Num34", "num34"); } private static final Num343PatternConverter INSTANCE = new Num343PatternConverter(); public static PatternConverter newInstance(final String[] options) { return INSTANCE; } public void format(LoggingEvent event, StringBuffer toAppendTo) { toAppendTo.append("343"); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/pattern/FormattingInfoTest.java0000644000175000017500000000516611751454672030017 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import junit.framework.TestCase; /** * Tests for FormattingInfo. * * @author Curt Arnold * */ public class FormattingInfoTest extends TestCase { /** * Create a new instance. * * @param name test name */ public FormattingInfoTest(final String name) { super(name); } /** * Check that getDefault does not return null. * */ public void testGetDefault() { FormattingInfo field = FormattingInfo.getDefault(); assertNotNull(field); assertEquals(0, field.getMinLength()); assertEquals(Integer.MAX_VALUE, field.getMaxLength()); assertEquals(false, field.isLeftAligned()); } /** * Check constructor * */ public void testConstructor() { FormattingInfo field = new FormattingInfo(true, 3, 6); assertNotNull(field); assertEquals(3, field.getMinLength()); assertEquals(6, field.getMaxLength()); assertEquals(true, field.isLeftAligned()); } /** * Field exceeds maximum width */ public void testTruncate() { StringBuffer buf = new StringBuffer("foobar"); FormattingInfo field = new FormattingInfo(true, 0, 3); field.format(2, buf); assertEquals("fobar", buf.toString()); } /** * Add padding to left since field is not minimum width. */ public void testPadLeft() { StringBuffer buf = new StringBuffer("foobar"); FormattingInfo field = new FormattingInfo(false, 5, 10); field.format(2, buf); assertEquals("fo obar", buf.toString()); } /** * Add padding to right since field is not minimum width. */ public void testPadRight() { StringBuffer buf = new StringBuffer("foobar"); FormattingInfo field = new FormattingInfo(true, 5, 10); field.format(2, buf); assertEquals("foobar ", buf.toString()); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/pattern/CachedDateFormatTest.java0000644000175000017500000003277011751454672030210 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.log4j.pattern.CachedDateFormat; import java.text.DateFormat; import java.util.TimeZone; import java.util.Date; import java.text.SimpleDateFormat; import java.util.Locale; import java.util.Calendar; /** Unit test {@link AbsoluteTimeDateFormat}. @author Curt Arnold */ public final class CachedDateFormatTest extends TestCase { /** * Test constructor * @param name String test name */ public CachedDateFormatTest(String name) { super(name); } private static DateFormat createAbsoluteTimeDateFormat(TimeZone timeZone) { DateFormat df = new SimpleDateFormat("HH:mm:ss,SSS"); df.setTimeZone(timeZone); return df; } /** * Timezone representing GMT. */ private static final TimeZone GMT = TimeZone.getTimeZone("GMT"); /** * Timezone for Chicago, Ill. USA. */ private static final TimeZone CHICAGO = TimeZone.getTimeZone( "America/Chicago"); /** * Test multiple calls in close intervals. */ public void test1() { // subsequent calls within one minute // are optimized to reuse previous formatted value // make a couple of nearly spaced calls DateFormat gmtFormat = new CachedDateFormat(createAbsoluteTimeDateFormat(GMT), 1000); long ticks = 12601L * 86400000L; Date jul1 = new Date(ticks); assertEquals("00:00:00,000", gmtFormat.format(jul1)); Date plus8ms = new Date(ticks + 8); assertEquals("00:00:00,008", gmtFormat.format(plus8ms)); Date plus17ms = new Date(ticks + 17); assertEquals("00:00:00,017", gmtFormat.format(plus17ms)); Date plus237ms = new Date(ticks + 237); assertEquals("00:00:00,237", gmtFormat.format(plus237ms)); Date plus1415ms = new Date(ticks + 1415); assertEquals("00:00:01,415", gmtFormat.format(plus1415ms)); } /** * Check for interaction between caches. */ public void test2() { Date jul2 = new Date(12602L * 86400000L); DateFormat gmtFormat = new CachedDateFormat(createAbsoluteTimeDateFormat(GMT), 1000); DateFormat chicagoFormat = new CachedDateFormat(createAbsoluteTimeDateFormat(CHICAGO), 1000); assertEquals("00:00:00,000", gmtFormat.format(jul2)); assertEquals("19:00:00,000", chicagoFormat.format(jul2)); assertEquals("00:00:00,000", gmtFormat.format(jul2)); } /** * Test multiple calls in close intervals prior to 1 Jan 1970. */ public void test3() { // subsequent calls within one minute // are optimized to reuse previous formatted value // make a couple of nearly spaced calls DateFormat gmtFormat = new CachedDateFormat( createAbsoluteTimeDateFormat(GMT), 1000); // // if the first call was exactly on an integral // second, it would not test the round toward zero compensation long ticks = -7L * 86400000L; Date jul1 = new Date(ticks + 8); assertEquals("00:00:00,008", gmtFormat.format(jul1)); Date plus8ms = new Date(ticks + 16); assertEquals("00:00:00,016", gmtFormat.format(plus8ms)); Date plus17ms = new Date(ticks + 23); assertEquals("00:00:00,023", gmtFormat.format(plus17ms)); Date plus237ms = new Date(ticks + 245); assertEquals("00:00:00,245", gmtFormat.format(plus237ms)); Date plus1415ms = new Date(ticks + 1423); assertEquals("00:00:01,423", gmtFormat.format(plus1415ms)); } public void test4() { // subsequent calls within one minute are optimized to reuse previous // formatted value. make a couple of nearly spaced calls // (Note: 'Z' is JDK 1.4, using 'z' instead.) SimpleDateFormat baseFormat = new SimpleDateFormat("EEE, MMM dd, HH:mm:ss.SSS z", Locale.ENGLISH); DateFormat cachedFormat = new CachedDateFormat(baseFormat, 1000); // // use a date in 2000 to attempt to confuse the millisecond locator long ticks = 11141L * 86400000L; Date jul1 = new Date(ticks); assertEquals(baseFormat.format(jul1), cachedFormat.format(jul1)); Date plus8ms = new Date(ticks + 8); baseFormat.format(plus8ms); cachedFormat.format(plus8ms); assertEquals(baseFormat.format(plus8ms), cachedFormat.format(plus8ms)); Date plus17ms = new Date(ticks + 17); assertEquals(baseFormat.format(plus17ms), cachedFormat.format(plus17ms)); Date plus237ms = new Date(ticks + 237); assertEquals(baseFormat.format(plus237ms), cachedFormat.format(plus237ms)); Date plus1415ms = new Date(ticks + 1415); assertEquals(baseFormat.format(plus1415ms), cachedFormat.format(plus1415ms)); } public void test5() { // subsequent calls within one minute // are optimized to reuse previous formatted value // make a couple of nearly spaced calls // (Note: 'Z' is JDK 1.4, using 'z' instead.) Locale thai = new Locale("th", "TH"); SimpleDateFormat baseFormat = new SimpleDateFormat("EEE, MMM dd, HH:mm:ss.SSS z", thai); DateFormat cachedFormat = new CachedDateFormat(baseFormat, 1000); // // use a date in the year 2000 CE to attempt to confuse the millisecond locator long ticks = 11141L * 86400000L; String sx; Date jul1 = new Date(ticks); sx = cachedFormat.format(jul1); System.out.println(baseFormat.format(jul1)); System.out.println(sx); assertEquals(baseFormat.format(jul1), sx); sx = cachedFormat.format(jul1); System.out.println(baseFormat.format(jul1)); System.out.println(sx); assertEquals(baseFormat.format(jul1), sx); Date plus8ms = new Date(ticks + 8); sx = cachedFormat.format(plus8ms); System.out.println(baseFormat.format(plus8ms)); System.out.println(sx); assertEquals(baseFormat.format(plus8ms), sx); Date plus17ms = new Date(ticks + 17); assertEquals(baseFormat.format(plus17ms), cachedFormat.format(plus17ms)); Date plus237ms = new Date(ticks + 237); assertEquals(baseFormat.format(plus237ms), cachedFormat.format(plus237ms)); Date plus1415ms = new Date(ticks + 1415); assertEquals(baseFormat.format(plus1415ms), cachedFormat.format(plus1415ms)); } /** * Checks that getNumberFormat does not return null. */ public void test6() { assertNotNull(new CachedDateFormat(new SimpleDateFormat(), 1000).getNumberFormat()); } /** * Set time zone on cached and check that it is effective. */ public void test8() { DateFormat baseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS"); baseFormat.setTimeZone(GMT); DateFormat cachedFormat = new CachedDateFormat(baseFormat, 1000); Date jul4 = new Date(12603L * 86400000L); assertEquals("2004-07-04 00:00:00,000", cachedFormat.format(jul4)); cachedFormat.setTimeZone(TimeZone.getTimeZone("GMT-6")); assertEquals("2004-07-03 18:00:00,000", cachedFormat.format(jul4)); } /** * Test of caching when less than three millisecond digits are specified. */ public void test9() { // (Note: 'Z' is JDK 1.4, using 'z' instead.) DateFormat baseFormat = new SimpleDateFormat("yyyy-MMMM-dd HH:mm:ss,SS z", Locale.US); DateFormat cachedFormat = new CachedDateFormat(baseFormat, 1000); TimeZone cet = TimeZone.getTimeZone("GMT+1"); cachedFormat.setTimeZone(cet); Calendar c = Calendar.getInstance(); c.set(2004, Calendar.DECEMBER, 12, 20, 0); c.set(Calendar.SECOND, 37); c.set(Calendar.MILLISECOND, 23); c.setTimeZone(cet); String expected = baseFormat.format(c.getTime()); String s = cachedFormat.format(c.getTime()); assertEquals(expected, s); c.set(2005, Calendar.JANUARY, 1, 0, 0); c.set(Calendar.SECOND, 13); c.set(Calendar.MILLISECOND, 905); expected = baseFormat.format(c.getTime()); s = cachedFormat.format(c.getTime()); assertEquals(expected, s); } /** * Test when millisecond position moves but length remains constant. */ public void test10() { DateFormat baseFormat = new SimpleDateFormat("MMMM SSS EEEEEE", Locale.US); DateFormat cachedFormat = new CachedDateFormat(baseFormat, 1000); TimeZone cet = TimeZone.getTimeZone("GMT+1"); cachedFormat.setTimeZone(cet); Calendar c = Calendar.getInstance(); c.set(2004, Calendar.OCTOBER, 5, 20, 0); c.set(Calendar.SECOND, 37); c.set(Calendar.MILLISECOND, 23); c.setTimeZone(cet); String expected = baseFormat.format(c.getTime()); String s = cachedFormat.format(c.getTime()); assertEquals(expected, s); c.set(2004, Calendar.NOVEMBER, 1, 0, 0); c.set(Calendar.MILLISECOND, 23); expected = baseFormat.format(c.getTime()); s = cachedFormat.format(c.getTime()); assertEquals(expected, s); c.set(Calendar.MILLISECOND, 984); expected = baseFormat.format(c.getTime()); s = cachedFormat.format(c.getTime()); assertEquals(expected, s); } /** * Test that tests if caching is skipped if only "SS" * is specified. */ public void test11() { // // Earlier versions could be tricked by "SS0" patterns. // String badPattern = "ss,SS0"; SimpleDateFormat simpleFormat = new SimpleDateFormat(badPattern); SimpleDateFormat baseFormat = new SimpleDateFormat(badPattern); DateFormat gmtFormat = new CachedDateFormat(simpleFormat, 1000); gmtFormat.setTimeZone(GMT); baseFormat.setTimeZone(GMT); // // The first request has to 100 ms after an ordinal second // to push the literal zero out of the pattern check long ticks = 11142L * 86400000L; Date jul2 = new Date(ticks + 120); String expected = baseFormat.format(jul2); assertEquals(expected, gmtFormat.format(jul2)); jul2.setTime(ticks + 87); // // Cache gives 00,087 expected = baseFormat.format(jul2); assertEquals(expected, gmtFormat.format(jul2)); } /** * Check pattern location for ISO8601 */ public void test12() { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS"); long ticks = 11142L * 86400000L; String formatted = df.format(new Date(ticks)); int millisecondStart = CachedDateFormat.findMillisecondStart(ticks, formatted, df); assertEquals(20, millisecondStart); } /** * Check pattern location for DATE */ public void test13() { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); long ticks = 11142L * 86400000L; String formatted = df.format(new Date(ticks)); int millisecondStart = CachedDateFormat.findMillisecondStart(ticks, formatted, df); assertEquals(CachedDateFormat.NO_MILLISECONDS, millisecondStart); } /** * Check pattern location for ABSOLUTE */ public void test14() { SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss,SSS"); long ticks = 11142L * 86400000L; String formatted = df.format(new Date(ticks)); int millisecondStart = CachedDateFormat.findMillisecondStart(ticks, formatted, df); assertEquals(9, millisecondStart); } /** * Check pattern location for single S */ public void test15() { SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss,S"); long ticks = 11142L * 86400000L; String formatted = df.format(new Date(ticks)); int millisecondStart = CachedDateFormat.findMillisecondStart(ticks, formatted, df); assertEquals(CachedDateFormat.UNRECOGNIZED_MILLISECONDS, millisecondStart); } /** * Check pattern location for single SS */ public void test16() { SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss,SS"); long ticks = 11142L * 86400000L; String formatted = df.format(new Date(ticks)); int millisecondStart = CachedDateFormat.findMillisecondStart(ticks, formatted, df); assertEquals(CachedDateFormat.UNRECOGNIZED_MILLISECONDS, millisecondStart); } /** * Check caching when multiple SSS appear in pattern */ public void test17() { Date jul2 = new Date(12602L * 86400000L); String badPattern = "HH:mm:ss,SSS HH:mm:ss,SSS"; SimpleDateFormat simpleFormat = new SimpleDateFormat(badPattern); simpleFormat.setTimeZone(GMT); DateFormat cachedFormat = new CachedDateFormat(simpleFormat, 1000); String s = cachedFormat.format(jul2); assertEquals("00:00:00,000 00:00:00,000", s); jul2.setTime(jul2.getTime() + 120); assertEquals("00:00:00,120 00:00:00,120", simpleFormat.format(jul2)); s = cachedFormat.format(jul2); // // TODO: why is this returning ,120 ... , 120 // //assertEquals("00:00:00,120 00:00:00,000", s) ; int maxValid = CachedDateFormat.getMaximumCacheValidity(badPattern); assertEquals(1, maxValid); } public static Test xsuite() { TestSuite suite = new TestSuite(); suite.addTest(new CachedDateFormatTest("test5")); //suite.addTest(new CachedDateFormatTest("testS2")); return suite; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/pattern/NameAbbreviatorTest.java0000644000175000017500000002330411751454672030124 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import junit.framework.TestCase; /** * Tests for NameAbbrevator. * */ public class NameAbbreviatorTest extends TestCase { /** * Create a new instance. * * @param name test name */ public NameAbbreviatorTest(final String name) { super(name); } /** * Check that getDefaultAbbreviator does not return null. * */ public void testGetDefault() { NameAbbreviator abbrev = NameAbbreviator.getDefaultAbbreviator(); assertNotNull(abbrev); } /** * Check that "0" drops all name content. * */ public void testZero() { NameAbbreviator abbrev = NameAbbreviator.getAbbreviator("0"); StringBuffer buf = new StringBuffer("DEBUG - "); int fieldStart = buf.length(); buf.append("org.example.foo.bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - ", buf.toString()); } /** * Check that getAbbreviator(" ") returns default abbreviator. * */ public void testBlank() { NameAbbreviator abbrev = NameAbbreviator.getAbbreviator(" "); NameAbbreviator defaultAbbrev = NameAbbreviator.getDefaultAbbreviator(); assertTrue(abbrev == defaultAbbrev); } /** * Check that getAbbreviator("1").abbreviate() drops all but the final name element. * */ public void testOne() { NameAbbreviator abbrev = NameAbbreviator.getAbbreviator("1"); StringBuffer buf = new StringBuffer("DEBUG - "); int fieldStart = buf.length(); buf.append("org.example.foo.bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - bar", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); buf.append("bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - bar", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - ", buf.toString()); } /** * Check that blanks are trimmed in evaluating abbreviation pattern. */ public void testBlankOne() { NameAbbreviator abbrev = NameAbbreviator.getAbbreviator(" 1 "); StringBuffer buf = new StringBuffer("DEBUG - "); int fieldStart = buf.length(); buf.append("org.example.foo.bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - bar", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); buf.append("bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - bar", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - ", buf.toString()); } /** * Check that getAbbreviator("2").abbreviate drops all but the last two elements. * */ public void testTwo() { NameAbbreviator abbrev = NameAbbreviator.getAbbreviator("2"); StringBuffer buf = new StringBuffer("DEBUG - "); int fieldStart = buf.length(); buf.append("org.example.foo.bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - foo.bar", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); buf.append("foo.bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - foo.bar", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); buf.append("bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - bar", buf.toString()); } /** * Check that getAbbreviator("1.").abbreviate abbreviates non-final elements * to one character. * */ public void testOneDot() { NameAbbreviator abbrev = NameAbbreviator.getAbbreviator("1."); StringBuffer buf = new StringBuffer("DEBUG - "); int fieldStart = buf.length(); buf.append("org.example.foo.bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - o.e.f.bar", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); buf.append("org.example.foo."); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - o.e.f.", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); buf.append("foo.bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - f.bar", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); buf.append("bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - bar", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - ", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); buf.append("."); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - .", buf.toString()); } /** * Check that getAbbreviator("1~.").abbreviate abbreviates non-final elements * to one character and a tilde. * */ public void testOneTildeDot() { NameAbbreviator abbrev = NameAbbreviator.getAbbreviator("1~."); StringBuffer buf = new StringBuffer("DEBUG - "); int fieldStart = buf.length(); buf.append("org.example.foo.bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - o~.e~.f~.bar", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); buf.append("org.example.foo."); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - o~.e~.f~.", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); buf.append("foo.bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - f~.bar", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); buf.append("bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - bar", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - ", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); buf.append("."); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - .", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); buf.append("o.e.f.bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - o.e.f.bar", buf.toString()); } /** * Check that getAbbreviator("1.*.2").abbreviate drops all but the first * character from the first element, uses all of the second element and * drops all but the first two characters of the rest of the non-final elements. * */ public void testMulti() { NameAbbreviator abbrev = NameAbbreviator.getAbbreviator("1.*.2"); StringBuffer buf = new StringBuffer("DEBUG - "); int fieldStart = buf.length(); buf.append("org.example.foo.bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - o.example.fo.bar", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); buf.append("org.example.foo."); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - o.example.fo.", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); buf.append("foo.bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - f.bar", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); buf.append("bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - bar", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - ", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); buf.append("."); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - .", buf.toString()); } /** * Check that getAbbreviator("-1").abbreviate() drops first name element. * */ public void testMinusOne() { NameAbbreviator abbrev = NameAbbreviator.getAbbreviator("-1"); StringBuffer buf = new StringBuffer("DEBUG - "); int fieldStart = buf.length(); buf.append("org.example.foo.bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - example.foo.bar", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); buf.append("bar"); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - bar", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - ", buf.toString()); buf.setLength(0); buf.append("DEBUG - "); fieldStart = buf.length(); buf.append("."); abbrev.abbreviate(fieldStart, buf); assertEquals("DEBUG - ", buf.toString()); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/pattern/PatternParserTest.java0000644000175000017500000001361411751454672027660 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TimeZone; import junit.framework.TestCase; import org.apache.log4j.Layout; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; /** Test case for PatternParser.java. Tests the various conversion patterns supported by PatternParser. This test class tests PatternParser via the EnhancedPatternLayout class which uses it. */ public class PatternParserTest extends TestCase { private final Logger logger = Logger.getLogger("org.foobar"); private final LoggingEvent event; public PatternParserTest(String name) { super(name); event = new LoggingEvent("org.apache.log4j.Logger", logger, Level.INFO, "msg 1", null); } private static String convert( String pattern, Map registry, LoggingEvent event) { List converters = new ArrayList(); List fields = new ArrayList(); PatternParser.parse(pattern, converters, fields, registry, PatternParser.getPatternLayoutRules()); assertEquals(converters.size(), fields.size()); StringBuffer buf = new StringBuffer(); Iterator converterIter = converters.iterator(); Iterator fieldIter = fields.iterator(); while(converterIter.hasNext()) { int fieldStart = buf.length(); ((PatternConverter) converterIter.next()).format(event, buf); ((FormattingInfo) fieldIter.next()).format(fieldStart, buf); } return buf.toString(); } public void testNewWord() throws Exception { HashMap ruleRegistry = new HashMap(5); ruleRegistry.put("z343", Num343PatternConverter.class.getName()); String result = convert("%z343", ruleRegistry, event); assertEquals("343", result); } /* Test whether words starting with the letter 'n' are treated differently, * which was previously the case by mistake. */ public void testNewWord2() throws Exception { HashMap ruleRegistry = new HashMap(5); ruleRegistry.put("n343", Num343PatternConverter.class.getName()); String result = convert("%n343", ruleRegistry, event); assertEquals("343", result); } public void testBogusWord1() throws Exception { String result = convert("%, foobar", null, event); assertEquals("%, foobar", result); } public void testBogusWord2() throws Exception { String result = convert("xyz %, foobar", null, event); assertEquals("xyz %, foobar", result); } public void testBasic1() throws Exception { String result = convert("hello %-5level - %m%n", null, event); assertEquals("hello INFO - msg 1" + Layout.LINE_SEP, result); } public void testBasic2() throws Exception { String result = convert("%relative %-5level [%thread] %logger - %m%n", null, event); long expectedRelativeTime = event.timeStamp - LoggingEvent.getStartTime(); assertEquals(expectedRelativeTime + " INFO [main] "+logger.getName()+" - msg 1" + Layout.LINE_SEP, result); } public void testMultiOption() throws Exception { String result = convert("%d{HH:mm:ss}{GMT} %d{HH:mm:ss} %c - %m", null, event); SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); String localTime = dateFormat.format(new Date(event.timeStamp)); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); String utcTime = dateFormat.format(new Date(event.timeStamp)); StringBuffer buf = new StringBuffer(utcTime); buf.append(' '); buf.append(localTime); buf.append(" org.foobar - msg 1"); assertEquals(buf.toString(), result); } public void testBogus() throws Exception { String result = convert("%bogus", null, event); assertEquals("%bogus", result); } public void testMore() throws Exception { String result = convert("%more", null, event); assertEquals("msg 1ore", result); } /** * Options with missing close braces will be treated as a literal. * Endless looped with earlier code. * */ public void testMalformedOption() { String result = convert("foo%m{yyyy.MM.dd", null, event); assertEquals("foomsg 1{yyyy.MM.dd", result); } private void assertFactories(Map rules) throws Exception { assertTrue(rules.size() > 0); Iterator iter = rules.values().iterator(); Class[] factorySig = new Class[] { Class.forName("[Ljava.lang.String;") }; Object[] factoryArg = new Object[] { null }; while(iter.hasNext()) { Class ruleClass = (Class) iter.next(); Method factory = ruleClass.getMethod("newInstance", factorySig); Object converter = factory.invoke(null, factoryArg); assertTrue(converter != null); } } public void testPatternLayoutFactories() throws Exception { assertFactories(PatternParser.getPatternLayoutRules()); } public void testFileNamePatternFactories() throws Exception { assertFactories(PatternParser.getFileNamePatternRules()); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/varia/0000755000175000017500000000000012126647422022775 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/varia/LevelMatchFilterTestCase.java0000644000175000017500000001137111751454671030476 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.varia; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; import org.apache.log4j.Logger; import org.apache.log4j.Level; import org.apache.log4j.Appender; import org.apache.log4j.FileAppender; import org.apache.log4j.Layout; import org.apache.log4j.SimpleLayout; import org.apache.log4j.varia.LevelMatchFilter; import org.apache.log4j.varia.DenyAllFilter; import org.apache.log4j.util.Transformer; import org.apache.log4j.util.Compare; import org.apache.log4j.util.LineNumberFilter; /** Test case for varia/LevelMatchFilter.java. */ public class LevelMatchFilterTestCase extends TestCase { static String ACCEPT_FILE = "output/LevelMatchFilter_accept"; static String ACCEPT_FILTERED = "output/LevelMatchFilter_accept_filtered"; static String ACCEPT_WITNESS = "witness/LevelMatchFilter_accept"; static String DENY_FILE = "output/LevelMatchFilter_deny"; static String DENY_FILTERED = "output/LevelMatchFilter_deny_filtered"; static String DENY_WITNESS = "witness/LevelMatchFilter_deny"; Logger root; Logger logger; public LevelMatchFilterTestCase(String name) { super(name); } public void setUp() { root = Logger.getRootLogger(); root.removeAllAppenders(); } public void tearDown() { root.getLoggerRepository().resetConfiguration(); } public void accept() throws Exception { // set up appender Layout layout = new SimpleLayout(); Appender appender = new FileAppender(layout, ACCEPT_FILE, false); // create LevelMatchFilter LevelMatchFilter matchFilter = new LevelMatchFilter(); // attach match filter to appender appender.addFilter(matchFilter); // attach DenyAllFilter to end of filter chain to deny neutral // (non matching) messages appender.addFilter(new DenyAllFilter()); // set appender on root and set level to debug root.addAppender(appender); root.setLevel(Level.TRACE); Level[] levelArray = new Level[] {Level.TRACE, Level.DEBUG, Level.INFO, Level.WARN, Level.ERROR, Level.FATAL}; for (int x = 0; x < levelArray.length; x++) { // set the level to match matchFilter.setLevelToMatch(levelArray[x].toString()); common("pass " + x + "; filter set to accept only " + levelArray[x].toString() + " msgs"); } Transformer.transform(ACCEPT_FILE, ACCEPT_FILTERED, new LineNumberFilter()); assertTrue(Compare.compare(ACCEPT_FILTERED, ACCEPT_WITNESS)); } public void deny() throws Exception { // set up appender Layout layout = new SimpleLayout(); Appender appender = new FileAppender(layout, DENY_FILE, false); // create LevelMatchFilter, set to deny matches LevelMatchFilter matchFilter = new LevelMatchFilter(); matchFilter.setAcceptOnMatch(false); // attach match filter to appender appender.addFilter(matchFilter); // set appender on root and set level to debug root.addAppender(appender); root.setLevel(Level.TRACE); Level[] levelArray = new Level[] {Level.TRACE, Level.DEBUG, Level.INFO, Level.WARN, Level.ERROR, Level.FATAL}; for (int x = 0; x < levelArray.length; x++) { // set the level to match matchFilter.setLevelToMatch(levelArray[x].toString()); common("pass " + x + "; filter set to deny only " + levelArray[x].toString() + " msgs"); } Transformer.transform(DENY_FILE, DENY_FILTERED, new LineNumberFilter()); assertTrue(Compare.compare(DENY_FILTERED, DENY_WITNESS)); } void common(String msg) { Logger logger = Logger.getLogger("test"); logger.trace(msg); logger.debug(msg); logger.info(msg); logger.warn(msg); logger.error(msg); logger.fatal(msg); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new LevelMatchFilterTestCase("accept")); suite.addTest(new LevelMatchFilterTestCase("deny")); return suite; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/varia/ERFATestCase.java0000644000175000017500000001021111751454671026011 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.varia; import junit.framework.TestCase; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.RFATestCase; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.net.Socket; /** * Test of ExternallyRolledFileAppender. * * @author Curt Arnold */ public class ERFATestCase extends TestCase { /** * Create new instance of test. * @param name test name. */ public ERFATestCase(final String name) { super(name); } /** * Reset configuration after test. */ public void tearDown() { LogManager.resetConfiguration(); } /** * Test ExternallyRolledFileAppender constructor. */ public void testConstructor() { ExternallyRolledFileAppender appender = new ExternallyRolledFileAppender(); assertEquals(0, appender.getPort()); } /** * Send a message to the ERFA. * @param port port number. * @param msg message, may not be null. * @param expectedResponse expected response, may not be null. * @throws IOException thrown on IO error. */ void sendMessage(int port, final String msg, final String expectedResponse) throws IOException { Socket socket = new Socket((String) null, port); DataInputStream reader = new DataInputStream(socket.getInputStream()); DataOutputStream writer = new DataOutputStream(socket.getOutputStream()); writer.writeUTF(msg); String response = reader.readUTF(); assertEquals(expectedResponse, response); reader.close(); writer.close(); socket.close(); } /** * Test externally triggered rollover. * @throws IOException thrown on IO error. */ public void testRollover() throws IOException { ExternallyRolledFileAppender erfa = new ExternallyRolledFileAppender(); int port = 5500; Logger logger = Logger.getLogger(RFATestCase.class); Logger root = Logger.getRootLogger(); PatternLayout layout = new PatternLayout("%m\n"); erfa.setLayout(layout); erfa.setAppend(false); erfa.setMaxBackupIndex(2); erfa.setPort(port); erfa.setFile("output/ERFA-test2.log"); try { erfa.activateOptions(); } catch(SecurityException ex) { return; } try { Thread.sleep(100); } catch(InterruptedException ex) { } root.addAppender(erfa); // Write exactly 10 bytes with each log for (int i = 0; i < 55; i++) { if (i < 10) { logger.debug("Hello---" + i); } else if (i < 100) { logger.debug("Hello--" + i); } if ((i % 10) == 9) { try { sendMessage(port, "RollOver", "OK"); } catch(SecurityException ex) { return; } } } try { sendMessage(port, "That's all folks.", "Expecting [RollOver] string."); } catch(SecurityException ex) { return; } assertTrue(new File("output/ERFA-test2.log").exists()); assertTrue(new File("output/ERFA-test2.log.1").exists()); assertTrue(new File("output/ERFA-test2.log.2").exists()); assertFalse(new File("output/ERFA-test2.log.3").exists()); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/varia/ErrorHandlerTestCase.java0000644000175000017500000000774711751454671027707 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.varia; import junit.framework.TestCase; import org.apache.log4j.Appender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.ErrorHandler; import org.apache.log4j.util.Filter; import org.apache.log4j.util.Transformer; import org.apache.log4j.util.Compare; import org.apache.log4j.util.JunitTestRunnerFilter; import org.apache.log4j.util.SunReflectFilter; import org.apache.log4j.util.LineNumberFilter; import org.apache.log4j.util.ControlFilter; import org.apache.log4j.xml.DOMConfigurator; import org.apache.log4j.PropertyConfigurator; public class ErrorHandlerTestCase extends TestCase { static String TEMP = "output/temp"; static String FILTERED = "output/filtered"; static String EXCEPTION1 = "java.lang.Exception: Just testing"; static String EXCEPTION2 = "\\s*at .*\\(.*\\)"; static String EXCEPTION3 = "\\s*at .*\\(Native Method\\)"; static String TEST1_PAT = "FALLBACK - (root|test) - Message \\d"; Logger root; Logger logger; public ErrorHandlerTestCase(String name) { super(name); } public void setUp() { root = Logger.getRootLogger(); logger = Logger.getLogger("test"); } public void tearDown() { root.getLoggerRepository().resetConfiguration(); } public void test1() throws Exception { DOMConfigurator.configure("input/xml/fallback1.xml"); Appender primary = root.getAppender("PRIMARY"); ErrorHandler eh = primary.getErrorHandler(); assertNotNull(eh); common(); ControlFilter cf = new ControlFilter(new String[]{TEST1_PAT, EXCEPTION1, EXCEPTION2, EXCEPTION3}); Transformer.transform(TEMP, FILTERED, new Filter[] {cf, new LineNumberFilter(), new JunitTestRunnerFilter(), new SunReflectFilter()}); assertTrue(Compare.compare(FILTERED, "witness/fallback1")); } public void test2() throws Exception { PropertyConfigurator.configure("input/fallback1.properties"); Appender primary = root.getAppender("PRIMARY"); ErrorHandler eh = primary.getErrorHandler(); assertNotNull(eh); common(); ControlFilter cf = new ControlFilter(new String[]{TEST1_PAT, EXCEPTION1, EXCEPTION2, EXCEPTION3}); Transformer.transform(TEMP, FILTERED, new Filter[] {cf, new LineNumberFilter(), new JunitTestRunnerFilter(), new SunReflectFilter()}); assertTrue(Compare.compare(FILTERED, "witness/fallback1")); } void common() { int i = -1; logger.debug("Message " + ++i); root.debug("Message " + i); logger.info ("Message " + ++i); root.info("Message " + i); logger.warn ("Message " + ++i); root.warn("Message " + i); logger.error("Message " + ++i); root.error("Message " + i); logger.log(Level.FATAL, "Message " + ++i); root.log(Level.FATAL, "Message " + i); Exception e = new Exception("Just testing"); logger.debug("Message " + ++i, e); root.debug("Message " + i, e); logger.error("Message " + ++i, e); root.error("Message " + i, e); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/xml/0000755000175000017500000000000012126647422022473 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/xml/XMLLayoutTestCase.java0000644000175000017500000001672211751454672026646 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.xml; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.log4j.FileAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.MDC; import org.apache.log4j.util.Compare; import org.apache.log4j.util.Filter; import org.apache.log4j.util.JunitTestRunnerFilter; import org.apache.log4j.util.LineNumberFilter; import org.apache.log4j.util.SunReflectFilter; import org.apache.log4j.util.Transformer; import org.apache.log4j.util.XMLLineAttributeFilter; import org.apache.log4j.util.XMLTimestampFilter; import java.util.Hashtable; public class XMLLayoutTestCase extends TestCase { static String TEMP = "output/temp"; static String FILTERED = "output/filtered"; Logger root; Logger logger; public XMLLayoutTestCase(String name) { super(name); } public void setUp() { root = Logger.getRootLogger(); root.setLevel(Level.TRACE); logger = Logger.getLogger(XMLLayoutTestCase.class); logger.setLevel(Level.TRACE); } public void tearDown() { root.getLoggerRepository().resetConfiguration(); } public void basic() throws Exception { XMLLayout xmlLayout = new XMLLayout(); root.addAppender(new FileAppender(xmlLayout, TEMP, false)); common(); Transformer.transform( TEMP, FILTERED, new Filter[] { new LineNumberFilter(), new XMLTimestampFilter(), new JunitTestRunnerFilter(), new SunReflectFilter() }); assertTrue(Compare.compare(FILTERED, "witness/xmlLayout.1")); } public void locationInfo() throws Exception { XMLLayout xmlLayout = new XMLLayout(); xmlLayout.setLocationInfo(true); root.addAppender(new FileAppender(xmlLayout, TEMP, false)); common(); Transformer.transform( TEMP, FILTERED, new Filter[] { new LineNumberFilter(), new XMLTimestampFilter(), new XMLLineAttributeFilter(), new JunitTestRunnerFilter(), new SunReflectFilter() }); assertTrue(Compare.compare(FILTERED, "witness/xmlLayout.2")); } public void testCDATA() throws Exception { XMLLayout xmlLayout = new XMLLayout(); xmlLayout.setLocationInfo(true); root.addAppender(new FileAppender(xmlLayout, TEMP, false)); String oldThreadName = Thread.currentThread().getName(); Thread.currentThread().setName("main"); logger.trace("Message with embedded hi]]>."); logger.debug("Message with embedded hi]]>."); Thread.currentThread().setName(oldThreadName); Transformer.transform( TEMP, FILTERED, new Filter[] { new LineNumberFilter(), new XMLTimestampFilter(), new XMLLineAttributeFilter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); Transformer.transform(TEMP, FILTERED, new Filter[] {new LineNumberFilter(), new XMLTimestampFilter(), new XMLLineAttributeFilter()}); assertTrue(Compare.compare(FILTERED, "witness/xmlLayout.3")); } public void testNull() throws Exception { XMLLayout xmlLayout = new XMLLayout(); root.addAppender(new FileAppender(xmlLayout, TEMP, false)); String oldThreadName = Thread.currentThread().getName(); Thread.currentThread().setName("main"); logger.debug("hi"); logger.debug(null); Exception e = new Exception((String) null); logger.debug("hi", e); Thread.currentThread().setName(oldThreadName); Transformer.transform( TEMP, FILTERED, new Filter[] { new LineNumberFilter(), new XMLTimestampFilter(), new JunitTestRunnerFilter(), new SunReflectFilter()}); assertTrue(Compare.compare(FILTERED, "witness/xmlLayout.null")); } /** * Tests the format of the MDC portion of the layout to ensure * the key-value pairs we put in turn up in the output file. * @throws Exception */ public void testMDC() throws Exception { XMLLayout xmlLayout = new XMLLayout(); xmlLayout.setProperties(true); root.addAppender(new FileAppender(xmlLayout, TEMP, false)); Hashtable context = MDC.getContext(); if (context != null) { context.clear(); } MDC.put("key1", "val1"); MDC.put("key2", "val2"); logger.debug("Hello"); Transformer.transform( TEMP, FILTERED, new Filter[] { new LineNumberFilter(), new JunitTestRunnerFilter(), new XMLTimestampFilter()}); assertTrue(Compare.compare(FILTERED, "witness/xmlLayout.mdc.1")); } public void testMDCEscaped() throws Exception { XMLLayout xmlLayout = new XMLLayout(); xmlLayout.setProperties(true); root.addAppender(new FileAppender(xmlLayout, TEMP, false)); Hashtable context = MDC.getContext(); if (context != null) { context.clear(); } MDC.put("blahAttribute", ""); MDC.put("", "blahValue"); logger.debug("Hello"); Transformer.transform( TEMP, FILTERED, new Filter[] { new LineNumberFilter(), new JunitTestRunnerFilter(), new XMLTimestampFilter() }); assertTrue(Compare.compare(FILTERED, "witness/xmlLayout.mdc.2")); } void common() { String oldThreadName = Thread.currentThread().getName(); Thread.currentThread().setName("main"); int i = -1; new X(); logger.trace("Message " + ++i); root.trace("Message " + i); logger.debug("Message " + ++i); root.debug("Message " + i); logger.info("Message " + ++i); root.info("Message " + i); logger.warn ("Message " + ++i); root.warn("Message " + i); logger.error("Message " + ++i); root.error("Message " + i); logger.log(Level.FATAL, "Message " + ++i); root.log(Level.FATAL, "Message " + i); Exception e = new Exception("Just testing"); logger.debug("Message " + ++i, e); root.debug("Message " + i, e); logger.error("Message " + ++i, e); root.error("Message " + i, e); Thread.currentThread().setName(oldThreadName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new XMLLayoutTestCase("basic")); suite.addTest(new XMLLayoutTestCase("locationInfo")); suite.addTest(new XMLLayoutTestCase("testCDATA")); suite.addTest(new XMLLayoutTestCase("testNull")); suite.addTest(new XMLLayoutTestCase("testMDC")); suite.addTest(new XMLLayoutTestCase("testMDCEscaped")); return suite; } class X { Logger logger = Logger.getLogger(X.class); public X() { logger.info("in X() constructor"); } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/xml/CustomLevelTestCase.java0000644000175000017500000000517311751454672027250 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.xml; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.log4j.Logger; import org.apache.log4j.util.Compare; public class CustomLevelTestCase extends TestCase { static String TEMP = "output/temp"; Logger root; Logger logger; public CustomLevelTestCase(String name) { super(name); } public void setUp() { root = Logger.getRootLogger(); logger = Logger.getLogger(CustomLevelTestCase.class); } public void tearDown() { root.getLoggerRepository().resetConfiguration(); } public void test1() throws Exception { DOMConfigurator.configure("input/xml/customLevel1.xml"); common(); assertTrue(Compare.compare(TEMP, "witness/customLevel.1")); } public void test2() throws Exception { DOMConfigurator.configure("input/xml/customLevel2.xml"); common(); assertTrue(Compare.compare(TEMP, "witness/customLevel.2")); } public void test3() throws Exception { DOMConfigurator.configure("input/xml/customLevel3.xml"); common(); assertTrue(Compare.compare(TEMP, "witness/customLevel.3")); } public void test4() throws Exception { DOMConfigurator.configure("input/xml/customLevel4.xml"); common(); assertTrue(Compare.compare(TEMP, "witness/customLevel.4")); } void common() { int i = 0; logger.debug("Message " + ++i); logger.info ("Message " + ++i); logger.warn ("Message " + ++i); logger.error("Message " + ++i); logger.log(XLevel.TRACE, "Message " + ++i); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new CustomLevelTestCase("test1")); suite.addTest(new CustomLevelTestCase("test2")); suite.addTest(new CustomLevelTestCase("test3")); suite.addTest(new CustomLevelTestCase("test4")); return suite; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/xml/DOMTestCase.java0000644000175000017500000003336111751454672025425 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.xml; import junit.framework.TestCase; import org.apache.log4j.Appender; import org.apache.log4j.FileAppender; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.VectorAppender; import org.apache.log4j.spi.ErrorHandler; import org.apache.log4j.spi.LoggerFactory; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.ThrowableRenderer; import org.apache.log4j.spi.OptionHandler; import org.apache.log4j.spi.ThrowableRendererSupport; import org.apache.log4j.util.Compare; import org.apache.log4j.util.ControlFilter; import org.apache.log4j.util.Filter; import org.apache.log4j.util.ISO8601Filter; import org.apache.log4j.util.JunitTestRunnerFilter; import org.apache.log4j.util.LineNumberFilter; import org.apache.log4j.util.SunReflectFilter; import org.apache.log4j.util.Transformer; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class DOMTestCase extends TestCase { static String TEMP_A1 = "output/temp.A1"; static String TEMP_A2 = "output/temp.A2"; static String FILTERED_A1 = "output/filtered.A1"; static String FILTERED_A2 = "output/filtered.A2"; static String EXCEPTION1 = "java.lang.Exception: Just testing"; static String EXCEPTION2 = "\\s*at .*\\(.*\\)"; static String EXCEPTION3 = "\\s*at .*\\(Native Method\\)"; static String EXCEPTION4 = "\\s*at .*\\(.*Compiled Code\\)"; static String EXCEPTION5 = "\\s*at .*\\(.*libgcj.*\\)"; static String TEST1_1A_PAT = "(TRACE|DEBUG|INFO |WARN |ERROR|FATAL) \\w*\\.\\w* - Message \\d"; static String TEST1_1B_PAT = "(TRACE|DEBUG|INFO |WARN |ERROR|FATAL) root - Message \\d"; static String TEST1_2_PAT = "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3} "+ "\\[main]\\ (TRACE|DEBUG|INFO|WARN|ERROR|FATAL) .* - Message \\d"; Logger root; Logger logger; public DOMTestCase(String name) { super(name); } public void setUp() { root = Logger.getRootLogger(); logger = Logger.getLogger(DOMTestCase.class); } public void tearDown() { root.getLoggerRepository().resetConfiguration(); } public void test1() throws Exception { DOMConfigurator.configure("input/xml/DOMTestCase1.xml"); common(); ControlFilter cf1 = new ControlFilter(new String[]{TEST1_1A_PAT, TEST1_1B_PAT, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); ControlFilter cf2 = new ControlFilter(new String[]{TEST1_2_PAT, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP_A1, FILTERED_A1, new Filter[] { cf1, new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); Transformer.transform( TEMP_A2, FILTERED_A2, new Filter[] { cf2, new LineNumberFilter(), new ISO8601Filter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); assertTrue(Compare.compare(FILTERED_A1, "witness/dom.A1.1")); assertTrue(Compare.compare(FILTERED_A2, "witness/dom.A2.1")); } /** * Tests processing of external entities in XML file. */ public void test4() throws Exception { DOMConfigurator.configure("input/xml/DOMTest4.xml"); common(); ControlFilter cf1 = new ControlFilter(new String[]{TEST1_1A_PAT, TEST1_1B_PAT, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); ControlFilter cf2 = new ControlFilter(new String[]{TEST1_2_PAT, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP_A1 + ".4", FILTERED_A1 + ".4", new Filter[] { cf1, new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); Transformer.transform( TEMP_A2 + ".4", FILTERED_A2 + ".4", new Filter[] { cf2, new LineNumberFilter(), new ISO8601Filter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); assertTrue(Compare.compare(FILTERED_A1 + ".4", "witness/dom.A1.4")); assertTrue(Compare.compare(FILTERED_A2 + ".4", "witness/dom.A2.4")); } void common() { String oldThreadName = Thread.currentThread().getName(); Thread.currentThread().setName("main"); int i = -1; logger.trace("Message " + ++i); root.trace("Message " + i); logger.debug("Message " + ++i); root.debug("Message " + i); logger.info ("Message " + ++i); root.info("Message " + i); logger.warn ("Message " + ++i); root.warn("Message " + i); logger.error("Message " + ++i); root.error("Message " + i); logger.log(Level.FATAL, "Message " + ++i); root.log(Level.FATAL, "Message " + i); Exception e = new Exception("Just testing"); logger.debug("Message " + ++i, e); root.debug("Message " + i, e); logger.error("Message " + ++i, e); root.error("Message " + i, e); Thread.currentThread().setName(oldThreadName); } /** * CustomLogger implementation for testCategoryFactory1 and 2. */ private static class CustomLogger extends Logger { /** * Creates new instance. * @param name logger name. */ public CustomLogger(final String name) { super(name); } } /** * Creates new instances of CustomLogger. */ public static class CustomLoggerFactory implements LoggerFactory { /** * Addivity, expected to be set false in configuration file. */ private boolean additivity; /** * Create new instance of factory. */ public CustomLoggerFactory() { additivity = true; } /** * Create new logger. * @param name logger name. * @return new logger. */ public Logger makeNewLoggerInstance(final String name) { Logger logger = new CustomLogger(name); assertFalse(additivity); return logger; } /** * Set additivity. * @param newVal new value of additivity. */ public void setAdditivity(final boolean newVal) { additivity = newVal; } } /** * CustomErrorHandler for testCategoryFactory2. */ public static class CustomErrorHandler implements ErrorHandler { public CustomErrorHandler() {} public void activateOptions() {} public void setLogger(final Logger logger) {} public void error(String message, Exception e, int errorCode) {} public void error(String message) {} public void error(String message, Exception e, int errorCode, LoggingEvent event) {} public void setAppender(Appender appender) {} public void setBackupAppender(Appender appender) {} } /** * Tests that loggers mentioned in logger elements * use the specified categoryFactory. See bug 33708. */ public void testCategoryFactory1() { DOMConfigurator.configure("input/xml/categoryfactory1.xml"); // // logger explicitly mentioned in configuration, // should be a CustomLogger Logger logger1 = Logger.getLogger("org.apache.log4j.xml.DOMTestCase.testCategoryFactory1.1"); assertTrue(logger1 instanceof CustomLogger); // // logger not explicitly mentioned in configuration, // should use default factory Logger logger2 = Logger.getLogger("org.apache.log4j.xml.DOMTestCase.testCategoryFactory1.2"); assertFalse(logger2 instanceof CustomLogger); } /** * Tests that loggers mentioned in logger-ref elements * use the specified categoryFactory. See bug 33708. */ public void testCategoryFactory2() { DOMConfigurator.configure("input/xml/categoryfactory2.xml"); // // logger explicitly mentioned in configuration, // should be a CustomLogger Logger logger1 = Logger.getLogger("org.apache.log4j.xml.DOMTestCase.testCategoryFactory2.1"); assertTrue(logger1 instanceof CustomLogger); // // logger not explicitly mentioned in configuration, // should use default factory Logger logger2 = Logger.getLogger("org.apache.log4j.xml.DOMTestCase.testCategoryFactory2.2"); assertFalse(logger2 instanceof CustomLogger); } /** * Tests that loggers mentioned in logger elements * use the specified loggerFactory. See bug 33708. */ public void testLoggerFactory1() { DOMConfigurator.configure("input/xml/loggerfactory1.xml"); // // logger explicitly mentioned in configuration, // should be a CustomLogger Logger logger1 = Logger.getLogger("org.apache.log4j.xml.DOMTestCase.testLoggerFactory1.1"); assertTrue(logger1 instanceof CustomLogger); // // logger not explicitly mentioned in configuration, // should use default factory Logger logger2 = Logger.getLogger("org.apache.log4j.xml.DOMTestCase.testLoggerFactory1.2"); assertFalse(logger2 instanceof CustomLogger); } /** * Tests that reset="true" on log4j:configuration element resets * repository before configuration. * @throws Exception thrown on error. */ public void testReset() throws Exception { VectorAppender appender = new VectorAppender(); appender.setName("V1"); Logger.getRootLogger().addAppender(appender); DOMConfigurator.configure("input/xml/testReset.xml"); assertNull(Logger.getRootLogger().getAppender("V1")); } /** * Test checks that configureAndWatch does initial configuration, see bug 33502. * @throws Exception if IO error. */ public void testConfigureAndWatch() throws Exception { DOMConfigurator.configureAndWatch("input/xml/DOMTestCase1.xml"); assertNotNull(Logger.getRootLogger().getAppender("A1")); } /** * This test checks that the subst method of an extending class * is checked when evaluating parameters. See bug 43325. * */ public void testOverrideSubst() { DOMConfigurator configurator = new DOMConfigurator() { protected String subst(final String value) { if ("output/temp.A1".equals(value)) { return "output/subst-test.A1"; } return value; } }; configurator.doConfigure("input/xml/DOMTestCase1.xml", LogManager.getLoggerRepository()); FileAppender a1 = (FileAppender) Logger.getRootLogger().getAppender("A1"); String file = a1.getFile(); assertEquals("output/subst-test.A1", file); } /** * Mock ThrowableRenderer for testThrowableRenderer. See bug 45721. */ public static class MockThrowableRenderer implements ThrowableRenderer, OptionHandler { private boolean activated = false; private boolean showVersion = true; public MockThrowableRenderer() { } public void activateOptions() { activated = true; } public boolean isActivated() { return activated; } public String[] doRender(final Throwable t) { return new String[0]; } public void setShowVersion(boolean v) { showVersion = v; } public boolean getShowVersion() { return showVersion; } } /** * Test of log4j.throwableRenderer support. See bug 45721. */ public void testThrowableRenderer1() { DOMConfigurator.configure("input/xml/throwableRenderer1.xml"); ThrowableRendererSupport repo = (ThrowableRendererSupport) LogManager.getLoggerRepository(); MockThrowableRenderer renderer = (MockThrowableRenderer) repo.getThrowableRenderer(); LogManager.resetConfiguration(); assertNotNull(renderer); assertEquals(true, renderer.isActivated()); assertEquals(false, renderer.getShowVersion()); } /** * Test for bug 47465. * configure(URL) did not close opened JarURLConnection. * @throws IOException if IOException creating properties jar. */ public void testJarURL() throws IOException { File input = new File("input/xml/defaultInit.xml"); System.out.println(input.getAbsolutePath()); InputStream is = new FileInputStream(input); File dir = new File("output"); dir.mkdirs(); File file = new File("output/xml.jar"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file)); zos.putNextEntry(new ZipEntry("log4j.xml")); int len; byte[] buf = new byte[1024]; while ((len = is.read(buf)) > 0) { zos.write(buf, 0, len); } zos.closeEntry(); zos.close(); URL url = new URL("jar:" + file.toURL() + "!/log4j.xml"); DOMConfigurator.configure(url); assertTrue(file.delete()); assertFalse(file.exists()); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/xml/XMLLayoutTest.java0000644000175000017500000003554311751454672026054 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.xml; import org.apache.log4j.Layout; import org.apache.log4j.LayoutTest; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.NDC; import org.apache.log4j.MDC; import org.apache.log4j.spi.LoggingEvent; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import java.io.Reader; import java.io.StringReader; import java.util.Hashtable; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; /** * Test for XMLLayout. * * @author Curt Arnold */ public class XMLLayoutTest extends LayoutTest { /** * Construct new instance of XMLLayoutTest. * * @param testName test name. */ public XMLLayoutTest(final String testName) { super(testName, "text/plain", false, null, null); } /** * Clear MDC and NDC before test. */ public void setUp() { NDC.clear(); if (MDC.getContext() != null) { MDC.getContext().clear(); } } /** * Clear MDC and NDC after test. */ public void tearDown() { setUp(); } /** * @{inheritDoc} */ protected Layout createLayout() { return new XMLLayout(); } /** * Parses the string as the body of an XML document and returns the document element. * @param source source string. * @return document element. * @throws Exception if parser can not be constructed or source is not a valid XML document. */ private Element parse(final String source) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false); factory.setCoalescing(true); DocumentBuilder builder = factory.newDocumentBuilder(); Reader reader = new StringReader(source); Document doc = builder.parse(new InputSource(reader)); return doc.getDocumentElement(); } /** * Checks a log4j:event element against expectations. * @param element element, may not be null. * @param event event, may not be null. */ private void checkEventElement( final Element element, final LoggingEvent event) { assertEquals("log4j:event", element.getTagName()); assertEquals( event.getLoggerName(), element.getAttribute("logger")); assertEquals( Long.toString(event.timeStamp), element.getAttribute("timestamp")); assertEquals(event.getLevel().toString(), element.getAttribute("level")); assertEquals(event.getThreadName(), element.getAttribute("thread")); } /** * Checks a log4j:message element against expectations. * @param element element, may not be null. * @param message expected message. */ private void checkMessageElement( final Element element, final String message) { assertEquals("log4j:message", element.getTagName()); Node messageNode = element.getFirstChild(); assertNotNull(messageNode); assertEquals(Node.TEXT_NODE, messageNode.getNodeType()); assertEquals(message, messageNode.getNodeValue()); assertNull(messageNode.getNextSibling()); } /** * Checks a log4j:message element against expectations. * @param element element, may not be null. * @param message expected message. */ private void checkNDCElement(final Element element, final String message) { assertEquals("log4j:NDC", element.getTagName()); Node messageNode = element.getFirstChild(); assertNotNull(messageNode); assertEquals(Node.TEXT_NODE, messageNode.getNodeType()); assertEquals(message, messageNode.getNodeValue()); assertNull(messageNode.getNextSibling()); } /** * Checks a log4j:throwable element against expectations. * @param element element, may not be null. * @param ex exception, may not be null. */ private void checkThrowableElement( final Element element, final Exception ex) { assertEquals("log4j:throwable", element.getTagName()); Node messageNode = element.getFirstChild(); assertNotNull(messageNode); assertEquals(Node.TEXT_NODE, messageNode.getNodeType()); String msg = ex.toString(); assertEquals(msg, messageNode.getNodeValue().substring(0, msg.length())); assertNull(messageNode.getNextSibling()); } /** * Checks a log4j:properties element against expectations. * @param element element, may not be null. * @param key key. * @param value value. */ private void checkPropertiesElement( final Element element, final String key, final String value) { assertEquals("log4j:properties", element.getTagName()); int childNodeCount = 0; for(Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) { if (child.getNodeType() == Node.ELEMENT_NODE) { assertEquals("log4j:data", child.getNodeName()); Element childElement = (Element) child; assertEquals(key, childElement.getAttribute("name")); assertEquals(value, childElement.getAttribute("value")); childNodeCount++; } } assertEquals(1, childNodeCount); } /** * Tests formatted results. * @throws Exception if parser can not be constructed or source is not a valid XML document. */ public void testFormat() throws Exception { Logger logger = Logger.getLogger("org.apache.log4j.xml.XMLLayoutTest"); LoggingEvent event = new LoggingEvent( "org.apache.log4j.Logger", logger, Level.INFO, "Hello, World", null); XMLLayout layout = (XMLLayout) createLayout(); String result = layout.format(event); Element parsedResult = parse(result); checkEventElement(parsedResult, event); int childElementCount = 0; for ( Node node = parsedResult.getFirstChild(); node != null; node = node.getNextSibling()) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: childElementCount++; checkMessageElement((Element) node, "Hello, World"); break; case Node.COMMENT_NODE: break; case Node.TEXT_NODE: // should only be whitespace break; default: fail("Unexpected node type"); break; } } assertEquals(1, childElementCount); } /** * Tests formatted results with an exception. * @throws Exception if parser can not be constructed or source is not a valid XML document. */ public void testFormatWithException() throws Exception { Logger logger = Logger.getLogger("org.apache.log4j.xml.XMLLayoutTest"); Exception ex = new IllegalArgumentException("'foo' is not a valid name"); LoggingEvent event = new LoggingEvent( "org.apache.log4j.Logger", logger, Level.INFO, "Hello, World", ex); XMLLayout layout = (XMLLayout) createLayout(); String result = layout.format(event); Element parsedResult = parse(result); checkEventElement(parsedResult, event); int childElementCount = 0; for ( Node node = parsedResult.getFirstChild(); node != null; node = node.getNextSibling()) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: childElementCount++; if (childElementCount == 1) { checkMessageElement((Element) node, "Hello, World"); } else { checkThrowableElement((Element) node, ex); } break; case Node.COMMENT_NODE: break; case Node.TEXT_NODE: // should only be whitespace break; default: fail("Unexpected node type"); break; } } assertEquals(2, childElementCount); } /** * Tests formatted results with an exception. * @throws Exception if parser can not be constructed or source is not a valid XML document. */ public void testFormatWithNDC() throws Exception { Logger logger = Logger.getLogger("org.apache.log4j.xml.XMLLayoutTest"); NDC.push("NDC goes here"); LoggingEvent event = new LoggingEvent( "org.apache.log4j.Logger", logger, Level.INFO, "Hello, World", null); XMLLayout layout = (XMLLayout) createLayout(); String result = layout.format(event); NDC.pop(); Element parsedResult = parse(result); checkEventElement(parsedResult, event); int childElementCount = 0; for ( Node node = parsedResult.getFirstChild(); node != null; node = node.getNextSibling()) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: childElementCount++; if (childElementCount == 1) { checkMessageElement((Element) node, "Hello, World"); } else { checkNDCElement((Element) node, "NDC goes here"); } break; case Node.COMMENT_NODE: break; case Node.TEXT_NODE: // should only be whitespace break; default: fail("Unexpected node type"); break; } } assertEquals(2, childElementCount); } /** * Tests getLocationInfo and setLocationInfo. */ public void testGetSetLocationInfo() { XMLLayout layout = new XMLLayout(); assertEquals(false, layout.getLocationInfo()); layout.setLocationInfo(true); assertEquals(true, layout.getLocationInfo()); layout.setLocationInfo(false); assertEquals(false, layout.getLocationInfo()); } /** * Tests activateOptions(). */ public void testActivateOptions() { XMLLayout layout = new XMLLayout(); layout.activateOptions(); } /** * Level with arbitrary toString value. */ private static final class ProblemLevel extends Level { private static final long serialVersionUID = 1L; /** * Construct new instance. * @param levelName level name, may not be null. */ public ProblemLevel(final String levelName) { super(6000, levelName, 6); } } /** * Tests problematic characters in multiple fields. * @throws Exception if parser can not be constructed or source is not a valid XML document. */ public void testProblemCharacters() throws Exception { String problemName = "com.example.bar<>&\"'"; Logger logger = Logger.getLogger(problemName); Level level = new ProblemLevel(problemName); Exception ex = new IllegalArgumentException(problemName); String threadName = Thread.currentThread().getName(); Thread.currentThread().setName(problemName); NDC.push(problemName); Hashtable mdcMap = MDC.getContext(); if (mdcMap != null) { mdcMap.clear(); } MDC.put(problemName, problemName); LoggingEvent event = new LoggingEvent( problemName, logger, level, problemName, ex); XMLLayout layout = (XMLLayout) createLayout(); layout.setProperties(true); String result = layout.format(event); mdcMap = MDC.getContext(); if (mdcMap != null) { mdcMap.clear(); } Thread.currentThread().setName(threadName); Element parsedResult = parse(result); checkEventElement(parsedResult, event); int childElementCount = 0; for ( Node node = parsedResult.getFirstChild(); node != null; node = node.getNextSibling()) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: childElementCount++; switch(childElementCount) { case 1: checkMessageElement((Element) node, problemName); break; case 2: checkNDCElement((Element) node, problemName); break; case 3: checkThrowableElement((Element) node, ex); break; case 4: checkPropertiesElement((Element) node, problemName, problemName); break; default: fail("Unexpected element"); break; } break; case Node.COMMENT_NODE: break; case Node.TEXT_NODE: // should only be whitespace break; default: fail("Unexpected node type"); break; } } } /** * Tests CDATA element within NDC content. See bug 37560. */ public void testNDCWithCDATA() throws Exception { Logger logger = Logger.getLogger("com.example.bar"); Level level = Level.INFO; String ndcMessage =""; NDC.push(ndcMessage); LoggingEvent event = new LoggingEvent( "com.example.bar", logger, level, "Hello, World", null); Layout layout = createLayout(); String result = layout.format(event); NDC.clear(); Element parsedResult = parse(result); NodeList ndcs = parsedResult.getElementsByTagName("log4j:NDC"); assertEquals(1, ndcs.getLength()); StringBuffer buf = new StringBuffer(); for(Node child = ndcs.item(0).getFirstChild(); child != null; child = child.getNextSibling()) { buf.append(child.getNodeValue()); } assertEquals(ndcMessage, buf.toString()); } /** * Tests CDATA element within exception. See bug 37560. */ public void testExceptionWithCDATA() throws Exception { Logger logger = Logger.getLogger("com.example.bar"); Level level = Level.INFO; String exceptionMessage =""; LoggingEvent event = new LoggingEvent( "com.example.bar", logger, level, "Hello, World", new Exception(exceptionMessage)); Layout layout = createLayout(); String result = layout.format(event); Element parsedResult = parse(result); NodeList throwables = parsedResult.getElementsByTagName("log4j:throwable"); assertEquals(1, throwables.getLength()); StringBuffer buf = new StringBuffer(); for(Node child = throwables.item(0).getFirstChild(); child != null; child = child.getNextSibling()) { buf.append(child.getNodeValue()); } assertTrue(buf.toString().indexOf(exceptionMessage) != -1); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/xml/XLevel.java0000644000175000017500000000460211751454672024545 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.xml; import org.apache.log4j.Level; /** This class introduces a new level level called TRACE. TRACE has lower level than DEBUG. */ public class XLevel extends Level { private static final long serialVersionUID = 7288304330257085144L; static public final int TRACE_INT = Level.DEBUG_INT - 1; static public final int LETHAL_INT = Level.FATAL_INT + 1; private static String TRACE_STR = "TRACE"; private static String LETHAL_STR = "LETHAL"; public static final XLevel TRACE = new XLevel(TRACE_INT, TRACE_STR, 7); public static final XLevel LETHAL = new XLevel(LETHAL_INT, LETHAL_STR, 0); protected XLevel(int level, String strLevel, int syslogEquiv) { super(level, strLevel, syslogEquiv); } /** Convert the string passed as argument to a level. If the conversion fails, then this method returns {@link #TRACE}. */ public static Level toLevel(String sArg) { return (Level) toLevel(sArg, XLevel.TRACE); } public static Level toLevel(String sArg, Level defaultValue) { if(sArg == null) { return defaultValue; } String stringVal = sArg.toUpperCase(); if(stringVal.equals(TRACE_STR)) { return XLevel.TRACE; } else if(stringVal.equals(LETHAL_STR)) { return XLevel.LETHAL; } return Level.toLevel(sArg, (Level) defaultValue); } public static Level toLevel(int i) throws IllegalArgumentException { switch(i) { case TRACE_INT: return XLevel.TRACE; case LETHAL_INT: return XLevel.LETHAL; } return Level.toLevel(i); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/VectorErrorHandler.java0000644000175000017500000000752211751454673026325 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.spi.ErrorHandler; import org.apache.log4j.spi.LoggingEvent; import java.util.Vector; /** * Utility class used in testing to capture errors dispatched * by appenders. * * @author Curt Arnold */ public final class VectorErrorHandler implements ErrorHandler { /** * Logger. */ private Logger logger; /** * Appender. */ private Appender appender; /** * Backup appender. */ private Appender backupAppender; /** * Array of processed errors. */ private final Vector errors = new Vector(); /** * Default constructor. */ public VectorErrorHandler() { } /** * {@inheritDoc} */ public void setLogger(final Logger logger) { this.logger = logger; } /** * Gets last logger specified by setLogger. * @return logger. */ public Logger getLogger() { return logger; } /** * {@inheritDoc} */ public void activateOptions() { } /** * {@inheritDoc} */ public void error( final String message, final Exception e, final int errorCode) { error(message, e, errorCode, null); } /** * {@inheritDoc} */ public void error(final String message) { error(message, null, -1, null); } /** * {@inheritDoc} */ public void error( final String message, final Exception e, final int errorCode, final LoggingEvent event) { errors.addElement( new Object[] { message, e, new Integer(errorCode), event }); } /** * Gets message from specified error. * * @param index index. * @return message, may be null. */ public String getMessage(final int index) { return (String) ((Object[]) errors.elementAt(index))[0]; } /** * Gets exception from specified error. * * @param index index. * @return exception. */ public Exception getException(final int index) { return (Exception) ((Object[]) errors.elementAt(index))[1]; } /** * Gets error code from specified error. * * @param index index. * @return error code, -1 if not specified. */ public int getErrorCode(final int index) { return ((Integer) ((Object[]) errors.elementAt(index))[2]).intValue(); } /** * Gets logging event from specified error. * * @param index index. * @return exception. */ public LoggingEvent getEvent(final int index) { return (LoggingEvent) ((Object[]) errors.elementAt(index))[3]; } /** * Gets number of errors captured. * @return number of errors captured. */ public int size() { return errors.size(); } /** * {@inheritDoc} */ public void setAppender(final Appender appender) { this.appender = appender; } /** * Get appender. * @return appender, may be null. */ public Appender getAppender() { return appender; } /** * {@inheritDoc} */ public void setBackupAppender(final Appender appender) { this.backupAppender = appender; } /** * Get backup appender. * @return backup appender, may be null. */ public Appender getBackupAppender() { return backupAppender; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/PriorityTest.java0000644000175000017500000001115511751454673025231 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; import java.util.Locale; /** * Tests of Priority. * * @author Curt Arnold * @since 1.2.14 */ public class PriorityTest extends TestCase { /** * Constructs new instance of test. * @param name test name. */ public PriorityTest(final String name) { super(name); } /** * Tests Priority.OFF_INT. */ public void testOffInt() { assertEquals(Integer.MAX_VALUE, Priority.OFF_INT); } /** * Tests Priority.FATAL_INT. */ public void testFatalInt() { assertEquals(50000, Priority.FATAL_INT); } /** * Tests Priority.ERROR_INT. */ public void testErrorInt() { assertEquals(40000, Priority.ERROR_INT); } /** * Tests Priority.WARN_INT. */ public void testWarnInt() { assertEquals(30000, Priority.WARN_INT); } /** * Tests Priority.INFO_INT. */ public void testInfoInt() { assertEquals(20000, Priority.INFO_INT); } /** * Tests Priority.DEBUG_INT. */ public void testDebugInt() { assertEquals(10000, Priority.DEBUG_INT); } /** * Tests Priority.ALL_INT. */ public void testAllInt() { assertEquals(Integer.MIN_VALUE, Priority.ALL_INT); } /** * Tests Priority.FATAL. * @deprecated */ public void testFatal() { assertTrue(Priority.FATAL instanceof Level); } /** * Tests Priority.ERROR. * @deprecated */ public void testERROR() { assertTrue(Priority.ERROR instanceof Level); } /** * Tests Priority.WARN. * @deprecated */ public void testWARN() { assertTrue(Priority.WARN instanceof Level); } /** * Tests Priority.INFO. * @deprecated */ public void testINFO() { assertTrue(Priority.INFO instanceof Level); } /** * Tests Priority.DEBUG. * @deprecated */ public void testDEBUG() { assertTrue(Priority.DEBUG instanceof Level); } /** * Tests Priority.equals(null). * @deprecated */ public void testEqualsNull() { assertFalse(Priority.DEBUG.equals(null)); } /** * Tests Priority.equals(Level.DEBUG). * @deprecated */ public void testEqualsLevel() { // // this behavior violates the equals contract. // assertTrue(Priority.DEBUG.equals(Level.DEBUG)); } /** * Tests getAllPossiblePriorities(). * @deprecated */ public void testGetAllPossiblePriorities() { Priority[] priorities = Priority.getAllPossiblePriorities(); assertEquals(5, priorities.length); } /** * Tests toPriority(String). * @deprecated */ public void testToPriorityString() { assertTrue(Priority.toPriority("DEBUG") == Level.DEBUG); } /** * Tests toPriority(int). * @deprecated */ public void testToPriorityInt() { assertTrue(Priority.toPriority(Priority.DEBUG_INT) == Level.DEBUG); } /** * Tests toPriority(String, Priority). * @deprecated */ public void testToPriorityStringPriority() { assertTrue(Priority.toPriority("foo", Priority.DEBUG) == Priority.DEBUG); } /** * Tests toPriority(int, Priority). * @deprecated */ public void testToPriorityIntPriority() { assertTrue(Priority.toPriority(17, Priority.DEBUG) == Priority.DEBUG); } /** * Test that dotless lower I + "nfo" is recognized as INFO. * @deprecated */ public void testDotlessLowerI() { Priority level = Priority.toPriority("\u0131nfo"); assertEquals("INFO", level.toString()); } /** * Test that dotted lower I + "nfo" is recognized as INFO * even in Turkish locale. * @deprecated */ public void testDottedLowerI() { Locale defaultLocale = Locale.getDefault(); Locale turkey = new Locale("tr", "TR"); Locale.setDefault(turkey); Priority level = Priority.toPriority("info"); Locale.setDefault(defaultLocale); assertEquals("INFO", level.toString()); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/CoreTestSuite.java0000644000175000017500000000610411751454673025310 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.log4j.spi.LoggingEventTest; /** * Suite of log4j class level unit tests. * */ public class CoreTestSuite { /** * Constructs test suite. * @return test suite */ public static Test suite() { TestSuite s = new TestSuite(); s.addTestSuite(LoggingEventTest.class); s.addTestSuite(org.apache.log4j.LevelTest.class); s.addTestSuite(org.apache.log4j.PriorityTest.class); s.addTestSuite(org.apache.log4j.CategoryTest.class); s.addTestSuite(org.apache.log4j.FileAppenderTest.class); s.addTestSuite(org.apache.log4j.LogManagerTest.class); s.addTestSuite(org.apache.log4j.helpers.LogLogTest.class); s.addTestSuite(org.apache.log4j.LayoutTest.class); s.addTestSuite(org.apache.log4j.helpers.DateLayoutTest.class); s.addTestSuite(org.apache.log4j.TTCCLayoutTest.class); s.addTestSuite(org.apache.log4j.xml.XMLLayoutTest.class); s.addTestSuite(org.apache.log4j.HTMLLayoutTest.class); s.addTestSuite(org.apache.log4j.PatternLayoutTest.class); s.addTestSuite(org.apache.log4j.spi.LoggingEventTest.class); s.addTestSuite(org.apache.log4j.spi.ThrowableInformationTest.class); s.addTestSuite(org.apache.log4j.spi.LocationInfoTest.class); s.addTestSuite(org.apache.log4j.PropertyConfiguratorTest.class); s.addTestSuite(org.apache.log4j.net.SMTPAppenderTest.class); s.addTestSuite(org.apache.log4j.net.TelnetAppenderTest.class); s.addTestSuite(org.apache.log4j.DefaultThrowableRendererTest.class); s.addTestSuite(org.apache.log4j.EnhancedThrowableRendererTest.class); s.addTestSuite(org.apache.log4j.TestLogXF.class); s.addTestSuite(org.apache.log4j.TestLogMF.class); s.addTestSuite(org.apache.log4j.TestLogSF.class); s.addTestSuite(org.apache.log4j.pattern.CachedDateFormatTest.class); s.addTestSuite(org.apache.log4j.pattern.FormattingInfoTest.class); s.addTestSuite(org.apache.log4j.pattern.NameAbbreviatorTest.class); s.addTestSuite(org.apache.log4j.pattern.PatternParserTest.class); s.addTestSuite(org.apache.log4j.helpers.UtilLoggingLevelTest.class); return s; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/LayoutTest.java0000644000175000017500000001005511751454673024663 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; import org.apache.log4j.spi.LoggingEvent; /** * Tests for Layout. * */ public class LayoutTest extends TestCase { /** * Expected content type. */ private final String contentType; /** * Expected value for ignoresThrowable. */ private final boolean ignoresThrowable; /** * Expected value for header. */ private final String header; /** * Expected value for footer. */ private final String footer; /** * Construct a new instance of LayoutTest. * @param testName test name. */ public LayoutTest(final String testName) { super(testName); contentType = "text/plain"; ignoresThrowable = true; header = null; footer = null; } /** * Constructor for use by derived tests. * @param testName name of test. * @param expectedContentType expected value for getContentType(). * @param expectedIgnoresThrowable expected value for ignoresThrowable(). * @param expectedHeader expected value for getHeader(). * @param expectedFooter expected value for getFooter(). */ protected LayoutTest( final String testName, final String expectedContentType, final boolean expectedIgnoresThrowable, final String expectedHeader, final String expectedFooter) { super(testName); contentType = expectedContentType; ignoresThrowable = expectedIgnoresThrowable; header = expectedHeader; footer = expectedFooter; } /** * Tests Layout.LINE_SEP. */ public void testLineSep() { assertEquals(System.getProperty("line.separator"), Layout.LINE_SEP); } /** * Tests Layout.LINE_SEP. */ public void testLineSepLen() { assertEquals(Layout.LINE_SEP.length(), Layout.LINE_SEP_LEN); } /** * Creates layout for test. * @return new instance of Layout. */ protected Layout createLayout() { return new MockLayout(); } /** * Tests getContentType. */ public void testGetContentType() { assertEquals(contentType, createLayout().getContentType()); } /** * Tests ignoresThrowable. */ public void testIgnoresThrowable() { assertEquals(ignoresThrowable, createLayout().ignoresThrowable()); } /** * Tests getHeader. */ public void testGetHeader() { assertEquals(header, createLayout().getHeader()); } /** * Tests getFooter. */ public void testGetFooter() { assertEquals(footer, createLayout().getFooter()); } /** * Tests format. * @throws Exception derived tests, particular XMLLayoutTest, may throw exceptions. */ public void testFormat() throws Exception { Logger logger = Logger.getLogger("org.apache.log4j.LayoutTest"); LoggingEvent event = new LoggingEvent( "org.apache.log4j.Logger", logger, Level.INFO, "Hello, World", null); String result = createLayout().format(event); assertEquals("Mock", result); } /** * Concrete Layout class for tests. */ private static final class MockLayout extends Layout { /** * @{inheritDoc} */ public String format(final LoggingEvent event) { return "Mock"; } /** * @{inheritDoc} */ public void activateOptions() { } /** * @{inheritDoc} */ public boolean ignoresThrowable() { return true; } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/MyPatternParser.java0000644000175000017500000000444211751454673025651 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.helpers.FormattingInfo; import org.apache.log4j.helpers.PatternConverter; import org.apache.log4j.helpers.PatternParser; import org.apache.log4j.spi.LoggingEvent; /** Example showing how to extend PatternParser to recognize additional conversion characters. The examples shows that minimum and maximum width and alignment settings apply for "extension" conversion characters just as they do for PatternLayout recognized characters.

In this case MyPatternParser recognizes %# and outputs the value of an internal counter which is also incremented at each call. See source code for more details. @see org.apache.log4j.examples.MyPatternLayout @see org.apache.log4j.helpers.PatternParser @see org.apache.log4j.PatternLayout @author Anders Kristensen */ public class MyPatternParser extends PatternParser { int counter = 0; public MyPatternParser(String pattern) { super(pattern); } public void finalizeConverter(char c) { if (c == '#') { addConverter(new UserDirPatternConverter(formattingInfo)); currentLiteral.setLength(0); } else { super.finalizeConverter(c); } } private class UserDirPatternConverter extends PatternConverter { UserDirPatternConverter(FormattingInfo formattingInfo) { super(formattingInfo); } public String convert(LoggingEvent event) { return String.valueOf(++counter); } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/PropertyConfiguratorTest.java0000644000175000017500000002665411751454673027631 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.net.URL; import java.util.Properties; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import junit.framework.TestCase; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.OptionHandler; import org.apache.log4j.spi.ThrowableRenderer; import org.apache.log4j.spi.ThrowableRendererSupport; import org.apache.log4j.varia.LevelRangeFilter; /** * Test property configurator. * */ public class PropertyConfiguratorTest extends TestCase { public PropertyConfiguratorTest(final String testName) { super(testName); } /** * Test for bug 40944. * Did not catch IllegalArgumentException on Properties.load * and close input stream. * @throws IOException if IOException creating properties file. */ public void testBadUnicodeEscape() throws IOException { String fileName = "output/badescape.properties"; FileWriter writer = new FileWriter(fileName); writer.write("log4j.rootLogger=\\uXX41"); writer.close(); PropertyConfigurator.configure(fileName); File file = new File(fileName); assertTrue(file.delete()) ; assertFalse(file.exists()); } /** * Test for bug 40944. * configure(URL) never closed opened stream. * @throws IOException if IOException creating properties file. */ public void testURL() throws IOException { File file = new File("output/unclosed.properties"); FileWriter writer = new FileWriter(file); writer.write("log4j.rootLogger=debug"); writer.close(); URL url = file.toURL(); PropertyConfigurator.configure(url); assertTrue(file.delete()); assertFalse(file.exists()); } /** * Test for bug 40944. * configure(URL) did not catch IllegalArgumentException and * did not close stream. * @throws IOException if IOException creating properties file. */ public void testURLBadEscape() throws IOException { File file = new File("output/urlbadescape.properties"); FileWriter writer = new FileWriter(file); writer.write("log4j.rootLogger=\\uXX41"); writer.close(); URL url = file.toURL(); PropertyConfigurator.configure(url); assertTrue(file.delete()); assertFalse(file.exists()); } /** * Tests configuring Log4J from an InputStream. * * @since 1.2.17 */ public void testInputStream() throws IOException { File file = new File("input/filter1.properties"); assertTrue(file.exists()); FileInputStream inputStream = new FileInputStream(file); try { PropertyConfigurator.configure(inputStream); } finally { inputStream.close(); } this.validateNested(); LogManager.resetConfiguration(); } public void validateNested() { RollingFileAppender rfa = (RollingFileAppender) Logger.getLogger("org.apache.log4j.PropertyConfiguratorTest") .getAppender("ROLLING"); FixedWindowRollingPolicy rollingPolicy = (FixedWindowRollingPolicy) rfa.getRollingPolicy(); assertEquals("filterBase-test1.log", rollingPolicy.getActiveFileName()); assertEquals("filterBased-test1.%i", rollingPolicy.getFileNamePattern()); assertEquals(0, rollingPolicy.getMinIndex()); assertTrue(rollingPolicy.isActivated()); FilterBasedTriggeringPolicy triggeringPolicy = (FilterBasedTriggeringPolicy) rfa.getTriggeringPolicy(); LevelRangeFilter filter = (LevelRangeFilter) triggeringPolicy.getFilter(); assertTrue(Level.INFO.equals(filter.getLevelMin())); } /** * Test for bug 47465. * configure(URL) did not close opened JarURLConnection. * @throws IOException if IOException creating properties jar. */ public void testJarURL() throws IOException { File dir = new File("output"); dir.mkdirs(); File file = new File("output/properties.jar"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file)); zos.putNextEntry(new ZipEntry(LogManager.DEFAULT_CONFIGURATION_FILE)); zos.write("log4j.rootLogger=debug".getBytes()); zos.closeEntry(); zos.close(); URL url = new URL("jar:" + file.toURL() + "!/" + LogManager.DEFAULT_CONFIGURATION_FILE); PropertyConfigurator.configure(url); assertTrue(file.delete()); assertFalse(file.exists()); } /** * Test processing of log4j.reset property, see bug 17531. * */ public void testReset() { VectorAppender appender = new VectorAppender(); appender.setName("A1"); Logger.getRootLogger().addAppender(appender); Properties props = new Properties(); props.put("log4j.reset", "true"); PropertyConfigurator.configure(props); assertNull(Logger.getRootLogger().getAppender("A1")); LogManager.resetConfiguration(); } /** * Mock definition of org.apache.log4j.rolling.RollingPolicy * from extras companion. */ public static class RollingPolicy implements OptionHandler { private boolean activated = false; public RollingPolicy() { } public void activateOptions() { activated = true; } public final boolean isActivated() { return activated; } } /** * Mock definition of FixedWindowRollingPolicy from extras companion. */ public static final class FixedWindowRollingPolicy extends RollingPolicy { private String activeFileName; private String fileNamePattern; private int minIndex; public FixedWindowRollingPolicy() { minIndex = -1; } public String getActiveFileName() { return activeFileName; } public void setActiveFileName(final String val) { activeFileName = val; } public String getFileNamePattern() { return fileNamePattern; } public void setFileNamePattern(final String val) { fileNamePattern = val; } public int getMinIndex() { return minIndex; } public void setMinIndex(final int val) { minIndex = val; } } /** * Mock definition of TriggeringPolicy from extras companion. */ public static class TriggeringPolicy implements OptionHandler { private boolean activated = false; public TriggeringPolicy() { } public void activateOptions() { activated = true; } public final boolean isActivated() { return activated; } } /** * Mock definition of FilterBasedTriggeringPolicy from extras companion. */ public static final class FilterBasedTriggeringPolicy extends TriggeringPolicy { private Filter filter; public FilterBasedTriggeringPolicy() { } public void setFilter(final Filter val) { filter = val; } public Filter getFilter() { return filter; } } /** * Mock definition of org.apache.log4j.rolling.RollingFileAppender * from extras companion. */ public static final class RollingFileAppender extends AppenderSkeleton { private RollingPolicy rollingPolicy; private TriggeringPolicy triggeringPolicy; private boolean append; public RollingFileAppender() { } public RollingPolicy getRollingPolicy() { return rollingPolicy; } public void setRollingPolicy(final RollingPolicy policy) { rollingPolicy = policy; } public TriggeringPolicy getTriggeringPolicy() { return triggeringPolicy; } public void setTriggeringPolicy(final TriggeringPolicy policy) { triggeringPolicy = policy; } public boolean getAppend() { return append; } public void setAppend(boolean val) { append = val; } public void close() { } public boolean requiresLayout() { return true; } public void append(final LoggingEvent event) { } } /** * Tests processing of nested objects, see bug 36384. */ public void testNested() { try { PropertyConfigurator.configure("input/filter1.properties"); this.validateNested(); } finally { LogManager.resetConfiguration(); } } /** * Mock ThrowableRenderer for testThrowableRenderer. See bug 45721. */ public static class MockThrowableRenderer implements ThrowableRenderer, OptionHandler { private boolean activated = false; private boolean showVersion = true; public MockThrowableRenderer() { } public void activateOptions() { activated = true; } public boolean isActivated() { return activated; } public String[] doRender(final Throwable t) { return new String[0]; } public void setShowVersion(boolean v) { showVersion = v; } public boolean getShowVersion() { return showVersion; } } /** * Test of log4j.throwableRenderer support. See bug 45721. */ public void testThrowableRenderer() { Properties props = new Properties(); props.put("log4j.throwableRenderer", "org.apache.log4j.PropertyConfiguratorTest$MockThrowableRenderer"); props.put("log4j.throwableRenderer.showVersion", "false"); PropertyConfigurator.configure(props); ThrowableRendererSupport repo = (ThrowableRendererSupport) LogManager.getLoggerRepository(); MockThrowableRenderer renderer = (MockThrowableRenderer) repo.getThrowableRenderer(); LogManager.resetConfiguration(); assertNotNull(renderer); assertEquals(true, renderer.isActivated()); assertEquals(false, renderer.getShowVersion()); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/PatternLayoutTestCase.java0000644000175000017500000003040711751454673027020 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; import org.apache.log4j.util.AbsoluteDateAndTimeFilter; import org.apache.log4j.util.AbsoluteTimeFilter; import org.apache.log4j.util.Compare; import org.apache.log4j.util.ControlFilter; import org.apache.log4j.util.Filter; import org.apache.log4j.util.ISO8601Filter; import org.apache.log4j.util.JunitTestRunnerFilter; import org.apache.log4j.util.LineNumberFilter; import org.apache.log4j.util.RelativeTimeFilter; import org.apache.log4j.util.SunReflectFilter; import org.apache.log4j.util.Transformer; public class PatternLayoutTestCase extends TestCase { static String TEMP = "output/temp"; static String FILTERED = "output/filtered"; Logger root; Logger logger; static String EXCEPTION1 = "java.lang.Exception: Just testing"; static String EXCEPTION2 = "\\s*at .*\\(.*\\)"; static String EXCEPTION3 = "\\s*at .*\\(Native Method\\)"; static String EXCEPTION4 = "\\s*at .*\\(.*Compiled Code\\)"; static String EXCEPTION5 = "\\s*at .*\\(.*libgcj.*\\)"; static String PAT0 = "\\[main]\\ (TRACE|DEBUG|INFO |WARN |ERROR|FATAL) .* - Message \\d{1,2}"; static String PAT1 = Filter.ISO8601_PAT + " " + PAT0; static String PAT2 = Filter.ABSOLUTE_DATE_AND_TIME_PAT+ " " + PAT0; static String PAT3 = Filter.ABSOLUTE_TIME_PAT+ " " + PAT0; static String PAT4 = Filter.RELATIVE_TIME_PAT+ " " + PAT0; static String PAT5 = "\\[main]\\ (TRACE|DEBUG|INFO |WARN |ERROR|FATAL) .* : Message \\d{1,2}"; static String PAT6 = "\\[main]\\ (TRACE|DEBUG|INFO |WARN |ERROR|FATAL) org.apache.log4j.PatternLayoutTestCase.common\\(PatternLayoutTestCase.java(:\\d{1,4})?\\): Message \\d{1,2}"; static String PAT11a = "^(TRACE|DEBUG|INFO |WARN |ERROR|FATAL) \\[main]\\ log4j.PatternLayoutTestCase: Message \\d{1,2}"; static String PAT11b = "^(TRACE|DEBUG|INFO |WARN |ERROR|FATAL) \\[main]\\ root: Message \\d{1,2}"; static String PAT12 = "^\\[main]\\ (TRACE|DEBUG|INFO |WARN |ERROR|FATAL) "+ "org.apache.log4j.PatternLayoutTestCase.common\\(PatternLayoutTestCase.java:\\d{3}\\): "+ "Message \\d{1,2}"; static String PAT13 = "^\\[main]\\ (TRACE|DEBUG|INFO |WARN |ERROR|FATAL) "+ "apache.log4j.PatternLayoutTestCase.common\\(PatternLayoutTestCase.java:\\d{3}\\): "+ "Message \\d{1,2}"; static String PAT14 = "^(TRACE|DEBUG| INFO| WARN|ERROR|FATAL)\\ \\d{1,2}\\ *- Message \\d{1,2}"; public PatternLayoutTestCase(String name) { super(name); } public void setUp() { root = Logger.getRootLogger(); logger = Logger.getLogger(PatternLayoutTestCase.class); } public void tearDown() { root.getLoggerRepository().resetConfiguration(); } public void test1() throws Exception { PropertyConfigurator.configure("input/patternLayout1.properties"); common(); Transformer.transform( TEMP, FILTERED, new Filter[] { new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); assertTrue(Compare.compare(FILTERED, "witness/patternLayout.1")); } public void test2() throws Exception { PropertyConfigurator.configure("input/patternLayout2.properties"); common(); ControlFilter cf1 = new ControlFilter(new String[]{PAT1, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new LineNumberFilter(), new ISO8601Filter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); assertTrue(Compare.compare(FILTERED, "witness/patternLayout.2")); } public void test3() throws Exception { PropertyConfigurator.configure("input/patternLayout3.properties"); common(); ControlFilter cf1 = new ControlFilter(new String[]{PAT1, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new LineNumberFilter(), new ISO8601Filter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); assertTrue(Compare.compare(FILTERED, "witness/patternLayout.3")); } // Output format: // 06 avr. 2002 18:30:58,937 [main] DEBUG rnLayoutTestCase - Message 0 public void test4() throws Exception { PropertyConfigurator.configure("input/patternLayout4.properties"); common(); ControlFilter cf1 = new ControlFilter(new String[]{PAT2, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new LineNumberFilter(), new AbsoluteDateAndTimeFilter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); assertTrue(Compare.compare(FILTERED, "witness/patternLayout.4")); } public void test5() throws Exception { PropertyConfigurator.configure("input/patternLayout5.properties"); common(); ControlFilter cf1 = new ControlFilter(new String[]{PAT2, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new LineNumberFilter(), new AbsoluteDateAndTimeFilter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); assertTrue(Compare.compare(FILTERED, "witness/patternLayout.5")); } // 18:54:19,201 [main] DEBUG rnLayoutTestCase - Message 0 public void test6() throws Exception { PropertyConfigurator.configure("input/patternLayout6.properties"); common(); ControlFilter cf1 = new ControlFilter(new String[]{PAT3, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new LineNumberFilter(), new AbsoluteTimeFilter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); assertTrue(Compare.compare(FILTERED, "witness/patternLayout.6")); } public void test7() throws Exception { PropertyConfigurator.configure("input/patternLayout7.properties"); common(); ControlFilter cf1 = new ControlFilter(new String[]{PAT3, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new LineNumberFilter(), new AbsoluteTimeFilter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); assertTrue(Compare.compare(FILTERED, "witness/patternLayout.7")); } public void test8() throws Exception { PropertyConfigurator.configure("input/patternLayout8.properties"); common(); ControlFilter cf1 = new ControlFilter(new String[]{PAT4, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new LineNumberFilter(), new RelativeTimeFilter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); assertTrue(Compare.compare(FILTERED, "witness/patternLayout.8")); } public void test9() throws Exception { PropertyConfigurator.configure("input/patternLayout9.properties"); common(); ControlFilter cf1 = new ControlFilter(new String[]{PAT5, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); assertTrue(Compare.compare(FILTERED, "witness/patternLayout.9")); } public void test10() throws Exception { PropertyConfigurator.configure("input/patternLayout10.properties"); common(); ControlFilter cf1 = new ControlFilter(new String[]{PAT6, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); assertTrue(Compare.compare(FILTERED, "witness/patternLayout.10")); } public void test11() throws Exception { PropertyConfigurator.configure("input/patternLayout11.properties"); common(); ControlFilter cf1 = new ControlFilter(new String[]{PAT11a, PAT11b, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); assertTrue(Compare.compare(FILTERED, "witness/patternLayout.11")); } public void test12() throws Exception { PropertyConfigurator.configure("input/patternLayout12.properties"); common(); ControlFilter cf1 = new ControlFilter(new String[]{PAT12, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); assertTrue(Compare.compare(FILTERED, "witness/patternLayout.12")); } public void test13() throws Exception { PropertyConfigurator.configure("input/patternLayout13.properties"); common(); ControlFilter cf1 = new ControlFilter(new String[]{PAT13, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); assertTrue(Compare.compare(FILTERED, "witness/patternLayout.13")); } public void test14() throws Exception { PropertyConfigurator.configure("input/patternLayout14.properties"); common(); ControlFilter cf1 = new ControlFilter(new String[]{PAT14, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5}); Transformer.transform( TEMP, FILTERED, new Filter[] { cf1, new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter() }); assertTrue(Compare.compare(FILTERED, "witness/patternLayout.14")); } public void testMDC1() throws Exception { PropertyConfigurator.configure("input/patternLayout.mdc.1.properties"); MDC.put("key1", "va11"); MDC.put("key2", "va12"); logger.debug("Hello World"); MDC.remove("key1"); MDC.remove("key2"); assertTrue(Compare.compare(TEMP, "witness/patternLayout.mdc.1")); } public void testMDCClear() throws Exception { PropertyConfigurator.configure("input/patternLayout.mdc.1.properties"); MDC.put("key1", "va11"); MDC.put("key2", "va12"); logger.debug("Hello World"); MDC.clear(); logger.debug("Hello World"); assertTrue(Compare.compare(TEMP, "witness/patternLayout.mdc.clear")); } void common() { String oldThreadName = Thread.currentThread().getName(); Thread.currentThread().setName("main"); int i = -1; logger.trace("Message " + ++i); root.trace("Message " + i); logger.debug("Message " + ++i); root.debug("Message " + i); logger.info ("Message " + ++i); root.info("Message " + i); logger.warn ("Message " + ++i); root.warn("Message " + i); logger.error("Message " + ++i); root.error("Message " + i); logger.log(Level.FATAL, "Message " + ++i); root.log(Level.FATAL, "Message " + i); Exception e = new Exception("Just testing"); logger.trace("Message " + ++i, e); logger.debug("Message " + ++i, e); logger.info("Message " + ++i, e); logger.warn("Message " + ++i , e); logger.error("Message " + ++i, e); logger.log(Level.FATAL, "Message " + ++i, e); Thread.currentThread().setName(oldThreadName); } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/PatternLayoutTest.java0000644000175000017500000000762111751454673026226 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.spi.LoggingEvent; /** * Test for PatternLayout. * * @author Curt Arnold */ public class PatternLayoutTest extends LayoutTest { /** * Construct new instance of PatternLayoutTest. * * @param testName test name. */ public PatternLayoutTest(final String testName) { super(testName, "text/plain", true, null, null); } /** * @{inheritDoc} */ protected Layout createLayout() { return new PatternLayout("[%t] %p %c - %m%n"); } /** * Tests format. */ public void testFormat() { Logger logger = Logger.getLogger("org.apache.log4j.LayoutTest"); LoggingEvent event = new LoggingEvent( "org.apache.log4j.Logger", logger, Level.INFO, "Hello, World", null); PatternLayout layout = (PatternLayout) createLayout(); String result = layout.format(event); StringBuffer buf = new StringBuffer(100); buf.append('['); buf.append(event.getThreadName()); buf.append("] "); buf.append(event.getLevel().toString()); buf.append(' '); buf.append(event.getLoggerName()); buf.append(" - "); buf.append(event.getMessage()); buf.append(System.getProperty("line.separator")); assertEquals(buf.toString(), result); } /** * Tests getPatternFormat(). */ public void testGetPatternFormat() { PatternLayout layout = (PatternLayout) createLayout(); assertEquals("[%t] %p %c - %m%n", layout.getConversionPattern()); } /** * Tests DEFAULT_CONVERSION_PATTERN constant. */ public void testDefaultConversionPattern() { assertEquals("%m%n", PatternLayout.DEFAULT_CONVERSION_PATTERN); } /** * Tests DEFAULT_CONVERSION_PATTERN constant. */ public void testTTCCConversionPattern() { assertEquals( "%r [%t] %p %c %x - %m%n", PatternLayout.TTCC_CONVERSION_PATTERN); } /** * Tests buffer downsizing code path. */ public void testFormatResize() { Logger logger = Logger.getLogger("org.apache.log4j.xml.PatternLayoutTest"); NDC.clear(); char[] msg = new char[2000]; for (int i = 0; i < msg.length; i++) { msg[i] = 'A'; } LoggingEvent event1 = new LoggingEvent( "org.apache.log4j.Logger", logger, Level.DEBUG, new String(msg), null); PatternLayout layout = (PatternLayout) createLayout(); String result = layout.format(event1); LoggingEvent event2 = new LoggingEvent( "org.apache.log4j.Logger", logger, Level.WARN, "Hello, World", null); result = layout.format(event2); assertEquals("[", result.substring(0, 1)); } /** * Class to ensure that protected members are still available. */ public static final class DerivedPatternLayout extends PatternLayout { /** * Constructs a new instance of DerivedPatternLayout. */ public DerivedPatternLayout() { } /** * Get BUF_SIZE. * @return return initial buffer size in characters. */ public int getBufSize() { return BUF_SIZE; } /** * Get MAX_CAPACITY. * @return maximum capacity in characters. */ public int getMaxCapacity() { return MAX_CAPACITY; } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/MDCTestCase.java0000644000175000017500000000645211751454673024613 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import java.lang.ref.Reference; import java.lang.reflect.Field; import java.lang.reflect.Method; import junit.framework.TestCase; /** * Test for MDC * * @author Maarten Bosteels */ public class MDCTestCase extends TestCase { public void setUp() { MDC.clear(); } public void tearDown() { MDC.clear(); } public void testPut() throws Exception { MDC.put("key", "some value"); assertEquals("some value", MDC.get("key")); assertEquals(1, MDC.getContext().size()); } public void testRemoveLastKey() throws Exception { MDC.put("key", "some value"); MDC.remove("key"); checkThreadLocalsForLeaks(); } private void checkThreadLocalsForLeaks() throws Exception { // this code is heavily based on code in org.apache.catalina.loader.WebappClassLoader // Make the fields in the Thread class that store ThreadLocals accessible Field threadLocalsField = Thread.class.getDeclaredField("threadLocals"); threadLocalsField.setAccessible(true); Field inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals"); inheritableThreadLocalsField.setAccessible(true); // Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects accessible Class tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap"); Field tableField = tlmClass.getDeclaredField("table"); tableField.setAccessible(true); Thread thread = Thread.currentThread(); Object threadLocalMap; threadLocalMap = threadLocalsField.get(thread); // Check the first map checkThreadLocalMapForLeaks(threadLocalMap, tableField); // Check the second map threadLocalMap = inheritableThreadLocalsField.get(thread); checkThreadLocalMapForLeaks(threadLocalMap, tableField); } private void checkThreadLocalMapForLeaks(Object map, Field internalTableField) throws IllegalAccessException, NoSuchFieldException { if (map != null) { Object[] table = (Object[]) internalTableField.get(map); if (table != null) { for (int j =0; j < table.length; j++) { if (table[j] != null) { // Check the key Object key = ((Reference) table[j]).get(); String keyClassName = key.getClass().getName(); if (key.getClass() == org.apache.log4j.helpers.ThreadLocalMap.class) { fail("Found a ThreadLocal with key of type [" + keyClassName + "]"); } } } } } } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/HierarchyThresholdTestCase.java0000644000175000017500000001000711751454673027772 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; import org.apache.log4j.util.Compare; import org.apache.log4j.xml.XLevel; /** Test the configuration of the hierarchy-wide threshold. @author Ceki Gülcü */ public class HierarchyThresholdTestCase extends TestCase { static String TEMP = "output/temp"; static Logger logger = Logger.getLogger(HierarchyThresholdTestCase.class); public HierarchyThresholdTestCase(String name) { super(name); } public void setUp() { } public void tearDown() { System.out.println("Tearing down test case."); logger.getLoggerRepository().resetConfiguration(); } public void test1() throws Exception { PropertyConfigurator.configure("input/hierarchyThreshold1.properties"); common(); assertTrue(Compare.compare(TEMP, "witness/hierarchyThreshold.1")); } public void test2() throws Exception { PropertyConfigurator.configure("input/hierarchyThreshold2.properties"); common(); assertTrue(Compare.compare(TEMP, "witness/hierarchyThreshold.2")); } public void test3() throws Exception { PropertyConfigurator.configure("input/hierarchyThreshold3.properties"); common(); assertTrue(Compare.compare(TEMP, "witness/hierarchyThreshold.3")); } public void test4() throws Exception { PropertyConfigurator.configure("input/hierarchyThreshold4.properties"); common(); assertTrue(Compare.compare(TEMP, "witness/hierarchyThreshold.4")); } public void test5() throws Exception { PropertyConfigurator.configure("input/hierarchyThreshold5.properties"); common(); assertTrue(Compare.compare(TEMP, "witness/hierarchyThreshold.5")); } public void test6() throws Exception { PropertyConfigurator.configure("input/hierarchyThreshold6.properties"); common(); assertTrue(Compare.compare(TEMP, "witness/hierarchyThreshold.6")); } public void test7() throws Exception { PropertyConfigurator.configure("input/hierarchyThreshold7.properties"); common(); assertTrue(Compare.compare(TEMP, "witness/hierarchyThreshold.7")); } public void test8() throws Exception { PropertyConfigurator.configure("input/hierarchyThreshold8.properties"); common(); assertTrue(Compare.compare(TEMP, "witness/hierarchyThreshold.8")); } static void common() { String oldThreadName = Thread.currentThread().getName(); Thread.currentThread().setName("main"); logger.log(XLevel.TRACE, "m0"); logger.debug("m1"); logger.info("m2"); logger.warn("m3"); logger.error("m4"); logger.fatal("m5"); Thread.currentThread().setName(oldThreadName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new HierarchyThresholdTestCase("test1")); suite.addTest(new HierarchyThresholdTestCase("test2")); suite.addTest(new HierarchyThresholdTestCase("test3")); suite.addTest(new HierarchyThresholdTestCase("test4")); suite.addTest(new HierarchyThresholdTestCase("test5")); suite.addTest(new HierarchyThresholdTestCase("test6")); suite.addTest(new HierarchyThresholdTestCase("test7")); suite.addTest(new HierarchyThresholdTestCase("test8")); return suite; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/defaultInit/0000755000175000017500000000000012126647422024143 5ustar tonytonyapache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/defaultInit/TestCase4.java0000644000175000017500000000336211751454672026617 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.defaultInit; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; import java.util.Enumeration; import org.apache.log4j.Appender; import org.apache.log4j.Logger; import org.apache.log4j.LogManager; public class TestCase4 extends TestCase { public TestCase4(String name) { super(name); } public void setUp() { } public void tearDown() { LogManager.shutdown(); } public void combinedTest() { Logger root = Logger.getRootLogger(); boolean rootIsConfigured = root.getAllAppenders().hasMoreElements(); assertTrue(rootIsConfigured); Enumeration e = root.getAllAppenders(); Appender appender = (Appender) e.nextElement(); assertEquals(appender.getName(), "D1"); assertEquals(e.hasMoreElements(), false); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new TestCase4("combinedTest")); return suite; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/defaultInit/TestCase2.java0000644000175000017500000000327211751454672026615 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.defaultInit; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; import java.util.Enumeration; import org.apache.log4j.Appender; import org.apache.log4j.Logger; import org.apache.log4j.LogManager; public class TestCase2 extends TestCase { public TestCase2(String name) { super(name); } public void setUp() { } public void tearDown() { LogManager.shutdown(); } public void xmlTest() { Logger root = Logger.getRootLogger(); boolean rootIsConfigured = root.getAllAppenders().hasMoreElements(); assertTrue(rootIsConfigured); Enumeration e = root.getAllAppenders(); Appender appender = (Appender) e.nextElement(); assertEquals(appender.getName(), "D1"); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new TestCase2("xmlTest")); return suite; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/defaultInit/TestCase3.java0000644000175000017500000000331011751454672026607 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.defaultInit; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; import java.util.Enumeration; import org.apache.log4j.Appender; import org.apache.log4j.Logger; import org.apache.log4j.LogManager; public class TestCase3 extends TestCase { public TestCase3(String name) { super(name); } public void setUp() { } public void tearDown() { LogManager.shutdown(); } public void propertiesTest() { Logger root = Logger.getRootLogger(); boolean rootIsConfigured = root.getAllAppenders().hasMoreElements(); assertTrue(rootIsConfigured); Enumeration e = root.getAllAppenders(); Appender appender = (Appender) e.nextElement(); assertEquals(appender.getName(), "D3"); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new TestCase3("propertiesTest")); return suite; } } apache-log4j1.2-1.2.17.orig/tests/src/java/org/apache/log4j/defaultInit/TestCase1.java0000644000175000017500000000276111751454672026616 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.defaultInit; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; import org.apache.log4j.Logger; import org.apache.log4j.LogManager; public class TestCase1 extends TestCase { public TestCase1(String name) { super(name); } public void setUp() { } public void tearDown() { LogManager.shutdown(); } public void noneTest() { Logger root = Logger.getRootLogger(); boolean rootIsConfigured = root.getAllAppenders().hasMoreElements(); assertTrue(!rootIsConfigured); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new TestCase1("noneTest")); return suite; } } apache-log4j1.2-1.2.17.orig/tests/sun_checks.xml0000644000175000017500000001043211751454673020012 0ustar tonytony apache-log4j1.2-1.2.17.orig/build.properties.sample0000644000175000017500000000500011751454714020465 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # # Providing a build.properties file is no longer # necessary for an Ant build as long as one Maven build # has previously been performed. # # base location of support directories # lib.home.dir=/java # The jaxp interface and a jaxp parser are required # to build the DOMConfigurator. # # modern equivalent is xml-commons-apis.jar # jaxp.home=${lib.home.dir}/crimson-1.1.3 jaxp.jaxp.jar=${jaxp.home}/crimson.jar # JavaMail API Required to build the SMTPAppender javamail.jar=${lib.home.dir}/javamail-1.3.2/mail.jar # and JavaBeans Activation Framework # http://java.sun.com/products/javabeans/jaf/index.jsp activation.jar=${lib.home.dir}/jaf-1.0.2/activation.jar # JMS interfaces are required to be on the classpath # in order to build the JMSAppender. jms.jar=${lib.home.dir}/jms1.1/lib/jms.jar # Required to build the org.apache.log4j.jmx package. jmx.home.dir=${lib.home.dir}/jmx-1_2_1-bin jmx.jar=${jmx.home.dir}/lib/jmxri.jar jndi.jar=${lib.home.dir}/jndi-1_2_1/lib/jndi.jar # Required to run Checkstyle. Available from http://checkstyle.sf.net checkstyle.jar=${lib.home.dir}/checkstyle-2.2/checkstyle-all-2.2.jar # Velocity's Anakia task is used in the generation of the documentation # download from http://jakarta.apache.org velocity.jar=${lib.home.dir}/velocity-1.4/velocity-dep-1.4.jar # Velocity's Anakia task requires JDOM, # but Velocity 1.4 is not compatible with JDOM 1.0, but beta 8 works okay # download for http://www.jdom.org/dist/binary/archive jdom.jar=${lib.home.dir}/jdom-b8/build/jdom.jar # # CLIRR binary compatibility checker # http://clirr.sourceforge.net clirr-core.jar=${lib.home.dir}/clirr-0.6/clirr-core-0.6.jar # bcel 5.1 will throw NullPointerExceptions bcel.jar=${lib.home.dir}/bcel-5.2/bcel-5.2.jar apache-log4j1.2-1.2.17.orig/KEYS0000644000175000017500000004274711751454714014511 0ustar tonytonyThis file contains the PGP&GPG keys of various Apache developers. This file contains the PGP&GPG keys of various Apache developers. Please don't use them for email unless you have to. Their main purpose is code signing. Apache users: pgp < KEYS Apache developers: (pgpk -ll && pgpk -xa ) >> this file. or (gpg --fingerprint --list-sigs && gpg --armor --export ) >> this file. Apache developers: please ensure that your key is also available via the PGP keyservers (such as pgpkeys.mit.edu). Type bits /keyID Date User ID pub 1024D/0C7C4F05 2005/06/10 Mark Dwayne Womack Mark Dwayne Womack -----BEGIN PGP PUBLIC KEY BLOCK----- Version: PGP Key Server 0.9.6 mQGiBEKqEj8RBADR8e9Xl0kFJqv8SspvDP8kUsivBxWVZz+HVKf0pL2wOie0LfsF E0Y3dI7k0k8i8KXtWYmHY3dpJGLUaruqIRxPFen/No56Q7udlK5hj7vKEUb46krx sLgik1s+WX8+61Yu5cLuGdqnfwRGuNV7uf3JF1Q78VXIyUlS4BFMXGtqjwCg//s6 1m7N3p8AtIgma+U13rEkq9cEAJ6l9eEPgOdRx53nKkCgkVpDxxhpbg90STQ1s94f rZIc+y5LN7FEERiQSiXvuzCwxiritiv+03sqdjYicxYZux+aladi0mHDIdgZkrAP MrRJ+8AKs7jv+WXcyaJcja8h3IZLShszgUM6uCW4Wr8mzZ+ns/65ihe4A/jS/Gu+ cD44A/9doNrvOnNXPD+N/R9ME3zS6FY8d5F6f8oxZOEsMll/AG1HhOR4yxOmZMOl +ZTg9AacHWMtTkjbs6JkT6uA8+tU+txoYjofkaGcJgq/SQYen89ifXZXVkUMWjqL ioUUKCsu4OQPnH5k3jCQp7DrkpDAgIBGZ5F3QGaYsrkVjxNoE7QnTWFyayBEd2F5 bmUgV29tYWNrIDxtd29tYWNrQGFwYWNoZS5vcmc+iEYEEBECAAYFAkKwy1kACgkQ vhbJXS4RQyKOYQCfddSBIMCd3kaFPvL90/piH/QIdIgAnRwG83V+KMRltnPRclDH IcTI5unMiQBOBBARAgAOBQJCqhI/BAsDAgECGQEACgkQErKHWAx8TwWGeACgnN9d jKDT2mjBKnApaDkMzmAaMvMAoKEcdBBCx62RPNIEBnxZ6zAxH244tC1NYXJrIER3 YXluZSBXb21hY2sgPG1hcmt3b21hY2tAd29tYWNrbmV0LmNvbT6IRgQQEQIABgUC QrDLXgAKCRC+FsldLhFDIgvLAJ9VsCFN6uBcObkb+UCN70ukHH5VWQCdEjPNvKCs c4+FGbTTsEoabhoNhsuJAEsEEBECAAsFAkKqFqUECwMCAQAKCRASsodYDHxPBeU1 AKDUIGqVzFZDXgK8PcLW8OlL2dXRmgCgwwxRkgpzuKNMnkphSZNend3VdJa5Ag0E QqoSPxAIAPZCV7cIfwgXcqK61qlC8wXo+VMROU+28W65Szgg2gGnVqMU6Y9AVfPQ B8bLQ6mUrfdMZIZJ+AyDvWXpF9Sh01D49Vlf3HZSTz09jdvOmeFXklnN/biudE/F /Ha8g8VHMGHOfMlm/xX5u/2RXscBqtNbno2gpXI61Brwv0YAWCvl9Ij9WE5J280g tJ3kkQc2azNsOA1FHQ98iLMcfFstjvbzySPAQ/ClWxiNjrtVjLhdONM0/XwXV0Oj HRhs3jMhLLUq/zzhsSlAGBGNfISnCnLWhsQDGcgHKXrKlQzZlp+r0ApQmwJG0wg9 ZqRdQZ+cfL2JSyIZJrqrol7DVekyCzsAAgIH/2A8l4YFI5dYs5ZV3OgspEh0Qa/N qd/JiVWBdygI77zp9TEgUtFBPDItEjmJq8sgnao0Cd5d68l9c+PQJ1xr4fOpdug0 YmYUgIaKutha3SSNRbD+T0WYmtTO5A4wxbsF3hYU7fvBJrt8gnO4tx6KAn/O2rRk wPfNTZ1EdnKttZDM2Mz4OiK0SsQ9mS7zP+HPx3kzdl1Oj0Vk2tUElD1R1hVjLa/o v5YgJCrwSD7RfCZAOEoPxXXN6StCqW1zT6HgcSR0clM5BC+ZyBJzczzD9I5+TrlH d3ISaCOuP5NeYQdTsQ446bjiNk7LT25gNHF6U6WjmLQ3lXCz4kNoBG6fiOKIRgQY EQIABgUCQqoSPwAKCRASsodYDHxPBQ7wAKD4DO0Se4+SvSqUKDfxhI0lJTgK0gCg 0lICv0KXT6PKyTndK+lr6K2AL4o= =GKga -----END PGP PUBLIC KEY BLOCK----- pub 1024D/2E114322 2005-06-11 [expires: 2010-06-10] Key fingerprint = A1A2 B554 6D43 31B2 A41E 1C07 BE16 C95D 2E11 4322 uid Curt Arnold sig 3 2E114322 2010-02-17 Curt Arnold sub 2048g/209ECE57 2005-06-11 [expires: 2010-06-10] sig 2E114322 2005-06-11 Curt Arnold pub 4096R/70C9C3D0 2010-02-17 [expires: 2012-02-17] Key fingerprint = 28F5 F554 39C7 1A8F 2B1E 58C4 D3EC 4990 70C9 C3D0 uid carnold@apache.org (CODE SIGNING KEY) sig 3 70C9C3D0 2010-02-17 carnold@apache.org (CODE SIGNING KEY) sig 2E114322 2010-02-17 Curt Arnold sub 4096R/0E434FF3 2010-02-17 [expires: 2012-02-17] sig 70C9C3D0 2010-02-17 carnold@apache.org (CODE SIGNING KEY) -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.14 (Darwin) mQGiBEKrSNQRBAC4J7udOBoC5+gVxBaPAbjXfnq12l5Pau1WD+UothePNGjI2hOp +Rnzikk3ISgyrjiX3A8ScZYbu3iXvMpF4zknkGLdmerpf4Gz9xGeushwun+UFaFL MX5u7LWJo9wDKzbcJJit1j/qGEg/HRp5fnVYCh0/l4dLansL60NhxtYdxwCguu2e wZMZFroaiIXqnce7+cGDRq8D/2HgKGtEJHY3z8OtUqncWbW+RAQqdcT0Z+bMB8o6 0UCHxUoJrFS1lA62qU3kcZ8ACPoh9xDW4X47EgNPELX81alymTI5FdqiDK7RIwzE JlOH/8JJgC6eSwiUXJ0cOJwpMonitcpMLouxuURuPSpfE5b1mQ1gFzN5MBL8xlZQ 8IO6A/9qWwyWyQBoJud0RDIsVRosdoSBZtw9PHsURgsqfNsS2NXTWK4HjxExw1KO AXmRlALfrH8yAShy/AyiUrwlKHG2WPTe6Etygjlr4dIxqTiCOoi+qv+H8SXW4Qy3 SnyozJ2RlKoYG0oDTbVMsPhOFdytHjConDLL9vS14j4kN9zWB7QgQ3VydCBBcm5v bGQgPGNhcm5vbGRAYXBhY2hlLm9yZz6IZwQTEQIAJwIbAwUJCWYBgAIeAQIXgAUC S3t0VgULCQgHAwUVCgkICwUWAgMBAAAKCRC+FsldLhFDIrS6AJ92lpskwBHNNWLw XsHLaFSGh9n9tACfT0dOv3wec7oM+lt2x81S0uqcbZq5Ag0EQqtJBRAIAN8maiGI O44Sdc9Ep3CAm0aXDeR8IQ/F253WcMQtkFBjeHEDd6/+EFT52vswMI6ZJDVV/A7p e4VMXAdNutFmUG2gy9OJOu8gMuO3jTCLxUXyQYNF/RasOAQJgc7q1N5QgKtXVH2I nQ21vHvlHM1fVe4rYDPr4JL2lZHe0P8kTzeQ7jI5pQnfYRJmS8I5AMQYFOiM48Pd 7SbsWu/rym7ikcmKUe6ZE59hSioneVP31CDMNRxCAQJVS1mZxTozsAEoh+cvmRjO D1Es0iXvu6Sfe8+sLRL+7CNUZgixE1UFbdnNxuZGlG9qs0LGP7hDWijT1/Y4SHz4 ovXxk0oocmFtiLcAAwcIAMbY7K99hLAFVaU2ukxCSp1TNPcD+IB3gtpRieKaZvBn /LGeCO+fNAogkw537lmpLk4nI+JiP/xWohyJ9lyEpW7yD4c9AHKNjqvEWD5Bhpnw 4qKJohQSVQwEeJRsftY4D0jCP9xbgPiq5woBzHWNok3BVaHqLK0fd0/+KygnT+k6 cR22Mus9RsEisXk9Oj5lvC0miDOWof4vk2Ll8/H3xt4CXAr13n5Yj2632HolOHrF UQXTgwc9v5CNIihOQMEiXFxHh743qbsUZktjxeYH7r8wSCV93/QQ4qELiWoUzndp kCRTlEKenucAv6f5qqZqG7pVW8S48T99HwzwqgFX5VOITwQYEQIADwUCQqtJBQIb DAUJCWYBgAAKCRC+FsldLhFDIjnoAJ9ECOIrTH3adnVLOkHZnewyp2ssxwCgtLjl wZ7/4QtL3W5Id3nKxPFiI+eZAg0ES3tyxgEQAMiGGFkj5EOkQv6EYFtWvd65Y6yn dpNIbOb/o9SszVu4kO1OHdemWg4OwXERb1+Ozl9NamOvW0ypH8qzFu4rhpoiUev0 DV93afBkhW6Mvd8D459okgnlfb/K7c3H72gHmuJKZkyNmLgyzX63BjgIbpjR83/N RC578BjoJbYCe0bKR9bCE+MxxCQzUO+tcUrk8o00zEhqycmw1B7gFLWL5MAf50h8 37/gbCcv9Q902kYfqsd5I7wPj4SRPnowN8vPlNtiwqMDqCl5rUmCrulfvSoNaJ/1 bEu7L9+/ptontfnr3kMJksGsoPo+Cf8xkGZL1D+80TxrBRf4CILQRF8dm+K8+4ms VMsPccCINw/AZh+GkIjJ+SfQpIE4Rx6OMd6JSmCuMnom4O8ZbJ9QYcuS1uf4r32M C6MQZrENvEFj1MaSZoRPXNdI/vwCKE5Hc1enB7bEHD6yayE3SgIGYVC+YPJkh0Ch fAANRSlw7arrL13UB6xwzAnzhIK7BzADsbGDMAMmIh+rvb6Xxb6iQCh/q7iGPpRz AXkmusLsbk6hMP4d8W5puJQTdy7a4t2DIX//9LYpl+DeYCww9DbXTwIays/WLnpo Jxj8R1G75gfUIC+kvFl+OiIOR7579yw5Ar35DmqG8RIwxW9cv+at3u63WhYwdhqB 4Dm5hujWYluYoAZvABEBAAG0OmNhcm5vbGRAYXBhY2hlLm9yZyAoQ09ERSBTSUdO SU5HIEtFWSkgPGNhcm5vbGRAYXBhY2hlLm9yZz6JAjwEEwEKACYFAkt7csYCGwMF CQPCZwAFCwkIBwMFFQoJCAsEFgIBAAIeAQIXgAAKCRDT7EmQcMnD0FNcD/oDWhmZ sikg42VV4SnaaIGUgjHoNT5NKWHhgeEXWAu44Y1r9X0+a6/xvtr69MfbExn9CJWJ 6vuyY9bpLcNNB49NLxhKD/IEpAUdGYcGGn1+AkkX/Sa7Y2SE5F9snJ2aSn+BctdP JNHgEQxWGXGHAFPEdw73RudqsDUvcIat+uU8H/ZdrXX1F2NiUp7rjHqYvizXgy5p Es99n00gCiz3eKg2l816v1ClDRAufFDj/JHghL4Yx+wUJN0cFBOAZHzDZgtcSUuv Jb2B2f31vjqJ5cGzSQ1KhRIqoIwUm+LYOtuCAbboW9P9GPbib6oavRXRbz/SAoIX BbYGWnA4aYQGT1r/FrLHZOmY6kw2izOPryXXxu1qAblFDc1C6XNHtNWx3uuTE/TL haePHai9N0rJLuJCwHSveY5Lc8LF6cE2sV+kFsyMUwzaxLHg4G2XpnVIx5mEM+Fr Hb89t8rThdE2n+qwUgCzlYgNEjAb1wf/xqUwXL7r/3rwKYkamq7Y7ljY9BTRX6VY XsDEiCPs2XSNQtZfTajkei/WN0/SJDQZfIbK9wPqQXTA4DxZ5qJaTa5hS/ueksYH tCK6pH3L8ov92ZbDcfxwq3u9wGl3GT1abFIfyfX53FXaoCXSi+g7F+a3hv6nmy0E 1zT26YXh3xRIPJ2x8gGCATHsGHabfnrRespQeYhGBBARCgAGBQJLe3TDAAoJEL4W yV0uEUMianUAn1+KjhbSeXIcMrxWK6WaCHojo0StAJ9GiDT+6t4AnRXCIJtob6uZ tN17tLkCDQRLe3LGARAAq9WmSZRtHLuOG8gmYesNeyfPqTdOgak+dgT4nnMIMnlN Y23k3oMIgSBeiYyFMDoTXPYsxVZW24mrMhi9D1XhsDygn534iD94ptrLpnDG+56z 0aHdGjS8eUhEK636uNLT47ZEm8997fWCiqQQzX7UP9ttP9DKLkseiZ97jtN5To+7 n5Kmog082k0208p2jJqVw9aqoeXh4520nRaqiD2QQg2onQLCAz7UH7RllVzhqH9Z G3HcI0RXw3q6FP33XlGNQuxhV9IPna9/43TXHaOsstwtJjvOaPfzGDS7BAmIKZx6 rbL7VYcIheZ+qXuVoRrwb0facxJfkTcLUy8aRQappDxk9FpWByEK2hEsWiw+CkI6 maFoyCvC/io5L3ZwWL3C+7wMZ1Qi8DvT93NbLboxhW5XRZk9gb1vlJSalTMbGNUV tOiV+SbwfkMQX1xOMFbDx2u5orcJ0h9/Ox1LJEuoTHx68nXLB1e9ioLfQPATM+70 JhXGAHmjp8rkY6Jdua0MbamQtUXfJAZv/pJrukWNWmT5UFYY0DNNcypfaqm0l4g9 ZFwwUaraWrMkcsrvmmZ+6JASSwA1a6RwXYLtsMLX0boaUKEvDPqnIbeF3jJnztLN MDWsGeW2NXYfuIaHMTUM7oVGgpDP+TG1IlOQU0lrSbw4Sm3AlA25tOF3jgGZtaMA EQEAAYkCJQQYAQoADwUCS3tyxgIbDAUJA8JnAAAKCRDT7EmQcMnD0MzLEACRQ6Em nkRbNupza9airUj2vrXj4I5ZN9jvgnvZcBVSmbKDEZR0akHFXaEes4d9AVh95y91 HuOHiiJ1hUZ0TGlk52ML5FEE68dDxvORUven9DiUdTAgLBJ5rUvfzj3tf6R4BNmM rzyEA0UCAthqTd1nCdjhwIT6z4BiEVGsBHVAN7mYl+blHqssvuRgNAWrdPFRGYJP cXI7wQc051WCHWXzi6b4h7oiIwlfsx7818S7ITHGM1AxTFl5rIqs9K4oHFTbcg1g sLbJFM0NJ4l1yQZG/9Vldo0RmDdMSc5KgwPa48nf8LHsL3qtcQuvy/b1CIhf8UqZ OWabhVa25xQFTRPmN5ND6wAsvx/zYr0/NF7RfJ3gTn8jCif8LZLVtYYP8zj4TgIL ZhP46YwxaLkyibh+7/R+obszGVt06yqefNYuzfAXpX+2/pDUVQ532AAVD5g4enX7 eAxMda//UAC+WxfCqE6c3CWhXlGaborCsP5auhBg0rbi3/dgPySwMugBfVksa16X X6y36kjw1MRZuhJi4WQGRLX4yjd6sGnWDoY5c/4G89JZKzjWsuNrSJIZRWrzgn84 NLAXpK81RMPkWukePN4ZQ1WEi0IH6AbBBbmQhIRR1bnGR48ZXH+/piJTNi9yKOPi wlp15dJcNo0puq0ZbuZjPboQjg8PQaGtlMVN6A== =EKia -----END PGP PUBLIC KEY BLOCK----- pub 4096R/F95275D4 2010-10-27 uid Scott Deboy (CODE SIGNING KEY) sig 3 F95275D4 2010-10-27 Scott Deboy (CODE SIGNING KEY) sub 4096R/FC1C7FAC 2010-10-27 sig F95275D4 2010-10-27 Scott Deboy (CODE SIGNING KEY) -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v2.0.13 (Darwin) mQINBEzHvBgBEACRXXPHv5LNRuQRjz2SkKjxMLmP+jqzKJ/iqbXjfdKSvfStI+8K 9F6HW7FFOvST14bhC6FIyVAJya8hm06ge2Qyg/VkxdxdI7A2rNZpqbF3mdohwJmk BtEbnU6KtLVV2kmi+U3aFwk8KEU6vbfta3XXd0oLWH5yDDaRhUUFmPqNQjp/Ivzc M2NwMf2lnJbAWwTpGrXmWOqeUaKaOg+wLQMjXoupDENRir7IOsIL0AAm84ghaLi/ MaVxBORnUsbq9mD9q7W6+0EFjun+Gh4WMualhTW1DZnZRFrCEcKkg5l5nM50DR40 KDlKcpvgDJFn+FIR8Bq3qVasqvsKCyI8FTYWtcUMUOOdCaowrRWRfvgrrUd07lrQ kzf2iH9POy1IMbk7Tx1Qhh9nSdZtLABeoFOQUoihsm6Gm2zohld/iNyTtDDW6WT1 92SatUz7qSDJ+qrhhc+O5FZYqzrmWAxJs+sHXkEUUtfEXEq0bdy/uh2uO4bm3WbK luXUXn6OJgGpICqtI5CiK1TwS2q8NHc9bFI4FF6drKE+bo/nz+q+ly67g3pa+Wtn /q6rTTqxcRF0yr4StxONrgSVMqderIbwlOuCtBodRnVciJBgr+zX2kblnIDLF3a1 qxcrdeMJ7bh7e3yMDmd+t+hoHnaRSMyhqBnFRpRJU7WQPxJNGrxy+H1djQARAQAB tDJTY290dCBEZWJveSAoQ09ERSBTSUdOSU5HIEtFWSkgPHNkZWJveUBhcGFjaGUu b3JnPokCNwQTAQoAIQUCTMe8GAIbAwULCQgHAwUVCgkICwUWAgMBAAIeAQIXgAAK CRDoZBtF+VJ11ONRD/wKr3kIhBzCfDqKv/vjWHj/5eAnLwT2SohWnnuqIJG7w+ES 4D0LBBvHJHd2ssGs/UpujFQppsZ16rWm7n1/sZH9YGlFyEXqTnssLwDGqZlUUPyy 5aETRzaanbtNV7tgc8lZCMv2wDheMiVPmgJ7nkAkd5oTEfoKnnMO31NGoxbqJ5WW 95hm/Mx9v16oub/wh1yEMOIgGeCfrM3M9tpYq3651fAcLLPnzl7Z8abPcelEUQK3 3Eo8CN3FZUizltDhutBCSlJgT1yt2x0LvvUJ9sKKN+uwRwDPmjaOsJIB8+L9FxSi nxAtUUDG4DpuB7ck0x8V+v9Ny4tgnnxtgP9kCuwL1IzJ4PjC5Jw3bVC1rwHKO0uU Sht/AUJV0lJLK3CISI+TfeKniOeIMrek424EqlPq0egrinNoS0T/3kF9GS14Oy9Q 8paGnOydMKjAg/e/2gNucG+bC44mZsxbwByKFwIXfplPaZaTxd6sHSIMUUTpe1tW vQi4a349kPs1DkO0nu8c1WOdieVoQ2pz753ASAgQfaLx0tjrabczrz5W1GdtzK0H uhrROlJR21M1W3YWglydUWETDaenOoGAkhQIFxZbae3PNf+T3lNrQztb3HSC4P/W QyhodEYrxKgKLnMWSQZWMPEFGgSguZt0+q5T1xOTvxfdTrKemFeanlESDb3Q4rkC DQRMx7wYARAA5M1zeDrEfVRc563s8WK95iAmrBoC+Ns9nuSHB5RSx+NFRUQATLvh sR3UYINQpgQu3YA+TJt+rv5G7UpsBXCZ1b87IBJ8wJqLYTY3lt48OFwdt88AxJuw xoDn06A78CNiqwJbRFV8MkaoZ2uNO+TVsFwfIF4J+zsTmbxcnW/oWoEP/stk9aH+ sLjIaWI/DeTNeCRsro50X3uojxeQ+xvSDIbgO+siZrvAcjdoI7PAgx5vQSn3P8tw hDGRokKm/Gxrww2s00SWTcI3jV/dhtHF+Rq2AJJOlwTpQ/gydJagioAgRd5gcRAa Lz5DmNV3ZzPtibXjxpO3BfCTXs8B5k4JSNP3XEw0gus2aB2fTUmHeS04MFo5dOOX njIpjqgruY6FPRT5UjwqT57a5XWdry0RrPQp6dqouDjs0rO+DB8Q3teniXqkkzIj bExKSapV1Lp9OIKNkMeDeJ7T/o39LntlVe0Tnh5tKQSsi3KwAFWdT/WgaSYn6j3+ 1nlD1f5RkWVGjbcG6PVWi3j8QBvuKYQV3kOFew5ryrNrKT9tsgoYFRpGEshxxbLI A+GnElaYm8CmaYlP+ddNzMxlFBT81zcqDes1ZhLRQbO14AYSJmrH8nsursoetzr0 H8lkpkYQYoSjfu2sbEI1DNJ/ODjtdgPKEm9Q1MIFpkS/VYVlSHIqsLcAEQEAAYkC HwQYAQoACQUCTMe8GAIbDAAKCRDoZBtF+VJ11BLMD/0QV+Tjh2fydHJ8AePWf+fR MoE3lPZmSVJLyWoH4qQp2eWrOojpHUHGOjs2UUCxKvvxP37ATwD2AGv3uVfXDACD KOD2UOB7fNrcBM26txI9hff+wUyJOx9LchRyfZFiXHXy0qm0j+pX4IgqxcWYNtJM Xpjc4G5MKZjvdaqsUJ0718ukTo/i4S2+bx3mqO14jr/O/AxKWRIK1IMKyIncV9YQ e9XX3bzBg1AC8CgnPqrsYZ64fcWk3AqsHoP9mkgD4cVsY4aVR+aUHrssWZoYb9mE 5Wgp59fggaldDIpa2SlNNzBl9m0KotRkGt73nVVMYzM4hUK810S9u41tAR4mJ+gj jAaIjMjLLnYU1suxmDm/+DNaAkZ8cpwvGBGWCfm638aYQL/FqANygWCcpWGaNkdN R73ZyGCSeWFBLrHM0OX26NiDgjYEtPi8V8TQ0th3qnWWUqkMTB3jUNUafHZnL56o 0PBtB/oOEW4qK31fjM/fnl86SItvZ276xhkrpzw1lHsvIi60Xzev2jdAbGZId73k XpZ88gue4SdRe2+hT2SVZepfZBIUPwK0Fc3SlvFmWLCM6NLrqB6HbfvKYxXtbKsk NR4RyqRdl9QfwiCNLqLnoaQ94KB/g2Ridc9NywQnmYF8hpCJcqtS382/dAe1+Dkm W/BEsu9SnUfOqLXtxR6Ayw== =N58I -----END PGP PUBLIC KEY BLOCK----- pub 4096R/B3D8E1BA 2009-11-05 Key fingerprint = 53C9 3582 1AA6 A755 BD33 7DB5 3595 395E B3D8 E1BA uid Ralph Goers (CODE SIGNING KEY) sig 3 B3D8E1BA 2009-11-05 Ralph Goers (CODE SIGNING KEY) sub 4096R/2910DD22 2009-11-05 sig B3D8E1BA 2009-11-05 Ralph Goers (CODE SIGNING KEY) -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.12 (Darwin) mQINBErygmoBEADbs8zVUn5ZwbsG3tqT4x6U7SZYOtd3WXOtHjuu9Cyp74rZ19Pi XNbYwIAoCgOI/nXVWwuOrNJH0pHaQ73slbNzLxo2ahQIkw9PbK4V3YXLai1r/W6T xU94s7WECoiH8uuRAZFwbei87/xwwTVnfwQjKBThom05LbOebtIGHkSg4Xl3b+Me 5iqHYiw/QOujiKOqm05s1aTWtm45KB3/u80/5y+2+/vn9HXor61gibDkC/oclDuj J1GYPCIAUvj95vw5n6Eq46I6aoed3BWCLD+qXBz3QJjwIKTYLOHO9iTCjPk1UmAq NQhrENV7eeahFIDgL+b9wsm6CwuH36B7cdobsOltqBegpMczM+kwTbeaVwyI+S6Y jQflqUclFctJCRxZYzUUL3C5X/yvb8Bj+WmoEjm3mSMEPUC+KwWeVGaXIrdw/yzX Vziqu+PVWZYovNKsLGlL5zUJt3nV0xmDJdPuLRgheIfB2t4oqn0Ki/PzMLQhhX9+ 9zWc9WD9V8cIZtiSs1hRny5Ns33nQr0KkdGOj1lfVcZVrDv64VUSzofH2nGEWS+f h9gkgD3aLHppt2XCH7tJK+wU/NlR5/0j+j3QwAfG5pziD0zMjvnKREfJ3aqqu9jj 8FgdJ5vJvo7hlq0zakD7qTUO0OJiELHcf8q0jfFdiqaocs4HZp1OO1w8hQARAQAB tDJSYWxwaCBHb2VycyAoQ09ERSBTSUdOSU5HIEtFWSkgPHJnb2Vyc0BhcGFjaGUu b3JnPokCNwQTAQoAIQUCSvKCagIbAwULCQgHAwUVCgkICwUWAgMBAAIeAQIXgAAK CRA1lTles9jhunOxEACwm5J1+TvPfwDA/HTKQcXwm8vfyAgf7HkUVoi1BRcJpqWn xa1KO3YIBj0luJkXw1D1LowLdH8/QHjjqxGliKqrKL+F7mDPlpuZ7mqj2JO+LUII OXMD8PLqjJ0rqaZ9u7IuWAHcFHoy+wApkqCQSFIMUTQREyoBgQiu2lgf4vGB3pEN O5Hsulky7BdWk/2v2ga1VdFBURh1Wykd4RLd6KLhonsnNe3CcParzzKTHG/JkTIT 4o7wZy0erv8UG4OBU3Db28Q4DiCCnwWb2LA0Az9eC7WRaIfA+Tx0x4PgtIhS20/3 GZp9C1DsTsHnIYy5KLhx9hReqiky0Hnkt9puLVWyhPdbG2K+7KZH8CX1elTrCLDP o25YwP1+xB9vmBoiKUwV60Ap5Jppup6k5CISfYzIE7wJ/pn7LXoE5m9H/rmWXQpq f4GrNvMOaAiXnvYR8N2qeQeMwYtbm/hZTk7mlrf1xgJ5aHq13T/jaxIbFBdvh32Y jPXNm53LcVf+H9uwy71dsmwCnnq6zxg83pBu2bpNb8d9MSg2MGT9yLdin3bvdnsy 9Kd4D08YcbdYyyby5FHpMFtqWSVvoCwsvztVE2bTC/ruR+AdZGl1+FxooqDhxeTF V3Sxf9zA7mVKZgVEdULvmi1gT91YAVp+GBg/FY6pf264wneqzKrWmdxG4oM6fLkC DQRK8oJqARAAzqD0AESdZa2wPgtiSQwRd+vn6YelEW52J3O9mP5HXVnQoVwJwikT eUAHWXiEFhGCp6RAo6kv1Jx/hOOpdcF0oPmHcxb6X1kxhqnZgs3DDPaKFfALQb7V Hr288GuIwVk09VY69gcFlWotidM5jSZ0N74rJmQJdbtaj9gyUz5+aW1YiuZ6IfFE 34j4psfvk3Db7RsQuGb7pmmFjQHXnBgcVo6h8N9un4P75hwer34sXDm9rutERzL1 MZMEuG7FE8SYDO+x6+pvlCSowSgo+SinzAM4f+4AEfCaOUv/Hw/dhL4dYi75XMI4 2B+mrD0+llfMKbMLofglRtxBA/oqgMkRAeg5LND+KoxqFBk6ztDrGjXIlf6TxPH5 MY2pkizyYVQGt3GgSXnz/LuzwmIQfZDmHe15QE6r+I06AY1ViICoMz7NiPdgfVS9 E3BlkPhs6OlsIgWE4pPnpuzuBo5CLQIHmMl+5IdJgFN+SNVV+4+stx4URMkaiUkc p0Mm8oupuyB28VG/fOpOqg1VBjFrFutYMja86mRY3Bg7Xg64Jj7dqoFXKjvPUfjx EuIamlEmNZM2n8pSsaPXPFAJG1H9y+yrVfa7L7ynAiqzWx8KrE3SnlKuEo/5ZVF3 xR1vdsJ38BCY+DYlzixVDaPM7qCBzCVGxVDZ6rPsEfwgBTPAGP2BzW0AEQEAAYkC HwQYAQoACQUCSvKCagIbDAAKCRA1lTles9jhulznD/oD95V8OrQuxY0+Af6DjLaZ ENjUcOhYElu+WNT9neH2bu0JLiO8y3ZjY1mT0XBHZaBnNKfhjfjSlQRO0ipojQ2c DQxnQ4gIkRn7Iz2wRcm6UJHOiCGR1w+DYAwVI/j33rrztg+yfpaET3s8k0wEOceW j8lb7WII7ek7xhIZ/d0hNFwy92/UnuuKSmDfFClIwTzPShy3CB0oFQR3SMbhquaI Z8+tOzYDDN9tQ00sO461VRgwmJ9fauieL/rLNRegigZrF0BYY4XusM1Bc2pXG/DV flePMoNQTx9J+dqx9Wk5SjEQ0dZsFwpz5WrweWMpNBhZaBkjfWL7EsYNChaN7n7u y8JgbO9FmRb4DPWvxk5otFqUv3fIPbt/X/XeFbV33eWp7kSDb9DL+YkXqBef4QLV BOBGeIJhQgm0rTKtxFl+YLuiFM167F56IHTnv9bKEv3Un1puPGgWnCpnF6zBx5Xg /3La4A01vkVydsb0P0Cx+ETPWCZzyRenut5dQLUAQEXz+G8HjdRf+aK824Mx4WAf pV8zkCkVae+se/txEFxedb/Y5jfejMqFX4M07ZuAydoFkeyCMaxin7WZI4ZUW1+s t7nSMQipZuv2XsTu6tbilQOccWm+5zILmBsSD7RT1+ek7F8ib130sFVsE4MKxXh0 DGLPEPiyStLVF41310m6rA== =LxkI -----END PGP PUBLIC KEY BLOCK----- pub 1024D/42196CA8 2009-05-05 uid Christian Grobmeier (Apache Codesigning) sig 3 42196CA8 2009-05-05 Christian Grobmeier (Apache Codesigning) sig 3 460FEEAA 2009-05-06 [User-ID nicht gefunden] sig P X 65D0FD58 2009-05-05 [User-ID nicht gefunden] sub 2048g/427473DA 2009-05-05 sig 42196CA8 2009-05-05 Christian Grobmeier (Apache Codesigning) -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.4.11 (Darwin) mQGiBEoAFh0RBACoIMutlZW5Isr0+btD/zsuxnCw5Ee2J+DANmA6Gvf4wiXPYw8X evehIDiitZFCB/imcxF+1Qr+30c/+2V/j8TrDAqrj4UvQ8ryyejfR8aPT31C4lYF +ktWT2PZA3ZOL03q8MtsLZiXdgRE5RwpUAGg2iAKlq4kx0RtDKJM3DHkQwCg9a7s erb8gudgyDo7vjmATzu9d5cD/imS3/8CPWHnIfQMQNFkniShm0XoVCuZfQASf4I7 ksRX+RfERc/RQ/vWoKW95DGupuBKm0KZYWjHgkd4NQcTvjtgVBpSksGuTg2dtY2R 96azS8Va0igUaUthZFCCD6TCHnOAsBCt47Fdv2ymlQiUZYXR1CPTkew/fXkBJJNw mtH2A/4mT16lRfma4n5uBpjNMRD4juW4hI7/7/QS7xol4Zb74i9rcYldWY3U6AGt lGUHeZ1ue9JZ+2SicJ25v+XAehbVsr+9NiiBqfOwGXij/d1UQTNsrsfvwYOC0foU zw0xQFW5lYqJ7romLcly42jSC/lDkACDrL6MfeT5LWPId/cMKrQ/Q2hyaXN0aWFu IEdyb2JtZWllciAoQXBhY2hlIENvZGVzaWduaW5nKSA8Z3JvYm1laWVyQGFwYWNo ZS5vcmc+iGAEExECACAFAkoAFh0CGwMGCwkIBwMCBBUCCAMEFgIDAQIeAQIXgAAK CRCG4CxaQhlsqK6wAKDLkpYfzS9kKqpEI9WAPYVW5prNLgCgmrZz7r8/bxUBloxL yK+fUQzwGoiIRgQTEQIABgUCSgFPqwAKCRDB1SNHRg/uqvlqAJ0QyWCwmm4w8YGj 4gHoyThA8YbARgCcDayOVtHZh8fSLT4BGLMbtSSqYVmIawQQEQIAKwUCSgAajgWD AeKFAB4aaHR0cDovL3d3dy5jYWNlcnQub3JnL2Nwcy5waHAACgkQ0rsNAWXQ/Vgc RQCfbryBlBcu3GZR08g3YvAtOEWFvKkAmwdDHEZYUvfc1KlBF8ckDIMgqyTMuQIN BEoAFh0QCADPnNYl1TZ5usGUhYd3L9mfgkP+gQTKQpdoR6B256Wk/D3gAgiHphdu oOykZdPGarR7pdNYXlmpJyF9z4im9y3GtYoqzjg3k81IuiKC3XJo5pTBskysqMfk r8/SvYTw3WkjnccxOy7/ZHTR95Kk4QE7v7ADuKM49vG6qqbrIjK5jQ8Xb9vuQjLr 2l2dlOcLnQB6+hyhPzGZpnt2OYMCmLFZyDXatJj3Rrh/Rmoz9jVyN2cVKk2Ho/+J tjzbfwjjJaBBUlAsZPQBnk+raAn4IeNqSSCrOokq4h5IFi9BQdrk6sV1PPQ00zxo RCUMA1YDmFmNSriqkpvrdsL3kVEUZct/AAMFCADNSCoj84hdKkXXO49G4Z2p0wX9 mNfaQbAUZx3Y74ph4BXAZsjgikpbml0MeZnrWt7H4P5NBAzRPQ2ChxT8QhYfNRay N102jNdnNkT3X3pfFrF/SDQq9lvqhjfYYz1vPY37tpdmW/IpOuER8b4EBw5V7HWe IIlcDpHYZvOFv3yuJr1MyHwN1f50FAoJc9ZNxee1cKgAZkR1ZE66iTpjiTqdNmKZ G8S6c1v6FLAB4ogFQmQ5WB7g2iQTDLj4k16suBFB9f3eSgtChg66dnOufYQgUCOT ReT5+FfYU/x1E5YO+XRYR/HBP9SImvO9E8E/+HRGfqf2IzHTF5mDfGsA0rk0iEkE GBECAAkFAkoAFh0CGwwACgkQhuAsWkIZbKjrlgCghD5yrAugimWHOYDtyKs53wcq VgUAoL1bX0lIWF44l1wm2/d0FeLEU0Qx =eW64 -----END PGP PUBLIC KEY BLOCK----- apache-log4j1.2-1.2.17.orig/LICENSE0000644000175000017500000002614611751454714015013 0ustar tonytony Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 1999-2005 The Apache Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. apache-log4j1.2-1.2.17.orig/src/0000755000175000017500000000000012126647422014561 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/ntdll/0000755000175000017500000000000012126647422015676 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/ntdll/build.xml0000755000175000017500000001527411751454713017535 0ustar tonytony -Dclasses.dir=/path/to/log4j/classes must be specified ${mingw-prefix}windres could not be found or failed, NTEventLogAppender.dll build skipped. ${jni.win32.include.dir}/jni_md.h not found, NTEventLogAppender.dll build skipped. -Dclasses.dir=/path/to/log4j/classes must be specified rc could not be found or failed, NTEventLogAppender.dll build skipped. apache-log4j1.2-1.2.17.orig/src/ntdll/NTEventLogAppender.rc0000755000175000017500000000777111751454713021711 0ustar tonytony// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // // // Message file include // LANGUAGE 0x9,0x1 1 11 MSG00001.bin // Microsoft Visual C++ generated resource script. // #include "windows.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // //#include "afxres.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // English (U.S.) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) #ifdef _WIN32 LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) #endif //_WIN32 #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE BEGIN "resource.h\0" END 2 TEXTINCLUDE BEGIN "#include ""afxres.h""\r\n" "\0" END 3 TEXTINCLUDE BEGIN "\r\n" "\0" END #endif // APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Version // VS_VERSION_INFO VERSIONINFO FILEVERSION 1, 2, 16, 1 PRODUCTVERSION 1, 2, 16, 1 FILEFLAGSMASK 0x17L #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS 0x4L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "CompanyName", "Apache Software Foundation" VALUE "FileDescription", "Platform methods for NTEventLogAppender" VALUE "FileVersion", "1, 2, 16, 1" VALUE "InternalName", "NTEventLogAppender" VALUE "LegalCopyright", "Licensed to the Apache Software Foundation (ASF) under one or more\ncontributor license agreements. See the NOTICE file distributed with\nthis work for additional information regarding copyright ownership.\nThe ASF licenses this file to You under the Apache License, Version 2.0\n(the ""License""); you may not use this file except in compliance with\nthe License. You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an ""AS IS"" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License." VALUE "OriginalFilename", "NTEventLogAppender.dll" VALUE "ProductName", "Apache log4j" VALUE "ProductVersion", "1, 2, 16, 1" VALUE "OLESelfRegister", "\0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END #endif // English (U.S.) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED apache-log4j1.2-1.2.17.orig/src/ntdll/NTEventLogAppender.def0000644000175000017500000000162011751454713022023 0ustar tonytony; ; Licensed to the Apache Software Foundation (ASF) under one or more ; contributor license agreements. See the NOTICE file distributed with ; this work for additional information regarding copyright ownership. ; The ASF licenses this file to You under the Apache License, Version 2.0 ; (the "License"); you may not use this file except in compliance with ; the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; LIBRARY "NTEventLogAppender" EXPORTS DllRegisterServer PRIVATE DllUnregisterServer PRIVATE apache-log4j1.2-1.2.17.orig/src/ntdll/nteventlog.cpp0000644000175000017500000002405711751454713020601 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef NtEventLogAppender_h #define NtEventLogAppender_h #ifdef __GNUC__ typedef long long __int64; #endif #include "org_apache_log4j_Priority.h" #include "org_apache_log4j_nt_NTEventLogAppender.h" #include #include HINSTANCE gModule = 0; class EventSourceMap { #if _WIN64 enum { MAX_SOURCES = 256 }; HANDLE* sources; public: EventSourceMap() { sources = (HANDLE*) calloc(MAX_SOURCES, sizeof(*sources)); } ~EventSourceMap() { free(sources); } jint createKey(HANDLE handle) { if (handle != 0) { // // find first available null entry (excluding sources[0]) // for(int i = 1; i < MAX_SOURCES; i++) { if (InterlockedCompareExchangePointer(sources + i, handle, 0) == 0) { return i; } } } return 0; } HANDLE getHandle(jint key) { if (key >= 1 && key < MAX_SOURCES) { return sources[key]; } return 0; } HANDLE releaseHandle(jint key) { if (key >= 1 && key < MAX_SOURCES) { return InterlockedExchangePointer(sources + key, 0); } return 0; } #else public: EventSourceMap() { } jint createKey(HANDLE handle) { return (jint) handle; } HANDLE getHandle(jint key) { return (HANDLE) key; } HANDLE releaseHandle(jint key) { return (HANDLE) key; } #endif } gEventSources; /* * Convert log4j Priority to an EventLog category. Each category is * backed by a message resource so that proper category names will * be displayed in the NT Event Viewer. */ WORD getCategory(jint priority) { WORD category = 1; if (priority >= org_apache_log4j_Priority_DEBUG_INT) { category = 2; if (priority >= org_apache_log4j_Priority_INFO_INT) { category = 3; if (priority >= org_apache_log4j_Priority_WARN_INT) { category = 4; if (priority >= org_apache_log4j_Priority_ERROR_INT) { category = 5; if (priority >= org_apache_log4j_Priority_FATAL_INT) { category = 6; } } } } } return category; } /* * Convert log4j Priority to an EventLog type. The log4j package * supports 8 defined priorites, but the NT EventLog only knows * 3 event types of interest to us: ERROR, WARNING, and INFO. */ WORD getType(jint priority) { WORD type = EVENTLOG_SUCCESS; if (priority >= org_apache_log4j_Priority_INFO_INT) { type = EVENTLOG_INFORMATION_TYPE; if (priority >= org_apache_log4j_Priority_WARN_INT) { type = EVENTLOG_WARNING_TYPE; if (priority >= org_apache_log4j_Priority_ERROR_INT) { type = EVENTLOG_ERROR_TYPE; } } } return type; } HKEY regGetKey(wchar_t *subkey, DWORD *disposition) { HKEY hkey = 0; RegCreateKeyExW(HKEY_LOCAL_MACHINE, subkey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &hkey, disposition); return hkey; } void regSetString(HKEY hkey, wchar_t *name, wchar_t *value) { RegSetValueExW(hkey, name, 0, REG_EXPAND_SZ, (LPBYTE)value, (wcslen(value) + 1) * sizeof(wchar_t)); } void regSetDword(HKEY hkey, wchar_t *name, DWORD value) { RegSetValueExW(hkey, name, 0, REG_DWORD, (LPBYTE)&value, sizeof(DWORD)); } /* * Add this source with appropriate configuration keys to the registry. */ void addRegistryInfo(wchar_t *source) { const wchar_t *prefix = L"SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\"; DWORD disposition; HKEY hkey = 0; wchar_t subkey[256]; wcscpy(subkey, prefix); wcscat(subkey, source); hkey = regGetKey(subkey, &disposition); if (disposition == REG_CREATED_NEW_KEY) { HMODULE hmodule = gModule; if (hmodule == NULL) { hmodule = GetModuleHandleW(L"NTEventLogAppender.dll"); } if (hmodule != NULL) { wchar_t modpath[_MAX_PATH]; DWORD modlen = GetModuleFileNameW(hmodule, modpath, _MAX_PATH - 1); if (modlen > 0) { modpath[modlen] = 0; regSetString(hkey, L"EventMessageFile", modpath); regSetString(hkey, L"CategoryMessageFile", modpath); } } regSetDword(hkey, L"TypesSupported", (DWORD)7); regSetDword(hkey, L"CategoryCount", (DWORD) 6); } RegCloseKey(hkey); return; } /* * Class: org.apache.log4j.nt.NTEventLogAppender * Method: registerEventSource * Signature: (Ljava/lang/String;Ljava/lang/String;)I */ JNIEXPORT jint JNICALL Java_org_apache_log4j_nt_NTEventLogAppender_registerEventSource( JNIEnv *env, jobject java_this, jstring server, jstring source) { jchar *nserver = 0; jchar *nsource = 0; if (server != 0) { jsize serverLen = env->GetStringLength(server); nserver = (jchar*) malloc((serverLen +1) * sizeof(jchar)); env->GetStringRegion(server, 0, serverLen, nserver); nserver[serverLen] = 0; } if (source != 0) { jsize sourceLen = env->GetStringLength(source); nsource = (jchar*) malloc((sourceLen +1) * sizeof(jchar)); env->GetStringRegion(source, 0, sourceLen, nsource); nsource[sourceLen] = 0; } addRegistryInfo((wchar_t*) nsource); jint handle = gEventSources.createKey(RegisterEventSourceW( (const wchar_t*) nserver, (const wchar_t*) nsource)); free(nserver); free(nsource); return handle; } /* * Class: org_apache_log4j_nt_NTEventLogAppender * Method: reportEvent * Signature: (ILjava/lang/String;I)V */ JNIEXPORT void JNICALL Java_org_apache_log4j_nt_NTEventLogAppender_reportEvent( JNIEnv *env, jobject java_this, jint jhandle, jstring jstr, jint priority) { jboolean localHandle = JNI_FALSE; HANDLE handle = gEventSources.getHandle(jhandle); if (handle == 0) { // Client didn't give us a handle so make a local one. handle = RegisterEventSourceW(NULL, L"Log4j"); localHandle = JNI_TRUE; } // convert Java String to character array jsize msgLen = env->GetStringLength(jstr); jchar* msg = (jchar*) malloc((msgLen + 1) * sizeof(jchar)); env->GetStringRegion(jstr, 0, msgLen, msg); msg[msgLen] = 0; // This is the only message supported by the package. It is backed by // a message resource which consists of just '%1' which is replaced // by the string we just created. const DWORD messageID = 0x1000; ReportEventW(handle, getType(priority), getCategory(priority), messageID, NULL, 1, 0, (const wchar_t**) &msg, NULL); free((void *)msg); if (localHandle == JNI_TRUE) { // Created the handle here so free it here too. DeregisterEventSource(handle); } return; } /* * Class: org_apache_log4j_nt_NTEventLogAppender * Method: deregisterEventSource * Signature: (I)V */ JNIEXPORT void JNICALL Java_org_apache_log4j_nt_NTEventLogAppender_deregisterEventSource( JNIEnv *env, jobject java_this, jint handle) { DeregisterEventSource(gEventSources.releaseHandle(handle)); } // // Entry point which registers default event source (Log4j) // when invoked using regsvr32 tool. // // extern "C" { __declspec(dllexport) HRESULT __stdcall DllRegisterServer(void) { HRESULT hr = E_FAIL; HMODULE hmodule = gModule; if (hmodule == NULL) { hmodule = GetModuleHandleW(L"NTEventLogAppender.dll"); } if (hmodule != NULL) { wchar_t modpath[_MAX_PATH]; DWORD modlen = GetModuleFileNameW(hmodule, modpath, _MAX_PATH - 1); if (modlen > 0) { modpath[modlen] = 0; const wchar_t key[] = L"SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\Log4j"; DWORD disposition; HKEY hkey = 0; LONG stat = RegCreateKeyExW(HKEY_LOCAL_MACHINE, key, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &hkey, &disposition); if (stat == ERROR_SUCCESS) { stat = RegSetValueExW(hkey, L"EventMessageFile", 0, REG_EXPAND_SZ, (LPBYTE) modpath, (wcslen(modpath) + 1) * sizeof(wchar_t)); if(stat == ERROR_SUCCESS) { stat = RegSetValueExW(hkey, L"CategoryMessageFile", 0, REG_EXPAND_SZ, (LPBYTE) modpath, (wcslen(modpath) + 1) * sizeof(wchar_t)); } if(stat == ERROR_SUCCESS) { DWORD value = 7; stat = RegSetValueExW(hkey, L"TypesSupported", 0, REG_DWORD, (LPBYTE)&value, sizeof(DWORD)); } if(stat == ERROR_SUCCESS) { DWORD value = 6; stat = RegSetValueExW(hkey, L"CategoryCount", 0, REG_DWORD, (LPBYTE)&value, sizeof(DWORD)); } LONG closeStat = RegCloseKey(hkey); if (stat == ERROR_SUCCESS && closeStat == ERROR_SUCCESS) { hr = S_OK; } } } } return hr; } // // Entry point which unregisters default event source (Log4j) // when invoked using regsvr32 tool with /u option. // // __declspec(dllexport) HRESULT __stdcall DllUnregisterServer(void) { LONG stat = RegDeleteKeyW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\Log4j"); return (stat == ERROR_SUCCESS || stat == ERROR_FILE_NOT_FOUND) ? S_OK : E_FAIL; } BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: gModule = hModule; break; case DLL_PROCESS_DETACH: gModule = 0; break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: break; } return TRUE; } } #endif apache-log4j1.2-1.2.17.orig/src/ntdll/EventLogCategories.mc0000644000175000017500000000203211751454713021747 0ustar tonytony; ; Licensed to the Apache Software Foundation (ASF) under one ; or more contributor license agreements. See the NOTICE file ; distributed with this work for additional information ; regarding copyright ownership. The ASF licenses this file ; to you under the Apache License, Version 2.0 (the ; "License"); you may not use this file except in compliance ; with the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, ; software distributed under the License is distributed on an ; "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ; KIND, either express or implied. See the License for the ; specific language governing permissions and limitations ; under the License. ; MessageId=1 Language=English Trace . MessageId=2 Language=English Debug . MessageId=3 Language=English Info . MessageId=4 Language=English Warn . MessageId=5 Language=English Error . MessageId=6 Language=English Fatal . MessageId=0x1000 Language=English %1 . apache-log4j1.2-1.2.17.orig/src/ntdll/MSG00001.bin0000644000175000017500000000024411751454713017401 0ustar tonytony”Trace Debug Info Warn Error Fatal %1 apache-log4j1.2-1.2.17.orig/src/main/0000755000175000017500000000000011751454711015505 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/resources/0000755000175000017500000000000011751454711017517 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/resources/org/0000755000175000017500000000000011751454711020306 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/resources/org/apache/0000755000175000017500000000000011751454711021527 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/resources/org/apache/log4j/0000755000175000017500000000000011751454712022547 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/resources/org/apache/log4j/lf5/0000755000175000017500000000000011751454712023235 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/resources/org/apache/log4j/lf5/config/0000755000175000017500000000000012126647422024501 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/resources/org/apache/log4j/lf5/config/defaultconfig.properties0000644000175000017500000000262711751454712031441 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # For the general syntax of property based configuration files see the # documenation of org.apache.log4j.PropertyConfigurator. # The root category uses the appender called A1. Since no priority is # specified, the root category assumes the default priority for root # which is DEBUG in log4j. The root category is the only category that # has a default priority. All other categories need not be assigned a # priority in which case they inherit their priority from the # hierarchy. log4j.rootCategory=, A1 # A1 is set to be a LogMonitorAppender which outputs to a swing # logging console. log4j.appender.A1=org.apache.log4j.lf5.LF5Appender apache-log4j1.2-1.2.17.orig/src/main/resources/org/apache/log4j/lf5/viewer/0000755000175000017500000000000011751454712024536 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/resources/org/apache/log4j/lf5/viewer/images/0000755000175000017500000000000012126647422026002 5ustar tonytony././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/resources/org/apache/log4j/lf5/viewer/images/channelexplorer_new.gifapache-log4j1.2-1.2.17.orig/src/main/resources/org/apache/log4j/lf5/viewer/images/channelexplorer_ne0000644000175000017500000000141211751454712031577 0ustar tonytonyGIF89aæÿÿÿÿÀÀÀÎËðÌÉî×ÔùÚ×üÉÇëÇÅéÎÌðÍËïÌÊîÛÙýÚØüØÖú¼ºáÂÀ濽ãÅÃéÏÍóÎÌòÈÆëÇÅêÆÄéÍËðÌÊïËÉîÊÈíÕÓøÓÑöÙ×üØÖû×Õú¶µÜ¼»âº¹à¹¸ßÄÃëÂÁè½¼ãÅÄëÀ¿åÊÉðÉÈïÈÇíÄÃéÎÍóÅÄéÑÐöÌËðÉÈìÈÇëÕÔùÒÑöÐÏôÍÌðÊÉíÖÕùÚÙýØ×û×ÖúÚÙü×ÖùžžÈ¨¨ÒÃÃò¯¯Ù²²Ü­­Õ¸¸á··à²²Ú±±Ø¯¯Ö´´Û³³Ú¾¾æ¸¸ß··ÝÀÀ翿澾弼ãÃÃêÂÂé½½ã¼¼áÆÆìÂÂèÃÃèÐÐõÏÏôÓÓ÷š›ÅŸ Ê¤¥ÏŸ É¥¦Ðª«Õ¦§Ð±²Ü­®Ø­®Öª«Ó©ªÒ´µÞ°±Ø¯°×º»ã¹ºâ™›Ä¤¦Ð ¢Ë¨ªÔ¯±Û©«Ôµ·ßòòò³³³ !ù,ÿ€‚ƒ„…†‡ˆ‰ˆwŒŽŠ‚u•—–u’wuonq?e_i”uw’”]s`BatDwA”Šb^rcFfQK²´Š”pd@EILJ("²‰ChmkP!W'͉”gljON,[/4 Œ‹uRH&M+)Z> : ·”GT$*0fðÀÀàÆ‡Z‡:•K‡;0PA>C”¬PÈÂeƒ‡ 2ä¤.a8hh0€!Â\ÈA G‚8Ààlg¡N 2Ü3 £Æ$Á6¢$ñÆŽ Z^&59ÑUt¦£iiZ¸x0EP¦¤•~Úyäè(LŸ†0aÒ)àÔ&¸’Ý-©4¯¡¾!þOCopyright 2000 by Sun Microsystems, Inc. All Rights Reserved. JLF GR Ver 1.0 ;././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/resources/org/apache/log4j/lf5/viewer/images/channelexplorer_satellite.gifapache-log4j1.2-1.2.17.orig/src/main/resources/org/apache/log4j/lf5/viewer/images/channelexplorer_sa0000644000175000017500000000040011751454712031574 0ustar tonytonyGIF89aÄÿÿÿ÷÷÷ðððèèèÞÞÞÕÕÕÌÌÌÅÅž¾¾´´´­­­¦¦¦™™™}}}sssfffYYYRRRJJJCCC)))þ!ù,} Žd96s˜f Š"ˆ†aV‰H$Â5’¤Q &’ÃÀ”hD G13ŽJD$l&F!bYuÅ%Fdû¨p= ¢¨T cIx1y ~% U"   E% ¢¤f,©ªª!;apache-log4j1.2-1.2.17.orig/src/main/resources/org/apache/log4j/lf5/viewer/images/lf5_small_icon.gif0000644000175000017500000000234111751454712031360 0ustar tonytonyGIF89a ÷«W"?+ßßß¿¿¿}}R¦¢Zêæ è¤:~[ Ò…:éÜp@@@€€€µ¤QÚÏlÚ…5ðŽ;+*ÌË„ÿÿÿ¦–HNN)ò»NľkÌÌÌ^^9Âo/ò프c)Ù³RFC#ç‰:“ŽIíãrX5# fff54øù’òÄXú£@YG PPPÌŸA˜M!¬}1 éØlïïïÙ;yv? õî†Ôx/ïé{™™™uG>6Üš3;*ò«<´³iî’:ãà‰úµAÚÐpúú¡—•X‰…Oò³H¯j,) Å‘8ñíŒT:NN3†Lò >‰Y$"^?èçy÷ßhõíx- ZV-˜i&ét/ú«;ùøŒÿÿ™<:!éª@ff3ÜØ{RJ!Ä3ä¸P??'òî›ò£8ÝÓm30éÞ|ú»IòÐhòçƒL:¯¦]èˆ4¯d)L4¶~,‡v;úœ<–^(QO*ð—?ï¥Bé”=ÉÅjþ!ùÿ, ÿH° Áƒ*\8F ˆ f̸ÐâFÁ,Tøá3¢Î0¸Ô A  €YhbÁˆ>V Pp´,XE!9–:B7E(ì,hbÄ% npãFéÒ‚<„ÐRÐMœ†W *ÑJT Ž9XX˶mÛS$ЩCÐK˜´nó²%(å'Á Õx@¸°aÂo°ÈCÐF`  4Ç šÇ‘%K©ÐŠç«Y³åf 5kbqŒ^ýÚÁíÞYãƒ` óϹ×E ȧƒP…@ø A$è ÃÏUÁ 8aÐ^xAaX2¼ðÔÆM¨Dq õpFIÄPt2làEC Á¢Aa@pÅ €ðàý tÁŒ2ÐÄF¨QAO aeHp„ЃYÔ@AW¨$P s¥j¬ù MÄÅÉ!ƒ æ©ç@;apache-log4j1.2-1.2.17.orig/src/main/resources/org/apache/log4j/xml/0000755000175000017500000000000012126647422023346 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/resources/org/apache/log4j/xml/log4j.dtd0000644000175000017500000001556411751454712025076 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/main/resources/META-INF/0000755000175000017500000000000012126647422020657 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/resources/META-INF/NOTICE0000644000175000017500000000024011751454711021557 0ustar tonytonyApache log4j Copyright 2007 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/).apache-log4j1.2-1.2.17.orig/src/main/resources/META-INF/LICENSE0000644000175000017500000002614611751454711021675 0ustar tonytony Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 1999-2005 The Apache Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. apache-log4j1.2-1.2.17.orig/src/main/javadoc/0000755000175000017500000000000011751454711017114 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/javadoc/org/0000755000175000017500000000000011751454711017703 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/javadoc/org/apache/0000755000175000017500000000000011751454711021124 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/javadoc/org/apache/log4j/0000755000175000017500000000000011751454711022143 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/javadoc/org/apache/log4j/xml/0000755000175000017500000000000011751454711022743 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/javadoc/org/apache/log4j/xml/examples/0000755000175000017500000000000012126647422024561 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/javadoc/org/apache/log4j/xml/examples/XMLSample.java0000644000175000017500000000405011751454711027225 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.xml.examples; import org.apache.log4j.xml.DOMConfigurator; import org.apache.log4j.Logger; /** This example code shows how to read an XML based configuration file using a DOM parser.

Sample XML files sample1.xml and sample2.xml are provided.

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 Logger cat = Logger.getLogger(XMLSample.class); public static void main(String argv[]) { if(argv.length == 1) init(argv[0]); else Usage("Wrong number of arguments."); sample(); } static void Usage(String msg) { System.err.println(msg); System.err.println( "Usage: java " + XMLSample.class.getName() + "configFile"); System.exit(1); } static void init(String configFile) { DOMConfigurator.configure(configFile); } static void sample() { int i = -1; cat.debug("Message " + ++i); cat.warn ("Message " + ++i); cat.error("Message " + ++i); Exception e = new Exception("Just testing"); cat.debug("Message " + ++i, e); } } apache-log4j1.2-1.2.17.orig/src/main/javadoc/org/apache/log4j/xml/examples/doc-files/0000755000175000017500000000000012126647422026426 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/javadoc/org/apache/log4j/xml/examples/doc-files/sample2.xml0000644000175000017500000000337011751454711030516 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/main/javadoc/org/apache/log4j/xml/examples/doc-files/XMLSample.java0000644000175000017500000000401211751454711031070 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.xml.examples; import org.apache.log4j.xml.DOMConfigurator; import org.apache.log4j.Logger; /** This example code shows how to read an XML based configuration file using a DOM parser.

Sample XML files sample1.xml and sample2.xml are provided.

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 Logger cat = Logger.getLogger(XMLSample.class); public static void main(String argv[]) { if(argv.length == 1) init(argv[0]); else Usage("Wrong number of arguments."); sample(); } static void Usage(String msg) { System.err.println(msg); System.err.println( "Usage: java " + XMLSample.class.getName() + "configFile"); System.exit(1); } static void init(String configFile) { DOMConfigurator.configure(configFile); } static void sample() { int i = -1; cat.debug("Message " + ++i); cat.warn ("Message " + ++i); cat.error("Message " + ++i); Exception e = new Exception("Just testing"); cat.debug("Message " + ++i, e); } } apache-log4j1.2-1.2.17.orig/src/main/javadoc/org/apache/log4j/xml/examples/doc-files/sample1.xml0000644000175000017500000000262311751454711030515 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/main/javadoc/org/apache/log4j/xml/examples/doc-files/sample4.xml0000644000175000017500000000274611751454711030526 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/main/javadoc/org/apache/log4j/xml/examples/doc-files/sample3.xml0000644000175000017500000000340511751454711030516 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/main/javadoc/org/apache/log4j/xml/examples/doc-files/sample5.xml0000644000175000017500000000341311751454711030517 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/main/javadoc/org/apache/log4j/xml/doc-files/0000755000175000017500000000000012126647422024610 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/javadoc/org/apache/log4j/xml/doc-files/log4j.dtd0000644000175000017500000001507611751454711026335 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/main/java/0000755000175000017500000000000011751454704016430 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/0000755000175000017500000000000011751454704017217 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/0000755000175000017500000000000011751454704020440 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/0000755000175000017500000000000012126647422021455 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/package.html0000644000175000017500000000163111751454711023737 0ustar tonytony

The main log4j package.


apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/rewrite/0000755000175000017500000000000012126647422023136 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/rewrite/RewriteAppender.java0000644000175000017500000001274211751454710027106 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.rewrite; import org.apache.log4j.Appender; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.helpers.AppenderAttachableImpl; import org.apache.log4j.spi.AppenderAttachable; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.OptionHandler; import org.apache.log4j.xml.UnrecognizedElementHandler; import org.w3c.dom.Element; import java.util.Enumeration; import java.util.Properties; /** * This appender forwards a logging request to another * appender after possibly rewriting the logging event. * * This appender (with the appropriate policy) * replaces the MapFilter, PropertyFilter and ReflectionFilter * from log4j 1.3. */ public class RewriteAppender extends AppenderSkeleton implements AppenderAttachable, UnrecognizedElementHandler { /** * Rewrite policy. */ private RewritePolicy policy; /** * Nested appenders. */ private final AppenderAttachableImpl appenders; public RewriteAppender() { appenders = new AppenderAttachableImpl(); } /** * {@inheritDoc} */ protected void append(final LoggingEvent event) { LoggingEvent rewritten = event; if (policy != null) { rewritten = policy.rewrite(event); } if (rewritten != null) { synchronized (appenders) { appenders.appendLoopOnAppenders(rewritten); } } } /** * Add appender. * * @param newAppender appender to add, may not be null. */ public void addAppender(final Appender newAppender) { synchronized (appenders) { appenders.addAppender(newAppender); } } /** * Get iterator over attached appenders. * @return iterator or null if no attached appenders. */ public Enumeration getAllAppenders() { synchronized (appenders) { return appenders.getAllAppenders(); } } /** * Get appender by name. * * @param name name, may not be null. * @return matching appender or null. */ public Appender getAppender(final String name) { synchronized (appenders) { return appenders.getAppender(name); } } /** * Close this AsyncAppender by interrupting the dispatcher * thread which will process all pending events before exiting. */ public void close() { closed = true; // // close all attached appenders. // synchronized (appenders) { Enumeration iter = appenders.getAllAppenders(); if (iter != null) { while (iter.hasMoreElements()) { Object next = iter.nextElement(); if (next instanceof Appender) { ((Appender) next).close(); } } } } } /** * Determines if specified appender is attached. * @param appender appender. * @return true if attached. */ public boolean isAttached(final Appender appender) { synchronized (appenders) { return appenders.isAttached(appender); } } /** * {@inheritDoc} */ public boolean requiresLayout() { return false; } /** * Removes and closes all attached appenders. */ public void removeAllAppenders() { synchronized (appenders) { appenders.removeAllAppenders(); } } /** * Removes an appender. * @param appender appender to remove. */ public void removeAppender(final Appender appender) { synchronized (appenders) { appenders.removeAppender(appender); } } /** * Remove appender by name. * @param name name. */ public void removeAppender(final String name) { synchronized (appenders) { appenders.removeAppender(name); } } public void setRewritePolicy(final RewritePolicy rewritePolicy) { policy = rewritePolicy; } /** * {@inheritDoc} */ public boolean parseUnrecognizedElement(final Element element, final Properties props) throws Exception { final String nodeName = element.getNodeName(); if ("rewritePolicy".equals(nodeName)) { Object rewritePolicy = org.apache.log4j.xml.DOMConfigurator.parseElement( element, props, RewritePolicy.class); if (rewritePolicy != null) { if (rewritePolicy instanceof OptionHandler) { ((OptionHandler) rewritePolicy).activateOptions(); } this.setRewritePolicy((RewritePolicy) rewritePolicy); } return true; } return false; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/rewrite/MapRewritePolicy.java0000644000175000017500000000633111751454710027242 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.rewrite; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; /** * This policy rewrites events where the message of the * original event implementes java.util.Map. * All other events are passed through unmodified. * If the map contains a "message" entry, the value will be * used as the message for the rewritten event. The rewritten * event will have a property set that is the combination of the * original property set and the other members of the message map. * If both the original property set and the message map * contain the same entry, the value from the message map * will overwrite the original property set. * * The combination of the RewriteAppender and this policy * performs the same actions as the MapFilter from log4j 1.3. */ public class MapRewritePolicy implements RewritePolicy { /** * {@inheritDoc} */ public LoggingEvent rewrite(final LoggingEvent source) { Object msg = source.getMessage(); if (msg instanceof Map) { Map props = new HashMap(source.getProperties()); Map eventProps = (Map) msg; // // if the map sent in the logging request // has "message" entry, use that as the message body // otherwise, use the entire map. // Object newMsg = eventProps.get("message"); if (newMsg == null) { newMsg = msg; } for(Iterator iter = eventProps.entrySet().iterator(); iter.hasNext(); ) { Map.Entry entry = (Map.Entry) iter.next(); if (!("message".equals(entry.getKey()))) { props.put(entry.getKey(), entry.getValue()); } } return new LoggingEvent( source.getFQNOfLoggerClass(), source.getLogger() != null ? source.getLogger(): Logger.getLogger(source.getLoggerName()), source.getTimeStamp(), source.getLevel(), newMsg, source.getThreadName(), source.getThrowableInformation(), source.getNDC(), source.getLocationInformation(), props); } else { return source; } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/rewrite/ReflectionRewritePolicy.java0000644000175000017500000000726511751454710030626 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.rewrite; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.spi.LoggingEvent; /** * This policy rewrites events by evaluating any * JavaBean properties on the message object and adding them * to the event properties. If the message object has a * message property, the value of that property will be * used as the message for the rewritten event and will * not be added to the event properties. Values from the * JavaBean properties will replace any existing property * with the same name. * * The combination of the RewriteAppender and this policy * performs the same actions as the ReflectionFilter from log4j 1.3. */ public class ReflectionRewritePolicy implements RewritePolicy { /** * {@inheritDoc} */ public LoggingEvent rewrite(final LoggingEvent source) { Object msg = source.getMessage(); if (!(msg instanceof String)) { Object newMsg = msg; Map rewriteProps = new HashMap(source.getProperties()); try { PropertyDescriptor[] props = Introspector.getBeanInfo( msg.getClass(), Object.class).getPropertyDescriptors(); if (props.length > 0) { for (int i=0;i This package lets you manage log4j settings using JMX. It is unfortunately not of production quality. apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/jmx/AbstractDynamicMBean.java0000644000175000017500000001355211751454711027077 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.jmx; import java.util.Enumeration; import java.util.Iterator; import java.util.Vector; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.DynamicMBean; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.JMException; import javax.management.MBeanRegistration; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import javax.management.RuntimeOperationsException; import org.apache.log4j.Logger; import org.apache.log4j.Appender; public abstract class AbstractDynamicMBean implements DynamicMBean, MBeanRegistration { String dClassName; MBeanServer server; private final Vector mbeanList = new Vector(); /** * Get MBean name. * @param appender appender, may not be null. * @return name. * @since 1.2.16 */ static protected String getAppenderName(final Appender appender){ String name = appender.getName(); if (name == null || name.trim().length() == 0) { // try to get some form of a name, because null is not allowed (exception), and empty string certainly isn't useful in JMX.. name = appender.toString(); } return name; } /** * Enables the to get the values of several attributes of the Dynamic MBean. */ public AttributeList getAttributes(String[] attributeNames) { // Check attributeNames is not null to avoid NullPointerException later on if (attributeNames == null) { throw new RuntimeOperationsException( new IllegalArgumentException("attributeNames[] cannot be null"), "Cannot invoke a getter of " + dClassName); } 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 0) { val = attributeName.substring(0, k)+'='+ attributeName.substring(k+3); } try { return new ObjectName("log4j:"+val); } catch(JMException e) { log.error("Could not create ObjectName" + val); } catch(RuntimeException e) { log.error("Could not create ObjectName" + val); } } // If attributeName has not been recognized throw an AttributeNotFoundException throw(new AttributeNotFoundException("Cannot find " + attributeName + " attribute in " + dClassName)); } public void addAppenderEvent(Category logger, Appender appender) { log.debug("addAppenderEvent called: logger="+logger.getName()+ ", appender="+appender.getName()); Notification n = new Notification(ADD_APPENDER+logger.getName(), this, 0); n.setUserData(appender); log.debug("sending notification."); nbs.sendNotification(n); } public void removeAppenderEvent(Category cat, Appender appender) { log.debug("removeAppenderCalled: logger="+cat.getName()+ ", appender="+appender.getName()); } public void postRegister(java.lang.Boolean registrationDone) { log.debug("postRegister is called."); hierarchy.addHierarchyEventListener(this); Logger root = hierarchy.getRootLogger(); addLoggerMBean(root); } public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { nbs.removeNotificationListener(listener); } public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, 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+" with null attribute"); } String name = attribute.getName(); Object value = attribute.getValue(); if (name == null) { throw new RuntimeOperationsException( 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, hierarchy.getThreshold()); hierarchy.setThreshold(l); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/nt/0000755000175000017500000000000012126647422022076 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/nt/package.html0000644000175000017500000000200711751454710024355 0ustar tonytony

Package for NT event logging.


Last modified: Sat Apr 29 14:30:12 MDT 2000 apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/nt/NTEventLogAppender.java0000644000175000017500000001135711751454710026413 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.nt; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.Layout; import org.apache.log4j.TTCCLayout; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.spi.LoggingEvent; /** Append to the NT event log system.

WARNING This appender can only be installed and used on a Windows system.

Do not forget to place NTEventLogAppender.dll, NTEventLogAppender.amd64.dll, NTEventLogAppender.ia64.dll or NTEventLogAppender.x86.dll as appropriate in a directory that is on the PATH of the Windows system. Otherwise, you will get a java.lang.UnsatisfiedLinkError. @author Chris Taylor @author Jim Cakalic */ public class NTEventLogAppender extends AppenderSkeleton { private int _handle = 0; private String source = null; private String server = null; 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"; } if (layout == null) { this.layout = new TTCCLayout(); } else { this.layout = layout; } try { _handle = registerEventSource(server, source); } catch (Exception e) { e.printStackTrace(); _handle = 0; } } public void close() { // unregister ... } public void activateOptions() { if (source != null) { try { _handle = registerEventSource(server, source); } catch (Exception e) { LogLog.error("Could not register event source.", e); _handle = 0; } } } public void append(LoggingEvent event) { 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++) { sbuf.append(s[i]); } } } // Normalize the log message level into the supported categories int nt_category = event.getLevel().toInt(); // Anything above FATAL or below DEBUG is labeled as INFO. //if (nt_category > FATAL || nt_category < DEBUG) { // nt_category = INFO; //} reportEvent(_handle, sbuf.toString(), nt_category); } public void finalize() { deregisterEventSource(_handle); _handle = 0; } /** The Source option which names the source of the event. The current value of this constant is Source. */ public void setSource(String source) { this.source = source.trim(); } public String getSource() { return source; } /** The NTEventLogAppender requires a layout. Hence, this method always returns true. */ public 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 { String[] archs; try { archs = new String[] { System.getProperty("os.arch")}; } catch(SecurityException e) { archs = new String[] { "amd64", "ia64", "x86"}; } boolean loaded = false; for(int i = 0; i < archs.length; i++) { try { System.loadLibrary("NTEventLogAppender." + archs[i]); loaded = true; break; } catch(java.lang.UnsatisfiedLinkError e) { loaded = false; } } if (!loaded) { System.loadLibrary("NTEventLogAppender"); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/NDC.java0000644000175000017500000003303011751454711022723 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Contributors: Dan Milstein // Ray Millard package org.apache.log4j; import java.util.Hashtable; import java.util.Stack; import java.util.Enumeration; import java.util.Vector; import org.apache.log4j.helpers.LogLog; /** The NDC class implements nested diagnostic contexts as defined by Neil Harrison in the article "Patterns for Logging Diagnostic Messages" part of the book "Pattern Languages of Program Design 3" edited by Martin et al.

A Nested Diagnostic Context, or NDC in short, is an instrument to distinguish interleaved log output from different sources. Log output is typically interleaved when a server handles multiple clients near-simultaneously.

Interleaved log output can still be meaningful if each log entry from different contexts had a distinctive stamp. This is where NDCs come into play.

Note that NDCs are managed on a per thread basis. NDC operations such as {@link #push push}, {@link #pop}, {@link #clear}, {@link #getDepth} and {@link #setMaxDepth} affect the NDC of the current thread only. NDCs of other threads remain unaffected.

For example, a servlet can build a per client request NDC consisting the clients host name and other information contained in the the request. Cookies are another source of distinctive information. To build an NDC one uses the {@link #push push} operation. Simply put,

  • Contexts can be nested.

  • When entering a context, call NDC.push. As a side effect, if there is no nested diagnostic context for the current thread, this method will create it.

  • When leaving a context, call NDC.pop.

  • When exiting a thread make sure to call {@link #remove NDC.remove()}.

There is no penalty for forgetting to match each push operation with a corresponding pop, except the obvious mismatch between the real application context and the context set in the NDC.

If configured to do so, {@link PatternLayout} and {@link TTCCLayout} instances automatically retrieve the nested diagnostic context for the current thread without any user intervention. Hence, even if a servlet is serving multiple clients simultaneously, the logs emanating from the same code (belonging to the same category) can still be distinguished because each client request will have a different NDC tag.

Heavy duty systems should call the {@link #remove} method when leaving the run method of a thread. This ensures that the memory used by the thread can be freed by the Java garbage collector. There is a mechanism to lazily remove references to dead threads. In practice, this means that you can be a little sloppy and sometimes forget to call {@link #remove} before exiting a thread.

A thread may inherit the nested diagnostic context of another (possibly parent) thread using the {@link #inherit inherit} method. A thread may obtain a copy of its NDC with the {@link #cloneStack cloneStack} method and pass the reference to any other thread, in particular to a child. @author Ceki Gülcü @since 0.7.0 */ public class NDC { // The synchronized keyword is not used in this class. This may seem // dangerous, especially since the class will be used by // multiple-threads. In particular, all threads share the same // hashtable (the "ht" variable). This is OK since java hashtables // are thread safe. Same goes for Stacks. // More importantly, when inheriting diagnostic contexts the child // thread is handed a clone of the parent's NDC. It follows that // each thread has its own NDC (i.e. stack). static Hashtable ht = new Hashtable(); static int pushCounter = 0; // the number of times push has been called // after the latest call to lazyRemove // The number of times we allow push to be called before we call lazyRemove // 5 is a relatively small number. As such, lazyRemove is not called too // frequently. We thus avoid the cost of creating an Enumeration too often. // The higher this number, the longer is the avarage period for which all // logging calls in all threads are blocked. static final int REAP_THRESHOLD = 5; // No instances allowed. private NDC() {} /** * Get NDC stack for current thread. * @return NDC stack for current thread. */ private static Stack getCurrentStack() { if (ht != null) { return (Stack) ht.get(Thread.currentThread()); } return null; } /** Clear any nested diagnostic information if any. This method is useful in cases where the same thread can be potentially used over and over in different unrelated contexts.

This method is equivalent to calling the {@link #setMaxDepth} method with a zero maxDepth argument. @since 0.8.4c */ public static void clear() { Stack stack = getCurrentStack(); if(stack != null) stack.setSize(0); } /** Clone the diagnostic context for the current thread.

Internally a diagnostic context is represented as a stack. A given thread can supply the stack (i.e. diagnostic context) to a child thread so that the child can inherit the parent thread's diagnostic context.

The child thread uses the {@link #inherit inherit} method to inherit the parent's diagnostic context. @return Stack A clone of the current thread's diagnostic context. */ public static Stack cloneStack() { Stack stack = getCurrentStack(); if(stack == null) return null; else { return (Stack) stack.clone(); } } /** Inherit the diagnostic context of another thread.

The parent thread can obtain a reference to its diagnostic context using the {@link #cloneStack} method. It should communicate this information to its child so that it may inherit the parent's diagnostic context.

The parent's diagnostic context is cloned before being inherited. In other words, once inherited, the two diagnostic contexts can be managed independently.

In java, a child thread cannot obtain a reference to its parent, unless it is directly handed the reference. Consequently, there is no client-transparent way of inheriting diagnostic contexts. Do you know any solution to this problem? @param stack The diagnostic context of the parent thread. */ public static void inherit(Stack stack) { if(stack != null) ht.put(Thread.currentThread(), stack); } /** Never use this method directly, use the {@link org.apache.log4j.spi.LoggingEvent#getNDC} method instead. */ static public String get() { Stack s = getCurrentStack(); if(s != null && !s.isEmpty()) return ((DiagnosticContext) s.peek()).fullMessage; else return null; } /** * Get the current nesting depth of this diagnostic context. * * @see #setMaxDepth * @since 0.7.5 */ public static int getDepth() { Stack stack = getCurrentStack(); if(stack == null) return 0; else return stack.size(); } private static void lazyRemove() { if (ht == null) return; // The synchronization on ht is necessary to prevent JDK 1.2.x from // throwing ConcurrentModificationExceptions at us. This sucks BIG-TIME. // One solution is to write our own hashtable implementation. Vector v; synchronized(ht) { // Avoid calling clean-up too often. if(++pushCounter <= REAP_THRESHOLD) { return; // We release the lock ASAP. } else { pushCounter = 0; // OK let's do some work. } int misses = 0; v = new Vector(); Enumeration enumeration = ht.keys(); // We give up after 4 straigt missses. That is 4 consecutive // inspected threads in 'ht' that turn out to be alive. // The higher the proportion on dead threads in ht, the higher the // chances of removal. while(enumeration.hasMoreElements() && (misses <= 4)) { Thread t = (Thread) enumeration.nextElement(); if(t.isAlive()) { misses++; } else { misses = 0; v.addElement(t); } } } // synchronized int size = v.size(); for(int i = 0; i < size; i++) { Thread t = (Thread) v.elementAt(i); LogLog.debug("Lazy NDC removal for thread [" + t.getName() + "] ("+ ht.size() + ")."); ht.remove(t); } } /** Clients should call this method before leaving a diagnostic context.

The returned value is the value that was pushed last. If no context is available, then the empty string "" is returned. @return String The innermost diagnostic context. */ public static String pop() { Stack stack = getCurrentStack(); if(stack != null && !stack.isEmpty()) return ((DiagnosticContext) stack.pop()).message; else return ""; } /** Looks at the last diagnostic context at the top of this NDC without removing it.

The returned value is the value that was pushed last. If no context is available, then the empty string "" is returned. @return String The innermost diagnostic context. */ public static String peek() { Stack stack = getCurrentStack(); if(stack != null && !stack.isEmpty()) return ((DiagnosticContext) stack.peek()).message; else return ""; } /** Push new diagnostic context information for the current thread.

The contents of the message parameter is determined solely by the client. @param message The new diagnostic context information. */ public static void push(String message) { Stack stack = getCurrentStack(); if(stack == null) { DiagnosticContext dc = new DiagnosticContext(message, null); stack = new Stack(); Thread key = Thread.currentThread(); ht.put(key, stack); stack.push(dc); } else if (stack.isEmpty()) { DiagnosticContext dc = new DiagnosticContext(message, null); stack.push(dc); } else { DiagnosticContext parent = (DiagnosticContext) stack.peek(); stack.push(new DiagnosticContext(message, parent)); } } /** Remove the diagnostic context for this thread.

Each thread that created a diagnostic context by calling {@link #push} should call this method before exiting. Otherwise, the memory used by the thread cannot be reclaimed by the VM.

As this is such an important problem in heavy duty systems and because it is difficult to always guarantee that the remove method is called before exiting a thread, this method has been augmented to lazily remove references to dead threads. In practice, this means that you can be a little sloppy and occasionally forget to call {@link #remove} before exiting a thread. However, you must call remove sometime. If you never call it, then your application is sure to run out of memory. */ static public void remove() { if (ht != null) { ht.remove(Thread.currentThread()); // Lazily remove dead-thread references in ht. lazyRemove(); } } /** Set maximum depth of this diagnostic context. If the current depth is smaller or equal to maxDepth, then no action is taken.

This method is a convenient alternative to multiple {@link #pop} calls. Moreover, it is often the case that at the end of complex call sequences, the depth of the NDC is unpredictable. The setMaxDepth method circumvents this problem.

For example, the combination

       void foo() {
          int depth = NDC.getDepth();

          ... complex sequence of calls

          NDC.setMaxDepth(depth);
       }
     
ensures that between the entry and exit of foo the depth of the diagnostic stack is conserved. @see #getDepth @since 0.7.5 */ static public void setMaxDepth(int maxDepth) { Stack stack = getCurrentStack(); if(stack != null && maxDepth < stack.size()) stack.setSize(maxDepth); } // ===================================================================== private static class DiagnosticContext { String fullMessage; String message; DiagnosticContext(String message, DiagnosticContext parent) { this.message = message; if(parent != null) { fullMessage = parent.fullMessage + ' ' + message; } else { fullMessage = message; } } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/AppenderSkeleton.java0000644000175000017500000001570211751454711025570 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; 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; /** * Abstract superclass of the other appenders in the package. * * This class provides the code for common functionality, such as * support for threshold filtering and support for general filters. * * @since 0.8.1 * @author Ceki Gülcü * */ public abstract class AppenderSkeleton implements Appender, OptionHandler { /** The layout variable does not need to be set if the appender implementation has its own layout. */ protected Layout layout; /** Appenders are named. */ protected String name; /** There is no level threshold filtering by default. */ protected Priority threshold; /** It is assumed and enforced that errorHandler is never null. */ protected ErrorHandler errorHandler = new OnlyOnceErrorHandler(); /** The first filter in the filter chain. Set to null initially. */ protected Filter headFilter; /** The last filter in the filter chain. */ protected Filter tailFilter; /** Is this appender closed? */ protected boolean closed = false; /** * Create new instance. */ public AppenderSkeleton() { super(); } /** * Create new instance. * Provided for compatibility with log4j 1.3. * * @param isActive true if appender is ready for use upon construction. * Not used in log4j 1.2.x. * @since 1.2.15 */ protected AppenderSkeleton(final boolean isActive) { super(); } /** Derived appenders should override this method if option structure requires it. */ public void activateOptions() { } /** Add a filter to end of the filter list. @since 0.9.0 */ public void addFilter(Filter newFilter) { if(headFilter == null) { headFilter = tailFilter = newFilter; } else { tailFilter.setNext(newFilter); tailFilter = newFilter; } } /** Subclasses of AppenderSkeleton should implement this method to perform actual logging. See also {@link #doAppend AppenderSkeleton.doAppend} method. @since 0.9.0 */ abstract protected void append(LoggingEvent event); /** Clear the filters chain. @since 0.9.0 */ public void clearFilters() { headFilter = tailFilter = null; } /** Finalize this appender by calling the derived class' close method. @since 0.8.4 */ public void finalize() { // An appender might be closed then garbage collected. There is no // point in closing twice. if(this.closed) return; LogLog.debug("Finalizing appender named ["+name+"]."); close(); } /** Return the currently set {@link ErrorHandler} for this Appender. @since 0.9.0 */ public ErrorHandler getErrorHandler() { return this.errorHandler; } /** Returns the head Filter. @since 1.1 */ public Filter getFilter() { return headFilter; } /** Return the first filter in the filter chain for this Appender. The return value may be null if no is filter is set. */ public final Filter getFirstFilter() { return headFilter; } /** Returns the layout of this appender. The value may be null. */ public Layout getLayout() { return layout; } /** Returns the name of this appender. @return name, may be null. */ public final String getName() { return this.name; } /** Returns this appenders threshold level. See the {@link #setThreshold} method for the meaning of this option. @since 1.1 */ public Priority getThreshold() { return threshold; } /** Check whether the message level is below the appender's threshold. If there is no threshold set, then the return value is always true. */ public boolean isAsSevereAsThreshold(Priority priority) { return ((threshold == null) || priority.isGreaterOrEqual(threshold)); } /** * This method performs threshold checks and invokes filters before * delegating actual logging to the subclasses specific {@link * AppenderSkeleton#append} method. * */ public synchronized void doAppend(LoggingEvent event) { if(closed) { LogLog.error("Attempted to append to closed appender named ["+name+"]."); return; } if(!isAsSevereAsThreshold(event.getLevel())) { return; } Filter f = this.headFilter; FILTER_LOOP: while(f != null) { switch(f.decide(event)) { case Filter.DENY: return; case Filter.ACCEPT: break FILTER_LOOP; case Filter.NEUTRAL: f = f.getNext(); } } this.append(event); } /** Set the {@link ErrorHandler} for this Appender. @since 0.9.0 */ public synchronized void setErrorHandler(ErrorHandler eh) { if(eh == null) { // We do not throw exception here since the cause is probably a // bad config file. LogLog.warn("You have tried to set a null error-handler."); } else { this.errorHandler = eh; } } /** Set the layout for this appender. Note that some appenders have their own (fixed) layouts or do not use one. For example, the {@link org.apache.log4j.net.SocketAppender} ignores the layout set here. */ public void setLayout(Layout layout) { this.layout = layout; } /** Set the name of this Appender. */ public void setName(String name) { this.name = name; } /** Set the threshold level. All log events with lower level than the threshold level are ignored by the appender.

In configuration files this option is specified by setting the value of the Threshold option to a level string, such as "DEBUG", "INFO" and so on. @since 0.8.3 */ public void setThreshold(Priority threshold) { this.threshold = threshold; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/net/0000755000175000017500000000000012126647422022243 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/net/package.html0000644000175000017500000000200311751454710024516 0ustar tonytony

Package for remote logging.


Last modified: Tue Mar 21 20:28:14 MET 2000 apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/net/TelnetAppender.java0000644000175000017500000001540711751454710026026 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.net; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.spi.LoggingEvent; import java.io.IOException; import java.io.PrintWriter; import java.io.InterruptedIOException; import java.net.ServerSocket; import java.net.Socket; import java.util.Enumeration; import java.util.Iterator; import java.util.Vector; /**

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.

Here is a list of the available configuration options:
Name Requirement Description Sample Value
Port optional This parameter determines the port to use for announcing log events. The default port is 23 (telnet). 5875
@author Jay Funnell */ public class TelnetAppender extends AppenderSkeleton { 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; } /** 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(InterruptedIOException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } catch(RuntimeException e) { e.printStackTrace(); } super.activateOptions(); } public int getPort() { return port; } public void setPort(int port) { this.port = port; } /** shuts down the appender. */ public void close() { if (sh != null) { sh.close(); try { sh.join(); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } } } /** Handles a log event. For this appender, that means writing the message to each connected client. */ protected void append(LoggingEvent event) { if(sh != null) { sh.send(layout.format(event)); if(layout.ignoresThrowable()) { String[] s = event.getThrowableStrRep(); if (s != null) { StringBuffer buf = new StringBuffer(); for(int i = 0; i < s.length; i++) { buf.append(s[i]); buf.append("\r\n"); } sh.send(buf.toString()); } } } } //---------------------------------------------------------- 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 { private Vector writers = new Vector(); private Vector connections = new Vector(); private ServerSocket serverSocket; private int MAX_CONNECTIONS = 20; public void finalize() { close(); } /** * make sure we close all network connections when this handler is destroyed. * @since 1.2.15 */ public void close() { synchronized(this) { for(Enumeration e = connections.elements();e.hasMoreElements();) { try { ((Socket)e.nextElement()).close(); } catch(InterruptedIOException ex) { Thread.currentThread().interrupt(); } catch(IOException ex) { } catch(RuntimeException ex) { } } } try { serverSocket.close(); } catch(InterruptedIOException ex) { Thread.currentThread().interrupt(); } catch(IOException ex) { } catch(RuntimeException ex) { } } /** sends a message to each of the clients in telnet-friendly output. */ public synchronized void send(final String message) { Iterator ce = connections.iterator(); for(Iterator e = writers.iterator();e.hasNext();) { ce.next(); PrintWriter writer = (PrintWriter)e.next(); writer.print(message); if(writer.checkError()) { ce.remove(); e.remove(); } } } /** Continually accepts client connections. Client connections are refused when MAX_CONNECTIONS is reached. */ public void run() { while(!serverSocket.isClosed()) { try { Socket newClient = serverSocket.accept(); PrintWriter pw = new PrintWriter(newClient.getOutputStream()); if(connections.size() < MAX_CONNECTIONS) { synchronized(this) { 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) { if (e instanceof InterruptedIOException || e instanceof InterruptedException) { Thread.currentThread().interrupt(); } if (!serverSocket.isClosed()) { LogLog.error("Encountered error while in SocketHandler loop.", e); } break; } } try { serverSocket.close(); } catch(InterruptedIOException ex) { Thread.currentThread().interrupt(); } catch(IOException ex) { } } public SocketHandler(int port) throws IOException { serverSocket = new ServerSocket(port); setName("TelnetAppender-" + getName() + "-" + port); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/net/ZeroConfSupport.java0000644000175000017500000002022411751454710026227 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.net; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import org.apache.log4j.helpers.LogLog; public class ZeroConfSupport { private static Object jmDNS = initializeJMDNS(); Object serviceInfo; private static Class jmDNSClass; private static Class serviceInfoClass; public ZeroConfSupport(String zone, int port, String name, Map properties) { //if version 3 is available, use it to constuct a serviceInfo instance, otherwise support the version1 API boolean isVersion3 = false; try { //create method is in version 3, not version 1 jmDNSClass.getMethod("create", null); isVersion3 = true; } catch (NoSuchMethodException e) { //no-op } if (isVersion3) { LogLog.debug("using JmDNS version 3 to construct serviceInfo instance"); serviceInfo = buildServiceInfoVersion3(zone, port, name, properties); } else { LogLog.debug("using JmDNS version 1.0 to construct serviceInfo instance"); serviceInfo = buildServiceInfoVersion1(zone, port, name, properties); } } public ZeroConfSupport(String zone, int port, String name) { this(zone, port, name, new HashMap()); } private static Object createJmDNSVersion1() { try { return jmDNSClass.newInstance(); } catch (InstantiationException e) { LogLog.warn("Unable to instantiate JMDNS", e); } catch (IllegalAccessException e) { LogLog.warn("Unable to instantiate JMDNS", e); } return null; } private static Object createJmDNSVersion3() { try { Method jmDNSCreateMethod = jmDNSClass.getMethod("create", null); return jmDNSCreateMethod.invoke(null, null); } catch (IllegalAccessException e) { LogLog.warn("Unable to instantiate jmdns class", e); } catch (NoSuchMethodException e) { LogLog.warn("Unable to access constructor", e); } catch (InvocationTargetException e) { LogLog.warn("Unable to call constructor", e); } return null; } private Object buildServiceInfoVersion1(String zone, int port, String name, Map properties) { //version 1 uses a hashtable Hashtable hashtableProperties = new Hashtable(properties); try { Class[] args = new Class[6]; args[0] = String.class; args[1] = String.class; args[2] = int.class; args[3] = int.class; //weight (0) args[4] = int.class; //priority (0) args[5] = Hashtable.class; Constructor constructor = serviceInfoClass.getConstructor(args); Object[] values = new Object[6]; values[0] = zone; values[1] = name; values[2] = new Integer(port); values[3] = new Integer(0); values[4] = new Integer(0); values[5] = hashtableProperties; Object result = constructor.newInstance(values); LogLog.debug("created serviceinfo: " + result); return result; } catch (IllegalAccessException e) { LogLog.warn("Unable to construct ServiceInfo instance", e); } catch (NoSuchMethodException e) { LogLog.warn("Unable to get ServiceInfo constructor", e); } catch (InstantiationException e) { LogLog.warn("Unable to construct ServiceInfo instance", e); } catch (InvocationTargetException e) { LogLog.warn("Unable to construct ServiceInfo instance", e); } return null; } private Object buildServiceInfoVersion3(String zone, int port, String name, Map properties) { try { Class[] args = new Class[6]; args[0] = String.class; //zone/type args[1] = String.class; //display name args[2] = int.class; //port args[3] = int.class; //weight (0) args[4] = int.class; //priority (0) args[5] = Map.class; Method serviceInfoCreateMethod = serviceInfoClass.getMethod("create", args); Object[] values = new Object[6]; values[0] = zone; values[1] = name; values[2] = new Integer(port); values[3] = new Integer(0); values[4] = new Integer(0); values[5] = properties; Object result = serviceInfoCreateMethod.invoke(null, values); LogLog.debug("created serviceinfo: " + result); return result; } catch (IllegalAccessException e) { LogLog.warn("Unable to invoke create method", e); } catch (NoSuchMethodException e) { LogLog.warn("Unable to find create method", e); } catch (InvocationTargetException e) { LogLog.warn("Unable to invoke create method", e); } return null; } public void advertise() { try { Method method = jmDNSClass.getMethod("registerService", new Class[]{serviceInfoClass}); method.invoke(jmDNS, new Object[]{serviceInfo}); LogLog.debug("registered serviceInfo: " + serviceInfo); } catch(IllegalAccessException e) { LogLog.warn("Unable to invoke registerService method", e); } catch(NoSuchMethodException e) { LogLog.warn("No registerService method", e); } catch(InvocationTargetException e) { LogLog.warn("Unable to invoke registerService method", e); } } public void unadvertise() { try { Method method = jmDNSClass.getMethod("unregisterService", new Class[]{serviceInfoClass}); method.invoke(jmDNS, new Object[]{serviceInfo}); LogLog.debug("unregistered serviceInfo: " + serviceInfo); } catch(IllegalAccessException e) { LogLog.warn("Unable to invoke unregisterService method", e); } catch(NoSuchMethodException e) { LogLog.warn("No unregisterService method", e); } catch(InvocationTargetException e) { LogLog.warn("Unable to invoke unregisterService method", e); } } private static Object initializeJMDNS() { try { jmDNSClass = Class.forName("javax.jmdns.JmDNS"); serviceInfoClass = Class.forName("javax.jmdns.ServiceInfo"); } catch (ClassNotFoundException e) { LogLog.warn("JmDNS or serviceInfo class not found", e); } //if version 3 is available, use it to constuct a serviceInfo instance, otherwise support the version1 API boolean isVersion3 = false; try { //create method is in version 3, not version 1 jmDNSClass.getMethod("create", null); isVersion3 = true; } catch (NoSuchMethodException e) { //no-op } if (isVersion3) { return createJmDNSVersion3(); } else { return createJmDNSVersion1(); } } public static Object getJMDNSInstance() { return jmDNS; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/net/SimpleSocketServer.java0000644000175000017500000000551211751454710026701 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.net; import java.net.ServerSocket; import java.net.Socket; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.xml.DOMConfigurator; /** * A simple {@link SocketNode} based server. *

   Usage: java org.apache.log4j.net.SimpleSocketServer port configFile

   where port is a part number where the server listens and
   configFile is a configuration file fed to the {@link
   PropertyConfigurator} or to {@link DOMConfigurator} if an XML file.
   
* * @author Ceki Gülcü * * @since 0.8.4 * */ public class SimpleSocketServer { static Logger cat = Logger.getLogger(SimpleSocketServer.class); static int port; public static void main(String argv[]) { if(argv.length == 2) { init(argv[0], argv[1]); } else { usage("Wrong number of arguments."); } try { cat.info("Listening on port " + port); ServerSocket serverSocket = new ServerSocket(port); while(true) { 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, LogManager.getLoggerRepository()),"SimpleSocketServer-" + port).start(); } } catch(Exception e) { e.printStackTrace(); } } static void usage(String msg) { System.err.println(msg); System.err.println( "Usage: java " +SimpleSocketServer.class.getName() + " port configFile"); System.exit(1); } static void init(String portStr, String configFile) { try { port = Integer.parseInt(portStr); } catch(java.lang.NumberFormatException e) { e.printStackTrace(); usage("Could not interpret port number ["+ portStr +"]."); } if(configFile.endsWith(".xml")) { DOMConfigurator.configure(configFile); } else { PropertyConfigurator.configure(configFile); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/net/JMSSink.java0000644000175000017500000001155511751454710024372 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.net; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.xml.DOMConfigurator; import javax.jms.JMSException; import javax.jms.ObjectMessage; import javax.jms.Session; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; import javax.jms.TopicSubscriber; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NameNotFoundException; import javax.naming.NamingException; import java.io.BufferedReader; import java.io.InputStreamReader; /** * A simple application that consumes logging events sent by a {@link * JMSAppender}. * * * @author Ceki Gülcü * */ public class JMSSink implements javax.jms.MessageListener { static Logger logger = Logger.getLogger(JMSSink.class); static public void main(String[] args) throws Exception { if(args.length != 5) { usage("Wrong number of arguments."); } String tcfBindingName = args[0]; String topicBindingName = args[1]; String username = args[2]; String password = args[3]; String configFile = args[4]; if(configFile.endsWith(".xml")) { DOMConfigurator.configure(configFile); } else { PropertyConfigurator.configure(configFile); } new JMSSink(tcfBindingName, topicBindingName, username, password); BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); // Loop until the word "exit" is typed System.out.println("Type \"exit\" to quit JMSSink."); while(true){ String s = stdin.readLine( ); if (s.equalsIgnoreCase("exit")) { System.out.println("Exiting. Kill the application if it does not exit " + "due to daemon threads."); return; } } } public JMSSink( String tcfBindingName, String topicBindingName, String username, String password) { try { Context ctx = new InitialContext(); TopicConnectionFactory topicConnectionFactory; topicConnectionFactory = (TopicConnectionFactory) lookup(ctx, tcfBindingName); TopicConnection topicConnection = topicConnectionFactory.createTopicConnection(username, password); topicConnection.start(); TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = (Topic)ctx.lookup(topicBindingName); TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic); topicSubscriber.setMessageListener(this); } catch(JMSException e) { logger.error("Could not read JMS message.", e); } catch(NamingException e) { logger.error("Could not read JMS message.", e); } catch(RuntimeException e) { logger.error("Could not read JMS message.", e); } } public void onMessage(javax.jms.Message message) { LoggingEvent event; Logger remoteLogger; try { if(message instanceof ObjectMessage) { ObjectMessage objectMessage = (ObjectMessage) message; event = (LoggingEvent) objectMessage.getObject(); remoteLogger = Logger.getLogger(event.getLoggerName()); remoteLogger.callAppenders(event); } else { logger.warn("Received message is of type "+message.getJMSType() +", was expecting ObjectMessage."); } } catch(JMSException jmse) { logger.error("Exception thrown while processing incoming message.", jmse); } } protected static Object lookup(Context ctx, String name) throws NamingException { try { return ctx.lookup(name); } catch(NameNotFoundException e) { logger.error("Could not find name ["+name+"]."); throw e; } } static void usage(String msg) { System.err.println(msg); System.err.println("Usage: java " + JMSSink.class.getName() + " TopicConnectionFactoryBindingName TopicBindingName username password configFile"); System.exit(1); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/net/SyslogAppender.java0000644000175000017500000003760011751454710026052 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.net; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.Layout; import org.apache.log4j.helpers.SyslogQuietWriter; import org.apache.log4j.helpers.SyslogWriter; import org.apache.log4j.spi.LoggingEvent; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.net.InetAddress; import java.net.UnknownHostException; import java.io.IOException; // Contributors: Yves Bossel // Christopher Taylor /** Use SyslogAppender to send log messages to a remote syslog daemon. @author Ceki Gülcü @author Anders Kristensen */ public class SyslogAppender extends AppenderSkeleton { // 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; /** Random user-level messages */ final static public int LOG_USER = 1<<3; /** Mail system */ final static public int LOG_MAIL = 2<<3; /** System daemons */ final static public int LOG_DAEMON = 3<<3; /** security/authorization messages */ 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; /** network news subsystem */ final static public int LOG_NEWS = 7<<3; /** UUCP subsystem */ final static public int LOG_UUCP = 8<<3; /** clock daemon */ final static public int LOG_CRON = 9<<3; /** security/authorization messages (private) */ final static public int LOG_AUTHPRIV = 10<<3; /** ftp daemon */ 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; /** reserved for local use */ final static public int LOG_LOCAL1 = 17<<3; /** reserved for local use */ final static public int LOG_LOCAL2 = 18<<3; /** reserved for local use */ final static public int LOG_LOCAL3 = 19<<3; /** reserved for local use */ final static public int LOG_LOCAL4 = 20<<3; /** reserved for local use */ final static public int LOG_LOCAL5 = 21<<3; /** reserved for local use */ final static public int LOG_LOCAL6 = 22<<3; /** reserved for local use*/ 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; boolean facilityPrinting = false; //SyslogTracerPrintWriter stp; SyslogQuietWriter sqw; String syslogHost; /** * If true, the appender will generate the HEADER (timestamp and host name) * part of the syslog packet. * @since 1.2.15 */ private boolean header = false; /** * Date format used if header = true. * @since 1.2.15 */ private final SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd HH:mm:ss ", Locale.ENGLISH); /** * Host name used to identify messages from this appender. * @since 1.2.15 */ private String localHostname; /** * Set to true after the header of the layout has been sent or if it has none. */ private boolean layoutHeaderChecked = false; public SyslogAppender() { this.initSyslogFacilityStr(); } public SyslogAppender(Layout layout, int syslogFacility) { this.layout = layout; this.syslogFacility = syslogFacility; this.initSyslogFacilityStr(); } public SyslogAppender(Layout layout, String syslogHost, int syslogFacility) { this(layout, syslogFacility); setSyslogHost(syslogHost); } /** Release any resources held by this SyslogAppender. @since 0.8.4 */ synchronized public void close() { closed = true; if (sqw != null) { try { if (layoutHeaderChecked && layout != null && layout.getFooter() != null) { sendLayoutMessage(layout.getFooter()); } sqw.close(); sqw = null; } catch(java.io.InterruptedIOException e) { Thread.currentThread().interrupt(); sqw = null; } catch(IOException e) { sqw = null; } } } private void initSyslogFacilityStr() { facilityStr = getFacilityString(this.syslogFacility); if (facilityStr == null) { System.err.println("\"" + syslogFacility + "\" is an unknown syslog facility. Defaulting to \"USER\"."); this.syslogFacility = LOG_USER; facilityStr = "user:"; } else { facilityStr += ":"; } } /** Returns the specified syslog facility as a lower-case String, e.g. "kern", "user", etc. */ public static String getFacilityString(int syslogFacility) { switch(syslogFacility) { case LOG_KERN: return "kern"; case LOG_USER: return "user"; case LOG_MAIL: return "mail"; case LOG_DAEMON: return "daemon"; case LOG_AUTH: return "auth"; case LOG_SYSLOG: return "syslog"; case LOG_LPR: return "lpr"; case LOG_NEWS: return "news"; case LOG_UUCP: return "uucp"; case LOG_CRON: return "cron"; case LOG_AUTHPRIV: return "authpriv"; case LOG_FTP: return "ftp"; case LOG_LOCAL0: return "local0"; case LOG_LOCAL1: return "local1"; case LOG_LOCAL2: return "local2"; case LOG_LOCAL3: return "local3"; case LOG_LOCAL4: return "local4"; case LOG_LOCAL5: return "local5"; case LOG_LOCAL6: return "local6"; case LOG_LOCAL7: return "local7"; default: return null; } } /** Returns the integer value corresponding to the named syslog facility, or -1 if it couldn't be recognized. @param facilityName one of the strings KERN, USER, MAIL, DAEMON, 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 static int getFacility(String facilityName) { if(facilityName != null) { facilityName = facilityName.trim(); } if("KERN".equalsIgnoreCase(facilityName)) { return LOG_KERN; } else if("USER".equalsIgnoreCase(facilityName)) { return LOG_USER; } else if("MAIL".equalsIgnoreCase(facilityName)) { return LOG_MAIL; } else if("DAEMON".equalsIgnoreCase(facilityName)) { return LOG_DAEMON; } else if("AUTH".equalsIgnoreCase(facilityName)) { return LOG_AUTH; } else if("SYSLOG".equalsIgnoreCase(facilityName)) { return LOG_SYSLOG; } else if("LPR".equalsIgnoreCase(facilityName)) { return LOG_LPR; } else if("NEWS".equalsIgnoreCase(facilityName)) { return LOG_NEWS; } else if("UUCP".equalsIgnoreCase(facilityName)) { return LOG_UUCP; } else if("CRON".equalsIgnoreCase(facilityName)) { return LOG_CRON; } else if("AUTHPRIV".equalsIgnoreCase(facilityName)) { return LOG_AUTHPRIV; } else if("FTP".equalsIgnoreCase(facilityName)) { return LOG_FTP; } else if("LOCAL0".equalsIgnoreCase(facilityName)) { return LOG_LOCAL0; } else if("LOCAL1".equalsIgnoreCase(facilityName)) { return LOG_LOCAL1; } else if("LOCAL2".equalsIgnoreCase(facilityName)) { return LOG_LOCAL2; } else if("LOCAL3".equalsIgnoreCase(facilityName)) { return LOG_LOCAL3; } else if("LOCAL4".equalsIgnoreCase(facilityName)) { return LOG_LOCAL4; } else if("LOCAL5".equalsIgnoreCase(facilityName)) { return LOG_LOCAL5; } else if("LOCAL6".equalsIgnoreCase(facilityName)) { return LOG_LOCAL6; } else if("LOCAL7".equalsIgnoreCase(facilityName)) { return LOG_LOCAL7; } else { return -1; } } private void splitPacket(final String header, final String packet) { int byteCount = packet.getBytes().length; // // if packet is less than RFC 3164 limit // of 1024 bytes, then write it // (must allow for up 5to 5 characters in the PRI section // added by SyslogQuietWriter) if (byteCount <= 1019) { sqw.write(packet); } else { int split = header.length() + (packet.length() - header.length())/2; splitPacket(header, packet.substring(0, split) + "..."); splitPacket(header, header + "..." + packet.substring(split)); } } public void append(LoggingEvent event) { if(!isAsSevereAsThreshold(event.getLevel())) return; // We must not attempt to append if sqw is null. if(sqw == null) { errorHandler.error("No syslog host is set for SyslogAppedender named \""+ this.name+"\"."); return; } if (!layoutHeaderChecked) { if (layout != null && layout.getHeader() != null) { sendLayoutMessage(layout.getHeader()); } layoutHeaderChecked = true; } String hdr = getPacketHeader(event.timeStamp); String packet; if (layout == null) { packet = String.valueOf(event.getMessage()); } else { packet = layout.format(event); } if(facilityPrinting || hdr.length() > 0) { StringBuffer buf = new StringBuffer(hdr); if(facilityPrinting) { buf.append(facilityStr); } buf.append(packet); packet = buf.toString(); } sqw.setLevel(event.getLevel().getSyslogEquivalent()); // // if message has a remote likelihood of exceeding 1024 bytes // when encoded, consider splitting message into multiple packets if (packet.length() > 256) { splitPacket(hdr, packet); } else { sqw.write(packet); } if (layout == null || layout.ignoresThrowable()) { String[] s = event.getThrowableStrRep(); if (s != null) { for(int i = 0; i < s.length; i++) { if (s[i].startsWith("\t")) { sqw.write(hdr+TAB+s[i].substring(1)); } else { sqw.write(hdr+s[i]); } } } } } /** This method returns immediately as options are activated when they are set. */ public void activateOptions() { if (header) { getLocalHostname(); } if (layout != null && layout.getHeader() != null) { sendLayoutMessage(layout.getHeader()); } layoutHeaderChecked = true; } /** The SyslogAppender requires a layout. Hence, this method returns true. @since 0.8.4 */ public boolean requiresLayout() { return true; } /** The SyslogHost option is the name of the the syslog host where log output should go. A non-default port can be specified by appending a colon and port number to a host name, an IPv4 address or an IPv6 address enclosed in square brackets. WARNING If the SyslogHost is not set, then this appender will fail. */ public void setSyslogHost(final String syslogHost) { this.sqw = new SyslogQuietWriter(new SyslogWriter(syslogHost), syslogFacility, errorHandler); //this.stp = new SyslogTracerPrintWriter(sqw); this.syslogHost = syslogHost; } /** Returns the value of the SyslogHost option. */ public String getSyslogHost() { return syslogHost; } /** Set the syslog facility. This is the Facility option.

The facilityName parameter must be one of the 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. if(sqw != null) { sqw.setSyslogFacility(this.syslogFacility); } } /** Returns the value of the Facility option. */ public String getFacility() { return getFacilityString(syslogFacility); } /** If the FacilityPrinting option is set to true, the printed message will include the facility name of the application. It is false by default. */ public void setFacilityPrinting(boolean on) { facilityPrinting = on; } /** Returns the value of the FacilityPrinting option. */ public boolean getFacilityPrinting() { return facilityPrinting; } /** * If true, the appender will generate the HEADER part (that is, timestamp and host name) * of the syslog packet. Default value is false for compatibility with existing behavior, * however should be true unless there is a specific justification. * @since 1.2.15 */ public final boolean getHeader() { return header; } /** * Returns whether the appender produces the HEADER part (that is, timestamp and host name) * of the syslog packet. * @since 1.2.15 */ public final void setHeader(final boolean val) { header = val; } /** * Get the host name used to identify this appender. * @return local host name * @since 1.2.15 */ private String getLocalHostname() { if (localHostname == null) { try { InetAddress addr = InetAddress.getLocalHost(); localHostname = addr.getHostName(); } catch (UnknownHostException uhe) { localHostname = "UNKNOWN_HOST"; } } return localHostname; } /** * Gets HEADER portion of packet. * @param timeStamp number of milliseconds after the standard base time. * @return HEADER portion of packet, will be zero-length string if header is false. * @since 1.2.15 */ private String getPacketHeader(final long timeStamp) { if (header) { StringBuffer buf = new StringBuffer(dateFormat.format(new Date(timeStamp))); // RFC 3164 says leading space, not leading zero on days 1-9 if (buf.charAt(4) == '0') { buf.setCharAt(4, ' '); } buf.append(getLocalHostname()); buf.append(' '); return buf.toString(); } return ""; } /** * Set header or footer of layout. * @param msg message body, may not be null. */ private void sendLayoutMessage(final String msg) { if (sqw != null) { String packet = msg; String hdr = getPacketHeader(new Date().getTime()); if(facilityPrinting || hdr.length() > 0) { StringBuffer buf = new StringBuffer(hdr); if(facilityPrinting) { buf.append(facilityStr); } buf.append(msg); packet = buf.toString(); } sqw.setLevel(6); sqw.write(packet); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/net/SocketAppender.java0000644000175000017500000003340311751454710026017 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Contributors: Dan MacDonald package org.apache.log4j.net; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.InterruptedIOException; import java.net.InetAddress; import java.net.Socket; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.spi.ErrorCode; import org.apache.log4j.spi.LoggingEvent; /** Sends {@link LoggingEvent} objects to a remote a log server, usually a {@link SocketNode}.

The SocketAppender has the following properties:

  • If sent to a {@link SocketNode}, remote logging is non-intrusive as far as the log event is concerned. In other words, the event will be logged with the same time stamp, {@link org.apache.log4j.NDC}, location info as if it were logged locally by the client.

  • SocketAppenders do not use a layout. They ship a serialized {@link LoggingEvent} object to the server side.

  • Remote logging uses the TCP protocol. Consequently, if the server is reachable, then log events will eventually arrive at the server.

  • 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 connector thread which periodically attempts to connect to the server.

  • Logging events are automatically buffered 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 by the client, the client will not be affected by the slow network connection. However, if the network connection is slower then the rate of event production, then the client can only progress at the network rate. In particular, if the network link to the the server is down, the client will be blocked.

    On the other hand, if the network link is up, but the server is down, the client will not be blocked when making log requests but the log events will be lost due to server unavailability.

  • Even if a SocketAppender is no longer attached to any category, it will not be garbage collected in the presence of a connector thread. A connector thread exists only if the connection to the server is down. To avoid this garbage collection problem, you should {@link #close} the the SocketAppender explicitly. See also next item.

    Long lived applications which create/destroy many SocketAppender instances should be aware of this garbage collection problem. Most other applications can safely ignore it.

  • If the JVM hosting the SocketAppender exits before the SocketAppender is closed either explicitly or subsequent to garbage collection, then there might be untransmitted data in the pipe which might be lost. This is a common problem on Windows based systems.

    To avoid lost data, it is usually sufficient to {@link #close} the SocketAppender either explicitly or by calling the {@link org.apache.log4j.LogManager#shutdown} method before exiting the application.

@author Ceki Gülcü @since 0.8.4 */ public class SocketAppender extends AppenderSkeleton { /** The default port number of remote logging server (4560). @since 1.2.15 */ static public final int DEFAULT_PORT = 4560; /** The default reconnection delay (30000 milliseconds or 30 seconds). */ static final int DEFAULT_RECONNECTION_DELAY = 30000; /** We remember host name as String in addition to the resolved InetAddress so that it can be returned via getOption(). */ String remoteHost; /** * The MulticastDNS zone advertised by a SocketAppender */ public static final String ZONE = "_log4j_obj_tcpconnect_appender.local."; InetAddress address; int port = DEFAULT_PORT; ObjectOutputStream oos; int reconnectionDelay = DEFAULT_RECONNECTION_DELAY; boolean locationInfo = false; private String application; private Connector connector; int counter = 0; // reset the ObjectOutputStream every 70 calls //private static final int RESET_FREQUENCY = 70; private static final int RESET_FREQUENCY = 1; private boolean advertiseViaMulticastDNS; private ZeroConfSupport zeroConf; public SocketAppender() { } /** Connects to remote server at address and port. */ public SocketAppender(InetAddress address, int port) { this.address = address; this.remoteHost = address.getHostName(); this.port = port; connect(address, port); } /** Connects to remote server at host and port. */ public SocketAppender(String host, int port) { this.port = port; this.address = getAddressByName(host); this.remoteHost = host; connect(address, port); } /** Connect to the specified RemoteHost and Port. */ public void activateOptions() { if (advertiseViaMulticastDNS) { zeroConf = new ZeroConfSupport(ZONE, port, getName()); zeroConf.advertise(); } connect(address, port); } /** * Close this appender. * *

This will mark the appender as closed and call then {@link * #cleanUp} method. * */ synchronized public void close() { if(closed) return; this.closed = true; if (advertiseViaMulticastDNS) { zeroConf.unadvertise(); } cleanUp(); } /** * Drop the connection to the remote host and release the underlying * connector thread if it has been created * */ public void cleanUp() { if(oos != null) { try { oos.close(); } catch(IOException e) { if (e instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.error("Could not close oos.", e); } oos = null; } if(connector != null) { //LogLog.debug("Interrupting the connector."); connector.interrupted = true; connector = null; // allow gc } } void connect(InetAddress address, int port) { if(this.address == null) return; try { // First, close the previous connection if any. cleanUp(); oos = new ObjectOutputStream(new Socket(address, port).getOutputStream()); } catch(IOException e) { if (e instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } String msg = "Could not connect to remote log4j server at [" +address.getHostName()+"]."; if(reconnectionDelay > 0) { msg += " We will try again later."; fireConnector(); // fire the connector thread } else { msg += " We are not retrying."; errorHandler.error(msg, e, ErrorCode.GENERIC_FAILURE); } LogLog.error(msg); } } public void append(LoggingEvent event) { if(event == null) return; if(address==null) { errorHandler.error("No remote host is set for SocketAppender named \""+ this.name+"\"."); return; } if(oos != null) { try { if(locationInfo) { event.getLocationInformation(); } if (application != null) { event.setProperty("application", application); } event.getNDC(); event.getThreadName(); event.getMDCCopy(); event.getRenderedMessage(); event.getThrowableStrRep(); oos.writeObject(event); //LogLog.debug("=========Flushing."); oos.flush(); if(++counter >= RESET_FREQUENCY) { counter = 0; // Failing to reset the object output stream every now and // then creates a serious memory leak. //System.err.println("Doing oos.reset()"); oos.reset(); } } catch(IOException e) { if (e instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } oos = null; LogLog.warn("Detected problem with connection: "+e); if(reconnectionDelay > 0) { fireConnector(); } else { errorHandler.error("Detected problem with connection, not reconnecting.", e, ErrorCode.GENERIC_FAILURE); } } } } public void setAdvertiseViaMulticastDNS(boolean advertiseViaMulticastDNS) { this.advertiseViaMulticastDNS = advertiseViaMulticastDNS; } public boolean isAdvertiseViaMulticastDNS() { return advertiseViaMulticastDNS; } void fireConnector() { if(connector == null) { LogLog.debug("Starting a new connector thread."); connector = new Connector(); connector.setDaemon(true); connector.setPriority(Thread.MIN_PRIORITY); connector.start(); } } static InetAddress getAddressByName(String host) { try { return InetAddress.getByName(host); } catch(Exception e) { if (e instanceof InterruptedIOException || e instanceof InterruptedException) { Thread.currentThread().interrupt(); } LogLog.error("Could not find address of ["+host+"].", e); return null; } } /** * The SocketAppender does not use a layout. Hence, this method * returns false. * */ public boolean requiresLayout() { return false; } /** * The RemoteHost option takes a string value which should be * the host name of the server where a {@link SocketNode} is * running. * */ public void setRemoteHost(String host) { address = getAddressByName(host); remoteHost = host; } /** Returns value of the RemoteHost option. */ public String getRemoteHost() { return remoteHost; } /** The Port option takes a positive integer representing the port where the server is waiting for connections. */ public void setPort(int port) { this.port = port; } /** Returns value of the Port option. */ public int getPort() { return port; } /** The LocationInfo option takes a boolean value. If true, the information sent to the remote host will include location information. By default no location information is sent to the server. */ public void setLocationInfo(boolean locationInfo) { this.locationInfo = locationInfo; } /** Returns value of the LocationInfo option. */ public boolean getLocationInfo() { return locationInfo; } /** * The App option takes a string value which should be the name of the * application getting logged. * If property was already set (via system property), don't set here. * @since 1.2.15 */ public void setApplication(String lapp) { this.application = lapp; } /** * Returns value of the Application option. * @since 1.2.15 */ public String getApplication() { return application; } /** The ReconnectionDelay 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.

Setting this option to zero turns off reconnection capability. */ public void setReconnectionDelay(int delay) { this.reconnectionDelay = delay; } /** Returns value of the ReconnectionDelay option. */ public 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 reconnectionDelay milliseconds.

It stops trying whenever a connection is established. It will restart to try reconnect to the server when previously open connection is droppped. @author Ceki Gülcü @since 0.8.4 */ class Connector extends Thread { boolean interrupted = false; public void run() { 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()); connector = null; LogLog.debug("Connection established. Exiting connector thread."); break; } } catch(InterruptedException e) { LogLog.debug("Connector interrupted. Leaving loop."); return; } catch(java.net.ConnectException e) { LogLog.debug("Remote host "+address.getHostName() +" refused connection."); } catch(IOException e) { if (e instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.debug("Could not connect to " + address.getHostName()+ ". Exception is " + e); } } //LogLog.debug("Exiting Connector.run() method."); } /** public void finalize() { LogLog.debug("Connector finalize() has been called."); } */ } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/net/SocketNode.java0000644000175000017500000001020611751454710025142 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.net; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InterruptedIOException; import java.io.ObjectInputStream; import java.net.Socket; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.LoggingEvent; // Contributors: Moses Hohman /** Read {@link LoggingEvent} objects sent from a remote client using Sockets (TCP). These logging events are logged according to local policy, as if they were generated locally.

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 { Socket socket; LoggerRepository hierarchy; ObjectInputStream ois; static Logger logger = Logger.getLogger(SocketNode.class); public SocketNode(Socket socket, LoggerRepository hierarchy) { this.socket = socket; this.hierarchy = hierarchy; try { ois = new ObjectInputStream( new BufferedInputStream(socket.getInputStream())); } catch(InterruptedIOException e) { Thread.currentThread().interrupt(); logger.error("Could not open ObjectInputStream to "+socket, e); } catch(IOException e) { logger.error("Could not open ObjectInputStream to "+socket, e); } catch(RuntimeException e) { logger.error("Could not open ObjectInputStream to "+socket, e); } } //public //void finalize() { //System.err.println("-------------------------Finalize called"); // System.err.flush(); //} public void run() { LoggingEvent event; Logger remoteLogger; try { if (ois != null) { while(true) { // read an event from the wire event = (LoggingEvent) ois.readObject(); // get a logger from the hierarchy. The name of the logger is taken to be the name contained in the event. remoteLogger = hierarchy.getLogger(event.getLoggerName()); //event.logger = remoteLogger; // apply the logger-level filter if(event.getLevel().isGreaterOrEqual(remoteLogger.getEffectiveLevel())) { // finally log the event as if was generated locally remoteLogger.callAppenders(event); } } } } catch(java.io.EOFException e) { logger.info("Caught java.io.EOFException closing conneciton."); } catch(java.net.SocketException e) { logger.info("Caught java.net.SocketException closing conneciton."); } catch(InterruptedIOException e) { Thread.currentThread().interrupt(); logger.info("Caught java.io.InterruptedIOException: "+e); logger.info("Closing connection."); } catch(IOException e) { logger.info("Caught java.io.IOException: "+e); logger.info("Closing connection."); } catch(Exception e) { logger.error("Unexpected exception. Closing conneciton.", e); } finally { if (ois != null) { try { ois.close(); } catch(Exception e) { logger.info("Could not close connection.", e); } } if (socket != null) { try { socket.close(); } catch(InterruptedIOException e) { Thread.currentThread().interrupt(); } catch(IOException ex) { } } } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/net/JMSAppender.java0000644000175000017500000003301611751454710025220 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.net; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.spi.ErrorCode; import org.apache.log4j.spi.LoggingEvent; import javax.jms.JMSException; import javax.jms.ObjectMessage; import javax.jms.Session; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicPublisher; import javax.jms.TopicSession; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NameNotFoundException; import javax.naming.NamingException; import java.util.Properties; /** * A simple appender that publishes events to a JMS Topic. The events * are serialized and transmitted as JMS message type {@link * ObjectMessage}. *

JMS {@link Topic topics} and {@link TopicConnectionFactory topic * connection factories} are administered objects that are retrieved * using JNDI messaging which in turn requires the retrieval of a JNDI * {@link Context}. *

There are two common methods for retrieving a JNDI {@link * Context}. If a file resource named jndi.properties is * available to the JNDI API, it will use the information found * therein to retrieve an initial JNDI context. To obtain an initial * context, your code will simply call:

   InitialContext jndiContext = new InitialContext();
   
*

Calling the no-argument InitialContext() method * will also work from within Enterprise Java Beans (EJBs) because it * is part of the EJB contract for application servers to provide each * bean an environment naming context (ENC). *

In the second approach, several predetermined properties are set * and these properties are passed to the InitialContext * constructor to connect to the naming service provider. For example, * to connect to JBoss naming service one would write:

   Properties env = new Properties( );
   env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
   env.put(Context.PROVIDER_URL, "jnp://hostname:1099");
   env.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
   InitialContext jndiContext = new InitialContext(env);
* where hostname is the host where the JBoss application * server is running. * *

To connect to the the naming service of Weblogic application * server one would write:

   Properties env = new Properties( );
   env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
   env.put(Context.PROVIDER_URL, "t3://localhost:7001");
   InitialContext jndiContext = new InitialContext(env);
*

Other JMS providers will obviously require different values. * * The initial JNDI context can be obtained by calling the * no-argument InitialContext() method in EJBs. Only * clients running in a separate JVM need to be concerned about the * jndi.properties file and calling {@link * InitialContext#InitialContext()} or alternatively correctly * setting the different properties before calling {@link * InitialContext#InitialContext(java.util.Hashtable)} method. @author Ceki Gülcü */ public class JMSAppender extends AppenderSkeleton { String securityPrincipalName; String securityCredentials; String initialContextFactoryName; String urlPkgPrefixes; String providerURL; String topicBindingName; String tcfBindingName; String userName; String password; boolean locationInfo; TopicConnection topicConnection; TopicSession topicSession; TopicPublisher topicPublisher; public JMSAppender() { } /** The TopicConnectionFactoryBindingName option takes a string value. Its value will be used to lookup the appropriate TopicConnectionFactory from the JNDI context. */ public void setTopicConnectionFactoryBindingName(String tcfBindingName) { this.tcfBindingName = tcfBindingName; } /** Returns the value of the TopicConnectionFactoryBindingName option. */ public String getTopicConnectionFactoryBindingName() { return tcfBindingName; } /** The TopicBindingName option takes a string value. Its value will be used to lookup the appropriate Topic from the JNDI context. */ public void setTopicBindingName(String topicBindingName) { this.topicBindingName = topicBindingName; } /** Returns the value of the TopicBindingName option. */ public String getTopicBindingName() { return topicBindingName; } /** Returns value of the LocationInfo property which determines whether location (stack) info is sent to the remote subscriber. */ public boolean getLocationInfo() { return locationInfo; } /** * Options are activated and become effective only after calling * this method.*/ public void activateOptions() { TopicConnectionFactory topicConnectionFactory; try { Context jndi; LogLog.debug("Getting initial context."); if(initialContextFactoryName != null) { Properties env = new Properties( ); env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactoryName); if(providerURL != null) { env.put(Context.PROVIDER_URL, providerURL); } else { LogLog.warn("You have set InitialContextFactoryName option but not the " +"ProviderURL. This is likely to cause problems."); } if(urlPkgPrefixes != null) { env.put(Context.URL_PKG_PREFIXES, urlPkgPrefixes); } if(securityPrincipalName != null) { env.put(Context.SECURITY_PRINCIPAL, securityPrincipalName); if(securityCredentials != null) { env.put(Context.SECURITY_CREDENTIALS, securityCredentials); } else { LogLog.warn("You have set SecurityPrincipalName option but not the " +"SecurityCredentials. This is likely to cause problems."); } } jndi = new InitialContext(env); } else { jndi = new InitialContext(); } LogLog.debug("Looking up ["+tcfBindingName+"]"); topicConnectionFactory = (TopicConnectionFactory) lookup(jndi, tcfBindingName); LogLog.debug("About to create TopicConnection."); if(userName != null) { topicConnection = topicConnectionFactory.createTopicConnection(userName, password); } else { topicConnection = topicConnectionFactory.createTopicConnection(); } LogLog.debug("Creating TopicSession, non-transactional, " +"in AUTO_ACKNOWLEDGE mode."); topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); LogLog.debug("Looking up topic name ["+topicBindingName+"]."); Topic topic = (Topic) lookup(jndi, topicBindingName); LogLog.debug("Creating TopicPublisher."); topicPublisher = topicSession.createPublisher(topic); LogLog.debug("Starting TopicConnection."); topicConnection.start(); jndi.close(); } catch(JMSException e) { errorHandler.error("Error while activating options for appender named ["+name+ "].", e, ErrorCode.GENERIC_FAILURE); } catch(NamingException e) { errorHandler.error("Error while activating options for appender named ["+name+ "].", e, ErrorCode.GENERIC_FAILURE); } catch(RuntimeException 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 { return ctx.lookup(name); } catch(NameNotFoundException e) { LogLog.error("Could not find name ["+name+"]."); throw e; } } protected boolean checkEntryConditions() { String fail = null; if(this.topicConnection == null) { fail = "No TopicConnection"; } else if(this.topicSession == null) { fail = "No TopicSession"; } else if(this.topicPublisher == null) { fail = "No TopicPublisher"; } if(fail != null) { errorHandler.error(fail +" for JMSAppender named ["+name+"]."); return false; } else { return true; } } /** Close this JMSAppender. Closing releases all resources used by the appender. A closed appender cannot be re-opened. */ public synchronized void close() { // The synchronized modifier avoids concurrent append and close operations if(this.closed) return; LogLog.debug("Closing appender ["+name+"]."); this.closed = true; try { if(topicSession != null) topicSession.close(); if(topicConnection != null) topicConnection.close(); } catch(JMSException e) { LogLog.error("Error while closing JMSAppender ["+name+"].", e); } catch(RuntimeException e) { LogLog.error("Error while closing JMSAppender ["+name+"].", e); } // Help garbage collection topicPublisher = null; topicSession = null; topicConnection = null; } /** This method called by {@link AppenderSkeleton#doAppend} method to do most of the real appending work. */ public void append(LoggingEvent event) { if(!checkEntryConditions()) { return; } try { ObjectMessage msg = topicSession.createObjectMessage(); if(locationInfo) { event.getLocationInformation(); } msg.setObject(event); topicPublisher.publish(msg); } catch(JMSException e) { errorHandler.error("Could not publish message in JMSAppender ["+name+"].", e, ErrorCode.GENERIC_FAILURE); } catch(RuntimeException e) { errorHandler.error("Could not publish message in JMSAppender ["+name+"].", e, ErrorCode.GENERIC_FAILURE); } } /** * Returns the value of the InitialContextFactoryName option. * See {@link #setInitialContextFactoryName} for more details on the * meaning of this option. * */ public String getInitialContextFactoryName() { return initialContextFactoryName; } /** * Setting the InitialContextFactoryName method will cause * this JMSAppender instance to use the {@link * InitialContext#InitialContext(Hashtable)} method instead of the * no-argument constructor. If you set this option, you should also * at least set the ProviderURL option. * *

See also {@link #setProviderURL(String)}. * */ public void setInitialContextFactoryName(String initialContextFactoryName) { this.initialContextFactoryName = initialContextFactoryName; } public String getProviderURL() { return providerURL; } public void setProviderURL(String providerURL) { this.providerURL = providerURL; } String getURLPkgPrefixes( ) { return urlPkgPrefixes; } public void setURLPkgPrefixes(String urlPkgPrefixes ) { this.urlPkgPrefixes = urlPkgPrefixes; } public String getSecurityCredentials() { return securityCredentials; } public void setSecurityCredentials(String securityCredentials) { this.securityCredentials = securityCredentials; } public String getSecurityPrincipalName() { return securityPrincipalName; } public void setSecurityPrincipalName(String securityPrincipalName) { this.securityPrincipalName = securityPrincipalName; } public String getUserName() { return userName; } /** * The user name to use when {@link * TopicConnectionFactory#createTopicConnection(String, String) * creating a topic session}. If you set this option, you should * also set the Password option. See {@link * #setPassword(String)}. * */ public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } /** * The paswword to use when creating a topic session. */ public void setPassword(String password) { this.password = password; } /** If true, the information sent to the remote subscriber will include caller's location information. By default no location information is sent to the subscriber. */ public void setLocationInfo(boolean locationInfo) { this.locationInfo = locationInfo; } /** * Returns the TopicConnection used for this appender. Only valid after * activateOptions() method has been invoked. */ protected TopicConnection getTopicConnection() { return topicConnection; } /** * Returns the TopicSession used for this appender. Only valid after * activateOptions() method has been invoked. */ protected TopicSession getTopicSession() { return topicSession; } /** * Returns the TopicPublisher used for this appender. Only valid after * activateOptions() method has been invoked. */ protected TopicPublisher getTopicPublisher() { return topicPublisher; } /** * The JMSAppender sends serialized events and consequently does not * require a layout. */ public boolean requiresLayout() { return false; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/net/SMTPAppender.java0000644000175000017500000005165311751454710025361 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 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.LogLog; import org.apache.log4j.helpers.OptionConverter; import org.apache.log4j.spi.ErrorCode; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.OptionHandler; import org.apache.log4j.spi.TriggeringEventEvaluator; import org.apache.log4j.xml.UnrecognizedElementHandler; import org.w3c.dom.Element; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.InternetHeaders; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.Date; import java.util.Properties; /** Send an e-mail when a specific logging event occurs, typically on errors or fatal errors.

The number of logging events delivered in this e-mail depend on the value of BufferSize option. The SMTPAppender keeps only the last BufferSize logging events in its cyclic buffer. This keeps memory requirements at a reasonable level while still delivering useful application context. By default, an email message will be sent when an ERROR or higher severity message is appended. The triggering criteria can be modified by setting the evaluatorClass property with the name of a class implementing TriggeringEventEvaluator, setting the evaluator property with an instance of TriggeringEventEvaluator or nesting a triggeringPolicy element where the specified class implements TriggeringEventEvaluator. This class has implemented UnrecognizedElementHandler since 1.2.15. Since 1.2.16, SMTP over SSL is supported by setting SMTPProtocol to "smpts". @author Ceki Gülcü @since 1.0 */ public class SMTPAppender extends AppenderSkeleton implements UnrecognizedElementHandler { private String to; /** * Comma separated list of cc recipients. */ private String cc; /** * Comma separated list of bcc recipients. */ private String bcc; private String from; /** * Comma separated list of replyTo addresses. */ private String replyTo; private String subject; private String smtpHost; private String smtpUsername; private String smtpPassword; private String smtpProtocol; private int smtpPort = -1; private boolean smtpDebug = false; private int bufferSize = 512; private boolean locationInfo = false; private boolean sendOnClose = false; protected CyclicBuffer cb = new CyclicBuffer(bufferSize); protected Message msg; protected TriggeringEventEvaluator evaluator; /** The default constructor will instantiate the appender with a {@link TriggeringEventEvaluator} that will trigger on events with level ERROR or higher.*/ public SMTPAppender() { this(new DefaultEvaluator()); } /** Use evaluator passed as parameter as the {@link TriggeringEventEvaluator} for this SMTPAppender. */ public SMTPAppender(TriggeringEventEvaluator evaluator) { this.evaluator = evaluator; } /** Activate the specified options, such as the smtp host, the recipient, from, etc. */ public void activateOptions() { Session session = createSession(); msg = new MimeMessage(session); try { addressMessage(msg); if(subject != null) { try { msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", null)); } catch(UnsupportedEncodingException ex) { LogLog.error("Unable to encode SMTP subject", ex); } } } catch(MessagingException e) { LogLog.error("Could not activate SMTPAppender options.", e ); } if (evaluator instanceof OptionHandler) { ((OptionHandler) evaluator).activateOptions(); } } /** * Address message. * @param msg message, may not be null. * @throws MessagingException thrown if error addressing message. * @since 1.2.14 */ protected void addressMessage(final Message msg) throws MessagingException { if (from != null) { msg.setFrom(getAddress(from)); } else { msg.setFrom(); } //Add ReplyTo addresses if defined. if (replyTo != null && replyTo.length() > 0) { msg.setReplyTo(parseAddress(replyTo)); } if (to != null && to.length() > 0) { msg.setRecipients(Message.RecipientType.TO, parseAddress(to)); } //Add CC receipients if defined. if (cc != null && cc.length() > 0) { msg.setRecipients(Message.RecipientType.CC, parseAddress(cc)); } //Add BCC receipients if defined. if (bcc != null && bcc.length() > 0) { msg.setRecipients(Message.RecipientType.BCC, parseAddress(bcc)); } } /** * Create mail session. * @return mail session, may not be null. * @since 1.2.14 */ protected Session createSession() { Properties props = null; try { props = new Properties (System.getProperties()); } catch(SecurityException ex) { props = new Properties(); } String prefix = "mail.smtp"; if (smtpProtocol != null) { props.put("mail.transport.protocol", smtpProtocol); prefix = "mail." + smtpProtocol; } if (smtpHost != null) { props.put(prefix + ".host", smtpHost); } if (smtpPort > 0) { props.put(prefix + ".port", String.valueOf(smtpPort)); } Authenticator auth = null; if(smtpPassword != null && smtpUsername != null) { props.put(prefix + ".auth", "true"); auth = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(smtpUsername, smtpPassword); } }; } Session session = Session.getInstance(props, auth); if (smtpProtocol != null) { session.setProtocolForAddress("rfc822", smtpProtocol); } if (smtpDebug) { session.setDebug(smtpDebug); } return session; } /** Perform SMTPAppender specific appending actions, mainly adding the event to a cyclic buffer and checking if the event triggers an e-mail to be sent. */ public void append(LoggingEvent event) { if(!checkEntryConditions()) { return; } event.getThreadName(); event.getNDC(); event.getMDCCopy(); if(locationInfo) { event.getLocationInformation(); } event.getRenderedMessage(); event.getThrowableStrRep(); cb.add(event); if(evaluator.isTriggeringEvent(event)) { sendBuffer(); } } /** This method determines if there is a sense in attempting to append.

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 false is returned. */ protected boolean checkEntryConditions() { if(this.msg == null) { errorHandler.error("Message object not configured."); return false; } if(this.evaluator == null) { errorHandler.error("No TriggeringEventEvaluator is set for appender ["+ name+"]."); return false; } if(this.layout == null) { errorHandler.error("No layout set for appender named ["+name+"]."); return false; } return true; } synchronized public void close() { this.closed = true; if (sendOnClose && cb.length() > 0) { sendBuffer(); } } InternetAddress getAddress(String addressStr) { try { return new InternetAddress(addressStr); } catch(AddressException e) { errorHandler.error("Could not parse address ["+addressStr+"].", e, ErrorCode.ADDRESS_PARSE_FAILURE); return null; } } InternetAddress[] parseAddress(String addressStr) { try { return InternetAddress.parse(addressStr, true); } catch(AddressException e) { errorHandler.error("Could not parse address ["+addressStr+"].", e, ErrorCode.ADDRESS_PARSE_FAILURE); return null; } } /** Returns value of the To option. */ public String getTo() { return to; } /** The SMTPAppender requires a {@link org.apache.log4j.Layout layout}. */ public boolean requiresLayout() { return true; } /** * Layout body of email message. * @since 1.2.16 */ protected String formatBody() { // Note: this code already owns the monitor for this // appender. This frees us from needing to synchronize on 'cb'. StringBuffer sbuf = new StringBuffer(); String t = layout.getHeader(); if(t != null) sbuf.append(t); int len = cb.length(); for(int i = 0; i < len; i++) { //sbuf.append(MimeUtility.encodeText(layout.format(cb.get()))); LoggingEvent event = cb.get(); sbuf.append(layout.format(event)); if(layout.ignoresThrowable()) { String[] s = event.getThrowableStrRep(); if (s != null) { for(int j = 0; j < s.length; j++) { sbuf.append(s[j]); sbuf.append(Layout.LINE_SEP); } } } } t = layout.getFooter(); if(t != null) { sbuf.append(t); } return sbuf.toString(); } /** Send the contents of the cyclic buffer as an e-mail message. */ protected void sendBuffer() { try { String s = formatBody(); boolean allAscii = true; for(int i = 0; i < s.length() && allAscii; i++) { allAscii = s.charAt(i) <= 0x7F; } MimeBodyPart part; if (allAscii) { part = new MimeBodyPart(); part.setContent(s, layout.getContentType()); } else { try { ByteArrayOutputStream os = new ByteArrayOutputStream(); Writer writer = new OutputStreamWriter( MimeUtility.encode(os, "quoted-printable"), "UTF-8"); writer.write(s); writer.close(); InternetHeaders headers = new InternetHeaders(); headers.setHeader("Content-Type", layout.getContentType() + "; charset=UTF-8"); headers.setHeader("Content-Transfer-Encoding", "quoted-printable"); part = new MimeBodyPart(headers, os.toByteArray()); } catch(Exception ex) { StringBuffer sbuf = new StringBuffer(s); for (int i = 0; i < sbuf.length(); i++) { if (sbuf.charAt(i) >= 0x80) { sbuf.setCharAt(i, '?'); } } part = new MimeBodyPart(); part.setContent(sbuf.toString(), layout.getContentType()); } } Multipart mp = new MimeMultipart(); mp.addBodyPart(part); msg.setContent(mp); msg.setSentDate(new Date()); Transport.send(msg); } catch(MessagingException e) { LogLog.error("Error occured while sending e-mail notification.", e); } catch(RuntimeException e) { LogLog.error("Error occured while sending e-mail notification.", e); } } /** Returns value of the EvaluatorClass option. */ public String getEvaluatorClass() { return evaluator == null ? null : evaluator.getClass().getName(); } /** Returns value of the From option. */ public String getFrom() { return from; } /** Get the reply addresses. @return reply addresses as comma separated string, may be null. @since 1.2.16 */ public String getReplyTo() { return replyTo; } /** Returns value of the Subject option. */ public String getSubject() { return subject; } /** The From option takes a string value which should be a e-mail address of the sender. */ public void setFrom(String from) { this.from = from; } /** Set the e-mail addresses to which replies should be directed. @param addresses reply addresses as comma separated string, may be null. @since 1.2.16 */ public void setReplyTo(final String addresses) { this.replyTo = addresses; } /** The Subject option takes a string value which should be a the subject of the e-mail message. */ public void setSubject(String subject) { this.subject = subject; } /** The BufferSize option takes a positive integer representing the maximum number of logging events to collect in a cyclic buffer. When the BufferSize is reached, oldest events are deleted as new events are added to the buffer. By default the size of the cyclic buffer is 512 events. */ public void setBufferSize(int bufferSize) { this.bufferSize = bufferSize; cb.resize(bufferSize); } /** The SMTPHost option takes a string value which should be a the host name of the SMTP server that will send the e-mail message. */ public void setSMTPHost(String smtpHost) { this.smtpHost = smtpHost; } /** Returns value of the SMTPHost option. */ public String getSMTPHost() { return smtpHost; } /** The To option takes a string value which should be a comma separated list of e-mail address of the recipients. */ public void setTo(String to) { this.to = to; } /** Returns value of the BufferSize option. */ public int getBufferSize() { return bufferSize; } /** The EvaluatorClass option takes a string value representing the name of the class implementing the {@link TriggeringEventEvaluator} interface. A corresponding object will be instantiated and assigned as the triggering event evaluator for the SMTPAppender. */ public void setEvaluatorClass(String value) { evaluator = (TriggeringEventEvaluator) OptionConverter.instantiateByClassName(value, TriggeringEventEvaluator.class, evaluator); } /** The LocationInfo option takes a boolean value. By default, it is set to false which means there will be no effort to extract the location information related to the event. As a 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).

Location information extraction is comparatively very slow and should be avoided unless performance is not a concern. */ public void setLocationInfo(boolean locationInfo) { this.locationInfo = locationInfo; } /** Returns value of the LocationInfo option. */ public boolean getLocationInfo() { return locationInfo; } /** Set the cc recipient addresses. @param addresses recipient addresses as comma separated string, may be null. @since 1.2.14 */ public void setCc(final String addresses) { this.cc = addresses; } /** Get the cc recipient addresses. @return recipient addresses as comma separated string, may be null. @since 1.2.14 */ public String getCc() { return cc; } /** Set the bcc recipient addresses. @param addresses recipient addresses as comma separated string, may be null. @since 1.2.14 */ public void setBcc(final String addresses) { this.bcc = addresses; } /** Get the bcc recipient addresses. @return recipient addresses as comma separated string, may be null. @since 1.2.14 */ public String getBcc() { return bcc; } /** * The SmtpPassword option takes a string value which should be the password required to authenticate against * the mail server. * @param password password, may be null. * @since 1.2.14 */ public void setSMTPPassword(final String password) { this.smtpPassword = password; } /** * The SmtpUsername option takes a string value which should be the username required to authenticate against * the mail server. * @param username user name, may be null. * @since 1.2.14 */ public void setSMTPUsername(final String username) { this.smtpUsername = username; } /** * Setting the SmtpDebug option to true will cause the mail session to log its server interaction to stdout. * This can be useful when debuging the appender but should not be used during production because username and * password information is included in the output. * @param debug debug flag. * @since 1.2.14 */ public void setSMTPDebug(final boolean debug) { this.smtpDebug = debug; } /** * Get SMTP password. * @return SMTP password, may be null. * @since 1.2.14 */ public String getSMTPPassword() { return smtpPassword; } /** * Get SMTP user name. * @return SMTP user name, may be null. * @since 1.2.14 */ public String getSMTPUsername() { return smtpUsername; } /** * Get SMTP debug. * @return SMTP debug flag. * @since 1.2.14 */ public boolean getSMTPDebug() { return smtpDebug; } /** * Sets triggering evaluator. * @param trigger triggering event evaluator. * @since 1.2.15 */ public final void setEvaluator(final TriggeringEventEvaluator trigger) { if (trigger == null) { throw new NullPointerException("trigger"); } this.evaluator = trigger; } /** * Get triggering evaluator. * @return triggering event evaluator. * @since 1.2.15 */ public final TriggeringEventEvaluator getEvaluator() { return evaluator; } /** {@inheritDoc} * @since 1.2.15 */ public boolean parseUnrecognizedElement(final Element element, final Properties props) throws Exception { if ("triggeringPolicy".equals(element.getNodeName())) { Object triggerPolicy = org.apache.log4j.xml.DOMConfigurator.parseElement( element, props, TriggeringEventEvaluator.class); if (triggerPolicy instanceof TriggeringEventEvaluator) { setEvaluator((TriggeringEventEvaluator) triggerPolicy); } return true; } return false; } /** * Get transport protocol. * Typically null or "smtps". * * @return transport protocol, may be null. * @since 1.2.16 */ public final String getSMTPProtocol() { return smtpProtocol; } /** * Set transport protocol. * Typically null or "smtps". * * @param val transport protocol, may be null. * @since 1.2.16 */ public final void setSMTPProtocol(final String val) { smtpProtocol = val; } /** * Get port. * * @return port, negative values indicate use of default ports for protocol. * @since 1.2.16 */ public final int getSMTPPort() { return smtpPort; } /** * Set port. * * @param val port, negative values indicate use of default ports for protocol. * @since 1.2.16 */ public final void setSMTPPort(final int val) { smtpPort = val; } /** * Get sendOnClose. * * @return if true all buffered logging events will be sent when the appender is closed. * @since 1.2.16 */ public final boolean getSendOnClose() { return sendOnClose; } /** * Set sendOnClose. * * @param val if true all buffered logging events will be sent when appender is closed. * @since 1.2.16 */ public final void setSendOnClose(final boolean val) { sendOnClose = val; } } class DefaultEvaluator implements TriggeringEventEvaluator { /** Is this event the e-mail triggering event?

This method returns true, if the event level has ERROR level or higher. Otherwise it returns false. */ public boolean isTriggeringEvent(LoggingEvent event) { return event.getLevel().isGreaterOrEqual(Level.ERROR); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/net/SocketServer.java0000644000175000017500000001573211751454710025534 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.net; import java.io.File; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.Hashtable; import org.apache.log4j.Hierarchy; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.RootLogger; /** A {@link SocketNode} based server that uses a different hierarchy for each client.

     Usage: java org.apache.log4j.net.SocketServer port configFile configDir

     where port is a part number where the server listens,
           configFile is a configuration file fed to the {@link PropertyConfigurator} and
           configDir is a path to a directory containing configuration files, possibly one for each client host.
     

The configFile is used to configure the log4j default hierarchy that the SocketServer will use to report on its actions.

When a new connection is opened from a previously unknown host, say foo.bar.net, then the SocketServer will search for a configuration file called foo.bar.net.lcf under the directory configDir that was passed as the third argument. If the file can be found, then a new hierarchy is instantiated and configured using the configuration file foo.bar.net.lcf. If and when the host foo.bar.net opens another connection to the server, then the previously configured hierarchy is used.

In case there is no file called foo.bar.net.lcf under the directory configDir, then the generic hierarchy is used. The generic hierarchy is configured using a configuration file called generic.lcf under the configDir directory. If no such file exists, then the generic hierarchy will be identical to the log4j default hierarchy.

Having different client hosts log using different hierarchies ensures the total independence of the clients with respect to their logging settings.

Currently, the hierarchy that will be used for a given request depends on the IP address of the client host. For example, two separate applicatons running on the same host and logging to the same server will share the same hierarchy. This is perfectly safe except that it might not provide the right amount of independence between applications. The SocketServer is intended as an example to be enhanced in order to implement more elaborate policies. @author Ceki Gülcü @since 1.0 */ public class SocketServer { static String GENERIC = "generic"; static String CONFIG_FILE_EXT = ".lcf"; static Logger cat = Logger.getLogger(SocketServer.class); static SocketServer server; static int port; // key=inetAddress, value=hierarchy Hashtable hierarchyMap; LoggerRepository genericHierarchy; File dir; public static void main(String argv[]) { if(argv.length == 3) init(argv[0], argv[1], argv[2]); else usage("Wrong number of arguments."); try { cat.info("Listening on port " + port); ServerSocket serverSocket = new ServerSocket(port); while(true) { cat.info("Waiting to accept a new client."); Socket socket = serverSocket.accept(); InetAddress inetAddress = socket.getInetAddress(); cat.info("Connected to client at " + inetAddress); LoggerRepository h = (LoggerRepository) server.hierarchyMap.get(inetAddress); if(h == null) { h = server.configureHierarchy(inetAddress); } cat.info("Starting new socket node."); new Thread(new SocketNode(socket, h)).start(); } } catch(Exception e) { e.printStackTrace(); } } static void usage(String msg) { System.err.println(msg); System.err.println( "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); } catch(java.lang.NumberFormatException e) { e.printStackTrace(); usage("Could not interpret port number ["+ portStr +"]."); } PropertyConfigurator.configure(configFile); File dir = new File(dirStr); if(!dir.isDirectory()) { usage("["+dirStr+"] is not a directory."); } server = new SocketServer(dir); } public SocketServer(File directory) { this.dir = directory; hierarchyMap = new Hashtable(11); } // This method assumes that there is no hiearchy for inetAddress // yet. It will configure one and return it. LoggerRepository configureHierarchy(InetAddress inetAddress) { cat.info("Locating configuration file for "+inetAddress); // We assume that the toSting method of InetAddress returns is in // the format hostname/d1.d2.d3.d4 e.g. torino/192.168.1.1 String s = inetAddress.toString(); int i = s.indexOf("/"); if(i == -1) { cat.warn("Could not parse the inetAddress ["+inetAddress+ "]. Using default hierarchy."); 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 RootLogger(Level.DEBUG)); hierarchyMap.put(inetAddress, h); new PropertyConfigurator().doConfigure(configFile.getAbsolutePath(), h); return h; } else { cat.warn("Could not find config file ["+configFile+"]."); return genericHierarchy(); } } } LoggerRepository genericHierarchy() { if(genericHierarchy == null) { File f = new File(dir, GENERIC+CONFIG_FILE_EXT); if(f.exists()) { genericHierarchy = new Hierarchy(new RootLogger(Level.DEBUG)); new PropertyConfigurator().doConfigure(f.getAbsolutePath(), genericHierarchy); } else { cat.warn("Could not find config file ["+f+ "]. Will use the default hierarchy."); genericHierarchy = LogManager.getLoggerRepository(); } } return genericHierarchy; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/net/SocketHubAppender.java0000644000175000017500000003667511751454710026474 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.net; import java.io.IOException; import java.io.InterruptedIOException; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.Vector; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.helpers.CyclicBuffer; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.spi.LoggingEvent; /** Sends {@link LoggingEvent} objects to a set of remote log servers, usually a {@link SocketNode SocketNodes}.

Acts just like {@link SocketAppender} except that instead of connecting to a given remote log server, SocketHubAppender accepts connections from the remote log servers as clients. It can accept more than one connection. When a log event is received, the event is sent to the set of currently connected remote log servers. Implemented this way it does not require any update to the configuration file to send data to another remote log server. The remote log server simply connects to the host and port the SocketHubAppender is running on.

The SocketHubAppender does not store events such that the remote side will events that arrived after the establishment of its connection. Once connected, events arrive in order as guaranteed by the TCP protocol.

This implementation borrows heavily from the {@link SocketAppender}.

The SocketHubAppender has the following characteristics:

  • If sent to a {@link SocketNode}, logging is non-intrusive as far as the log event is concerned. In other words, the event will be logged with the same time stamp, {@link org.apache.log4j.NDC}, location info as if it were logged locally.

  • SocketHubAppender does not use a layout. It ships a serialized {@link LoggingEvent} object to the remote side.

  • SocketHubAppender relies on the TCP protocol. Consequently, if the remote side is reachable, then log events will eventually arrive at remote client.

  • If no remote clients are attached, the logging requests are simply dropped.

  • Logging events are automatically buffered by the native TCP implementation. This means that if the link to remote client is slow but still faster than the rate of (log) event production, the application will not be affected by the slow network connection. However, if the network connection is slower then the rate of event production, then the local application can only progress at the network rate. In particular, if the network link to the the remote client is down, the application will be blocked.

    On the other hand, if the network link is up, but the remote client is down, the client will not be blocked when making log requests but the log events will be lost due to client unavailability.

    The single remote client case extends to multiple clients connections. The rate of logging will be determined by the slowest link.

  • If the JVM hosting the SocketHubAppender exits before the SocketHubAppender is closed either explicitly or subsequent to garbage collection, then there might be untransmitted data in the pipe which might be lost. This is a common problem on Windows based systems.

    To avoid lost data, it is usually sufficient to {@link #close} the SocketHubAppender either explicitly or by calling the {@link org.apache.log4j.LogManager#shutdown} method before exiting the application.

@author Mark Womack */ public class SocketHubAppender extends AppenderSkeleton { /** The default port number of the ServerSocket will be created on. */ static final int DEFAULT_PORT = 4560; private int port = DEFAULT_PORT; private Vector oosList = new Vector(); private ServerMonitor serverMonitor = null; private boolean locationInfo = false; private CyclicBuffer buffer = null; private String application; private boolean advertiseViaMulticastDNS; private ZeroConfSupport zeroConf; /** * The MulticastDNS zone advertised by a SocketHubAppender */ public static final String ZONE = "_log4j_obj_tcpaccept_appender.local."; private ServerSocket serverSocket; public SocketHubAppender() { } /** Connects to remote server at address and port. */ public SocketHubAppender(int _port) { port = _port; startServer(); } /** Set up the socket server on the specified port. */ public void activateOptions() { if (advertiseViaMulticastDNS) { zeroConf = new ZeroConfSupport(ZONE, port, getName()); zeroConf.advertise(); } startServer(); } /** Close this appender.

This will mark the appender as closed and call then {@link #cleanUp} method. */ synchronized public void close() { if(closed) return; LogLog.debug("closing SocketHubAppender " + getName()); this.closed = true; if (advertiseViaMulticastDNS) { zeroConf.unadvertise(); } cleanUp(); LogLog.debug("SocketHubAppender " + getName() + " closed"); } /** Release the underlying ServerMonitor thread, and drop the connections to all connected remote servers. */ public void cleanUp() { // stop the monitor thread LogLog.debug("stopping ServerSocket"); serverMonitor.stopMonitor(); serverMonitor = null; // close all of the connections LogLog.debug("closing client connections"); while (oosList.size() != 0) { ObjectOutputStream oos = (ObjectOutputStream)oosList.elementAt(0); if(oos != null) { try { oos.close(); } catch(InterruptedIOException e) { Thread.currentThread().interrupt(); LogLog.error("could not close oos.", e); } catch(IOException e) { LogLog.error("could not close oos.", e); } oosList.removeElementAt(0); } } } /** Append an event to all of current connections. */ public void append(LoggingEvent event) { if (event != null) { // set up location info if requested if (locationInfo) { event.getLocationInformation(); } if (application != null) { event.setProperty("application", application); } event.getNDC(); event.getThreadName(); event.getMDCCopy(); event.getRenderedMessage(); event.getThrowableStrRep(); if (buffer != null) { buffer.add(event); } } // if no event or no open connections, exit now if ((event == null) || (oosList.size() == 0)) { return; } // loop through the current set of open connections, appending the event to each for (int streamCount = 0; streamCount < oosList.size(); streamCount++) { ObjectOutputStream oos = null; try { oos = (ObjectOutputStream)oosList.elementAt(streamCount); } catch (ArrayIndexOutOfBoundsException e) { // catch this, but just don't assign a value // this should not really occur as this method is // the only one that can remove oos's (besides cleanUp). } // list size changed unexpectedly? Just exit the append. if (oos == null) break; try { oos.writeObject(event); oos.flush(); // Failing to reset the object output stream every now and // then creates a serious memory leak. // right now we always reset. TODO - set up frequency counter per oos? oos.reset(); } catch(IOException e) { if (e instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } // there was an io exception so just drop the connection oosList.removeElementAt(streamCount); LogLog.debug("dropped connection"); // decrement to keep the counter in place (for loop always increments) streamCount--; } } } /** The SocketHubAppender does not use a layout. Hence, this method returns false. */ public boolean requiresLayout() { return false; } /** The Port option takes a positive integer representing the port where the server is waiting for connections. */ public void setPort(int _port) { port = _port; } /** * The App option takes a string value which should be the name of the application getting logged. If property was already set (via system * property), don't set here. */ public void setApplication(String lapp) { this.application = lapp; } /** * Returns value of the Application option. */ public String getApplication() { return application; } /** Returns value of the Port option. */ public int getPort() { return port; } /** * The BufferSize option takes a positive integer representing the number of events this appender will buffer and send to newly connected * clients. */ public void setBufferSize(int _bufferSize) { buffer = new CyclicBuffer(_bufferSize); } /** * Returns value of the bufferSize option. */ public int getBufferSize() { if (buffer == null) { return 0; } else { return buffer.getMaxSize(); } } /** The LocationInfo option takes a boolean value. If true, the information sent to the remote host will include location information. By default no location information is sent to the server. */ public void setLocationInfo(boolean _locationInfo) { locationInfo = _locationInfo; } /** Returns value of the LocationInfo option. */ public boolean getLocationInfo() { return locationInfo; } public void setAdvertiseViaMulticastDNS(boolean advertiseViaMulticastDNS) { this.advertiseViaMulticastDNS = advertiseViaMulticastDNS; } public boolean isAdvertiseViaMulticastDNS() { return advertiseViaMulticastDNS; } /** Start the ServerMonitor thread. */ private void startServer() { serverMonitor = new ServerMonitor(port, oosList); } /** * Creates a server socket to accept connections. * @param socketPort port on which the socket should listen, may be zero. * @return new socket. * @throws IOException IO error when opening the socket. */ protected ServerSocket createServerSocket(final int socketPort) throws IOException { return new ServerSocket(socketPort); } /** This class is used internally to monitor a ServerSocket and register new connections in a vector passed in the constructor. */ private class ServerMonitor implements Runnable { private int port; private Vector oosList; private boolean keepRunning; private Thread monitorThread; /** Create a thread and start the monitor. */ public ServerMonitor(int _port, Vector _oosList) { port = _port; oosList = _oosList; keepRunning = true; monitorThread = new Thread(this); monitorThread.setDaemon(true); monitorThread.setName("SocketHubAppender-Monitor-" + port); monitorThread.start(); } /** Stops the monitor. This method will not return until the thread has finished executing. */ public synchronized void stopMonitor() { if (keepRunning) { LogLog.debug("server monitor thread shutting down"); keepRunning = false; try { if (serverSocket != null) { serverSocket.close(); serverSocket = null; } } catch (IOException ioe) {} try { monitorThread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // do nothing? } // release the thread monitorThread = null; LogLog.debug("server monitor thread shut down"); } } private void sendCachedEvents(ObjectOutputStream stream) throws IOException { if (buffer != null) { for (int i = 0; i < buffer.length(); i++) { stream.writeObject(buffer.get(i)); } stream.flush(); stream.reset(); } } /** Method that runs, monitoring the ServerSocket and adding connections as they connect to the socket. */ public void run() { serverSocket = null; try { serverSocket = createServerSocket(port); serverSocket.setSoTimeout(1000); } catch (Exception e) { if (e instanceof InterruptedIOException || e instanceof InterruptedException) { Thread.currentThread().interrupt(); } LogLog.error("exception setting timeout, shutting down server socket.", e); keepRunning = false; return; } try { try { serverSocket.setSoTimeout(1000); } catch (SocketException e) { LogLog.error("exception setting timeout, shutting down server socket.", e); return; } while (keepRunning) { Socket socket = null; try { socket = serverSocket.accept(); } catch (InterruptedIOException e) { // timeout occurred, so just loop } catch (SocketException e) { LogLog.error("exception accepting socket, shutting down server socket.", e); keepRunning = false; } catch (IOException e) { LogLog.error("exception accepting socket.", e); } // if there was a socket accepted if (socket != null) { try { InetAddress remoteAddress = socket.getInetAddress(); LogLog.debug("accepting connection from " + remoteAddress.getHostName() + " (" + remoteAddress.getHostAddress() + ")"); // create an ObjectOutputStream ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); if (buffer != null && buffer.length() > 0) { sendCachedEvents(oos); } // add it to the oosList. OK since Vector is synchronized. oosList.addElement(oos); } catch (IOException e) { if (e instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.error("exception creating output stream on socket.", e); } } } } finally { // close the socket try { serverSocket.close(); } catch(InterruptedIOException e) { Thread.currentThread().interrupt(); } catch (IOException e) { // do nothing with it? } } } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/EnhancedPatternLayout.java0000644000175000017500000004371411751454711026572 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.helpers.OptionConverter; import org.apache.log4j.helpers.PatternConverter; import org.apache.log4j.pattern.BridgePatternConverter; import org.apache.log4j.spi.LoggingEvent; // Contributors: Nelson Minar // Anders Kristensen /** * This class is an enhanced version of org.apache.log4j.PatternLayout * which was originally developed as part of the abandoned log4j 1.3 * effort and has been available in the extras companion. * This pattern layout should be used in preference to * org.apache.log4j.PatternLayout except when compatibility * where PatternLayout has been extended either through subclassing * or alternative pattern parsers. * * *

A flexible layout configurable with pattern string. The goal of this class * is to {@link #format format} a {@link LoggingEvent} and return the results * in a {@link StringBuffer}. The format of the result depends on the * conversion pattern. *

* *

The conversion pattern is closely related to the conversion * pattern of the printf function in C. A conversion pattern is * composed of literal text and format control expressions called * conversion specifiers. * *

Note that you are free to insert any literal text within the * conversion pattern. *

Each conversion specifier starts with a percent sign (%) and is followed by optional format modifiers and a conversion character. The conversion character specifies the type of data, e.g. category, priority, date, thread name. The format modifiers control such things as field width, padding, left and right justification. The following is a simple example.

Let the conversion pattern be "%-5p [%t]: %m%n" and assume that the log4j environment was set to use a EnhancedPatternLayout. Then the statements

   Category root = Category.getRoot();
   root.debug("Message 1");
   root.warn("Message 2");
   
would yield the output
   DEBUG [main]: Message 1
   WARN  [main]: Message 2
   

Note that there is no explicit separator between text and conversion specifiers. The pattern parser knows when it has reached the end of a conversion specifier when it reads a conversion character. In the example above the conversion specifier %-5p means the priority of the logging event should be left justified to a width of five characters. The recognized conversion characters are

Conversion Character Effect
c Used to output the category of the logging event. The category conversion specifier can be optionally followed by NameAbbreviator pattern.

For example, for the category name "alpha.beta.gamma" the pattern %c{2} will output the last two elements ("beta.gamma"), %c{-2} will remove two elements leaving "gamma", %c{1.} will output "a.b.gamma".

C Used to output the fully qualified class name of the caller issuing the logging request. This conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets. Used to output the category of the logging event. The category conversion specifier can be optionally followed by NameAbbreviator pattern.

For example, for the category name "alpha.beta.gamma" the pattern %c{2} will output the last two elements ("beta.gamma"), %c{-2} will remove two elements leaving "gamma", %c{1.} will output "a.b.gamma".

WARNING Generating the caller class information is slow. Thus, its use should be avoided unless execution speed is not an issue.

d Used to output the date of the logging event. The date conversion specifier may be followed by a set of braces containing a date and time pattern strings {@link java.text.SimpleDateFormat}, ABSOLUTE, DATE or ISO8601 and a set of braces containing a time zone id per {@link java.util.TimeZone#getTimeZone(String)}. For example, %d{HH:mm:ss,SSS}, %d{dd MMM yyyy HH:mm:ss,SSS}, %d{DATE} or %d{HH:mm:ss}{GMT+0}. If no date format specifier is given then ISO8601 format is assumed.
F Used to output the file name where the logging request was issued.

WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue.

l Used to output location information of the caller which generated the logging event.

The location information depends on the JVM implementation but usually consists of the fully qualified name of the calling method followed by the callers source the file name and line number between parentheses.

The location information can be very useful. However, its generation is extremely slow and should be avoided unless execution speed is not an issue.

L Used to output the line number from where the logging request was issued.

WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue.

m Used to output the application supplied message associated with the logging event.
M Used to output the method name where the logging request was issued.

WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue.

n Outputs the platform dependent line separator character or characters.

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.

p Used to output the priority of the logging event.
r Used to output the number of milliseconds elapsed since the construction of the layout until the creation of the logging event.
t Used to output the name of the thread that generated the logging event.
x Used to output the NDC (nested diagnostic context) associated with the thread that generated the logging event.
X

Used to output the MDC (mapped diagnostic context) associated with the thread that generated the logging event. The X conversion character can be followed by the key for the map placed between braces, as in %X{clientNumber} where clientNumber is the key. The value in the MDC corresponding to the key will be output. If no additional sub-option is specified, then the entire contents of the MDC key value pair set is output using a format {{key1,val1},{key2,val2}}

See {@link MDC} class for more details.

properties

Used to output the Properties associated with the logging event. The properties conversion word can be followed by the key for the map placed between braces, as in %properties{application} where application is the key. The value in the Properties bundle corresponding to the key will be output. If no additional sub-option is specified, then the entire contents of the Properties key value pair set is output using a format {{key1,val1},{key2,val2}}

throwable

Used to output the Throwable trace that has been bound to the LoggingEvent, by default this will output the full trace as one would normally find by a call to Throwable.printStackTrace(). %throwable{short} or %throwable{1} will output the first line of stack trace. throwable{none} or throwable{0} will suppress the stack trace. %throwable{n} will output n lines of stack trace if a positive integer or omit the last -n lines if a negative integer. If no %throwable pattern is specified, the appender will take responsibility to output the stack trace as it sees fit.

% The sequence %% outputs a single percent sign.

By default the relevant information is output as is. However, with the aid of format modifiers it is possible to change the minimum field width, the maximum field width and justification.

The optional format modifier is placed between the percent sign and the conversion character.

The first optional format modifier is the left justification flag which is just the minus (-) character. Then comes the optional minimum field width modifier. This is a decimal constant that represents the minimum number of characters to output. If the data item requires fewer characters, it is padded on either the left or the right until the minimum width is reached. The default is to pad on the left (right justify) but you can specify right padding with the left justification flag. The padding character is space. If the data item is larger than the minimum field width, the field is expanded to accommodate the data. The value is never truncated.

This behavior can be changed using the maximum field width modifier which is designated by a period followed by a decimal constant. If the data item is longer than the maximum field, then the extra characters are removed from the beginning of the data item and not from the end. For example, it the maximum field width is eight and the data item is ten characters long, then the first two characters of the data item are dropped. This behavior deviates from the printf function in C where truncation is done from the end.

Below are various format modifier examples for the category conversion specifier.

Format modifier left justify minimum width maximum width comment
%20c false 20 none Left pad with spaces if the category name is less than 20 characters long.
%-20c true 20 none Right pad with spaces if the category name is less than 20 characters long.
%.30c NA none 30 Truncate from the beginning if the category name is longer than 30 characters.
%20.30c false 20 30 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.
%-20.30c true 20 30 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.

Below are some examples of conversion patterns.

%r [%t] %-5p %c %x - %m%n

This is essentially the TTCC layout.

%-6r [%15.15t] %-5p %30.30c %x - %m%n

Similar to the TTCC layout except that the relative time is right padded if less than 6 digits, thread name is right padded if less than 15 characters and truncated if longer and the category name is left padded if shorter than 30 characters and truncated if longer.

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 James P. Cakalic @author Ceki Gülcü @since 1.2.16 */ public class EnhancedPatternLayout extends Layout { /** Default pattern string for log output. Currently set to the string "%m%n" which just prints the application supplied message. */ public static final String DEFAULT_CONVERSION_PATTERN = "%m%n"; /** A conversion pattern equivalent to the TTCCCLayout. Current value is %r [%t] %p %c %x - %m%n. */ public static final String TTCC_CONVERSION_PATTERN = "%r [%t] %p %c %x - %m%n"; /** * Initial size of internal buffer, no longer used. * @deprecated since 1.3 */ protected final int BUF_SIZE = 256; /** * Maximum capacity of internal buffer, no longer used. * @deprecated since 1.3 */ protected final int MAX_CAPACITY = 1024; /** * Customized pattern conversion rules are stored under this key in the * {@link org.apache.log4j.spi.LoggerRepository LoggerRepository} object store. */ public static final String PATTERN_RULE_REGISTRY = "PATTERN_RULE_REGISTRY"; /** * Initial converter for pattern. */ private PatternConverter head; /** * Conversion pattern. */ private String conversionPattern; /** * True if any element in pattern formats information from exceptions. */ private boolean handlesExceptions; /** Constructs a EnhancedPatternLayout using the DEFAULT_LAYOUT_PATTERN. The default pattern just produces the application supplied message. */ public EnhancedPatternLayout() { this(DEFAULT_CONVERSION_PATTERN); } /** * Constructs a EnhancedPatternLayout using the supplied conversion pattern. * @param pattern conversion pattern. */ public EnhancedPatternLayout(final String pattern) { this.conversionPattern = pattern; head = createPatternParser( (pattern == null) ? DEFAULT_CONVERSION_PATTERN : pattern).parse(); if (head instanceof BridgePatternConverter) { handlesExceptions = !((BridgePatternConverter) head).ignoresThrowable(); } else { handlesExceptions = false; } } /** * Set the ConversionPattern option. This is the string which * controls formatting and consists of a mix of literal content and * conversion specifiers. * * @param conversionPattern conversion pattern. */ public void setConversionPattern(final String conversionPattern) { this.conversionPattern = OptionConverter.convertSpecialChars(conversionPattern); head = createPatternParser(this.conversionPattern).parse(); if (head instanceof BridgePatternConverter) { handlesExceptions = !((BridgePatternConverter) head).ignoresThrowable(); } else { handlesExceptions = false; } } /** * Returns the value of the ConversionPattern option. * @return conversion pattern. */ public String getConversionPattern() { return conversionPattern; } /** Returns PatternParser used to parse the conversion string. Subclasses may override this to return a subclass of PatternParser which recognize custom conversion characters. @since 0.9.0 */ protected org.apache.log4j.helpers.PatternParser createPatternParser(String pattern) { return new org.apache.log4j.pattern.BridgePatternParser(pattern); } /** Activates the conversion pattern. Do not forget to call this method after you change the parameters of the EnhancedPatternLayout instance. */ public void activateOptions() { // nothing to do. } /** * Formats a logging event to a writer. * @param event logging event to be formatted. */ public String format(final LoggingEvent event) { StringBuffer buf = new StringBuffer(); for(PatternConverter c = head; c != null; c = c.next) { c.format(buf, event); } return buf.toString(); } /** * Will return false if any of the conversion specifiers in the pattern * handles {@link Exception Exceptions}. * @return true if the pattern formats any information from exceptions. */ public boolean ignoresThrowable() { return !handlesExceptions; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/Category.java0000644000175000017500000007635511751454711024115 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Contibutors: Alex Blewitt // Markus Oestreicher // Frank Hoering // Nelson Minar // Jim Cakalic // Avy Sharell // Ciaran Treanor // Jeff Turner // Michael Horwitz // Calvin Chan // Aaron Greenhouse // Beat Meier // Colin Sampaleanu package org.apache.log4j; import org.apache.log4j.spi.AppenderAttachable; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.HierarchyEventListener; import org.apache.log4j.helpers.NullEnumeration; import org.apache.log4j.helpers.AppenderAttachableImpl; import java.util.Enumeration; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Vector; /** * This class has been deprecated and * replaced by the {@link Logger} subclass. It * will be kept around to preserve backward compatibility until mid * 2003. * *

Logger is a subclass of Category, i.e. it extends * Category. In other words, a logger is a category. Thus, * all operations that can be performed on a category can be * performed on a logger. Internally, whenever log4j is asked to * produce a Category object, it will instead produce a Logger * object. Log4j 1.2 will never produce Category objects but * only Logger instances. In order to preserve backward * compatibility, methods that previously accepted category objects * still continue to accept category objects. * *

For example, the following are all legal and will work as * expected. *

       // Deprecated form:
       Category cat = Category.getInstance("foo.bar")
   
       // Preferred form for retrieving loggers:
       Logger logger = Logger.getLogger("foo.bar")
   
*

The first form is deprecated and should be avoided. * *

There is absolutely no need for new client code to use or * refer to the Category class. Whenever possible, * please avoid referring to it or using it. * *

See the short manual for an * introduction on this class. *

* See the document entitled preparing * for log4j 1.3 for a more detailed discussion. * * @author Ceki Gülcü * @author Anders Kristensen */ public class Category implements AppenderAttachable { /** The hierarchy where categories are attached to by default. */ //static //public //final Hierarchy defaultHierarchy = new Hierarchy(new // RootCategory(Level.DEBUG)); /** The name of this category. */ protected String name; /** The assigned level of this category. The level variable need not be assigned a value in which case it is inherited form the hierarchy. */ volatile protected Level level; /** The parent of this category. All categories have at least one ancestor which is the root category. */ volatile protected Category parent; /** 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; AppenderAttachableImpl aai; /** Additivity is set to true by default, that is children inherit the appenders of their ancestors by default. If this variable is set to false then the appenders found in the ancestors of this category are not used. However, the children of this category will inherit its appenders, unless the children have their additivity flag set to false too. See the user manual for more details. */ protected boolean additive = true; /** This constructor created a new Category instance and sets its name.

It is intended to be used by sub-classes only. You should not create categories directly. @param name The name of the category. */ protected Category(String name) { this.name = name; } /** Add newAppender to the list of appenders of this Category instance.

If newAppender is already in the list of appenders, then it won't be added again. */ synchronized public void addAppender(Appender newAppender) { if(aai == null) { aai = new AppenderAttachableImpl(); } aai.addAppender(newAppender); repository.fireAddAppenderEvent(this, newAppender); } /** If assertion parameter is false, then logs msg as an {@link #error(Object) error} statement.

The assert method has been renamed to assertLog because assert is a language reserved word in JDK 1.4. @param assertion @param msg The message to print if assertion is false. @since 1.2 */ public void assertLog(boolean assertion, String msg) { if(!assertion) this.error(msg); } /** Call the appenders in the hierrachy starting at this. If no appenders could be found, emit a warning.

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 event the event to log. */ public void callAppenders(LoggingEvent event) { int writes = 0; for(Category c = this; c != null; c=c.parent) { // Protected against simultaneous call to addAppender, removeAppender,... synchronized(c) { if(c.aai != null) { writes += c.aai.appendLoopOnAppenders(event); } if(!c.additive) { break; } } } if(writes == 0) { repository.emitNoAppenderWarning(this); } } /** Close all attached appenders implementing the AppenderAttachable interface. @since 1.0 */ synchronized void closeNestedAppenders() { Enumeration enumeration = this.getAllAppenders(); if(enumeration != null) { while(enumeration.hasMoreElements()) { Appender a = (Appender) enumeration.nextElement(); if(a instanceof AppenderAttachable) { a.close(); } } } } /** Log a message object with the {@link Level#DEBUG DEBUG} level.

This method first checks if this category is DEBUG enabled by comparing the level of this category with the {@link Level#DEBUG DEBUG} level. If this category is DEBUG enabled, then it converts the message object (passed as parameter) to a string by invoking the appropriate {@link org.apache.log4j.or.ObjectRenderer}. It then proceeds to call all the registered appenders in this category and also higher in the hierarchy depending on the value of the additivity flag.

WARNING 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 #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(Level.DEBUG.isGreaterOrEqual(this.getEffectiveLevel())) { forcedLog(FQCN, Level.DEBUG, message, null); } } /** Log a message object with the DEBUG level including the stack trace of the {@link Throwable} t passed as parameter.

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. */ public void debug(Object message, Throwable t) { if(repository.isDisabled(Level.DEBUG_INT)) return; if(Level.DEBUG.isGreaterOrEqual(this.getEffectiveLevel())) forcedLog(FQCN, Level.DEBUG, message, t); } /** Log a message object with the {@link Level#ERROR ERROR} Level.

This method first checks if this category is ERROR enabled by comparing the level of this category with {@link Level#ERROR ERROR} Level. If this category is ERROR enabled, then it converts the message object passed as parameter to a string by invoking the appropriate {@link org.apache.log4j.or.ObjectRenderer}. It proceeds to call all the registered appenders in this category and also higher in the hierarchy depending on the value of the additivity flag.

WARNING 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 #error(Object, Throwable)} form instead. @param message the message object to log */ public void error(Object message) { if(repository.isDisabled(Level.ERROR_INT)) return; if(Level.ERROR.isGreaterOrEqual(this.getEffectiveLevel())) forcedLog(FQCN, Level.ERROR, message, null); } /** Log a message object with the ERROR level including the stack trace of the {@link Throwable} t passed as parameter.

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. */ 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); } /** If the named category exists (in the default hierarchy) then it returns a reference to the category, otherwise it returns null. @deprecated Please use {@link LogManager#exists} instead. @since 0.8.5 */ public static Logger exists(String name) { return LogManager.exists(name); } /** Log a message object with the {@link Level#FATAL FATAL} Level.

This method first checks if this category is FATAL enabled by comparing the level of this category with {@link Level#FATAL FATAL} Level. If the category is FATAL enabled, then it converts the message object passed as parameter to a string by invoking the appropriate {@link org.apache.log4j.or.ObjectRenderer}. It proceeds to call all the registered appenders in this category and also higher in the hierarchy depending on the value of the additivity flag.

WARNING 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. @param message the message object to log */ public void fatal(Object message) { 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 FATAL level including the stack trace of the {@link Throwable} t passed as parameter.

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; if(Level.FATAL.isGreaterOrEqual(this.getEffectiveLevel())) forcedLog(FQCN, Level.FATAL, message, t); } /** This method creates a new logging event and logs the event without further checks. */ protected void forcedLog(String fqcn, Priority level, Object message, Throwable t) { callAppenders(new LoggingEvent(fqcn, this, level, message, t)); } /** Get the additivity flag for this Category instance. */ public boolean getAdditivity() { return additive; } /** 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 return aai.getAllAppenders(); } /** Look for the appender named as name.

Return the appender with that name if in the list. Return null otherwise. */ synchronized public Appender getAppender(String name) { if(aai == null || name == null) return null; 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.

The Category class is designed so that this method executes as quickly as possible. */ public Level getEffectiveLevel() { for(Category c = this; c != null; c=c.parent) { if(c.level != null) return c.level; } return null; // If reached will cause an NullPointerException. } /** * * @deprecated Please use the the {@link #getEffectiveLevel} method * instead. * */ public Priority getChainedPriority() { for(Category c = this; c != null; c=c.parent) { if(c.level != null) return c.level; } return null; // If reached will cause an NullPointerException. } /** Returns all the currently defined categories in the default hierarchy as an {@link java.util.Enumeration Enumeration}.

The root category is not included in the returned {@link Enumeration}. @deprecated Please use {@link LogManager#getCurrentLoggers()} instead. */ public static Enumeration getCurrentCategories() { return LogManager.getCurrentLoggers(); } /** Return the default Hierarchy instance. @deprecated Please use {@link LogManager#getLoggerRepository()} instead. @since 1.0 */ public static LoggerRepository getDefaultHierarchy() { return LogManager.getLoggerRepository(); } /** Return the the {@link Hierarchy} where this Category instance is attached. @deprecated Please use {@link #getLoggerRepository} instead. @since 1.1 */ public LoggerRepository getHierarchy() { return repository; } /** Return the the {@link LoggerRepository} where this Category is attached. @since 1.2 */ public LoggerRepository getLoggerRepository() { return repository; } /** * @deprecated Make sure to use {@link Logger#getLogger(String)} instead. */ public static Category getInstance(String name) { return LogManager.getLogger(name); } /** * @deprecated Please make sure to use {@link Logger#getLogger(Class)} instead. */ public static Category getInstance(Class clazz) { return LogManager.getLogger(clazz); } /** Return the category name. */ public final String getName() { return name; } /** Returns the parent of this category. Note that the parent of a given category may change during the lifetime of the category.

The root category will return null. @since 1.2 */ final public Category getParent() { return this.parent; } /** Returns the assigned {@link Level}, if any, for this Category. @return Level - the assigned Level, can be null. */ final public Level getLevel() { return this.level; } /** @deprecated Please use {@link #getLevel} instead. */ final public Level getPriority() { return this.level; } /** * @deprecated Please use {@link Logger#getRootLogger()} instead. */ final public static Category getRoot() { return LogManager.getRootLogger(); } /** Return the inherited {@link ResourceBundle} for this category.

This method walks the hierarchy to find the appropriate resource bundle. It will return the resource bundle attached to the closest ancestor of this category, much like the way priorities are searched. In case there is no bundle in the hierarchy then null is returned. @since 0.9.0 */ public ResourceBundle getResourceBundle() { for(Category c = this; c != null; c=c.parent) { if(c.resourceBundle != null) return c.resourceBundle; } // It might be the case that there is no resource bundle return null; } /** Returns the string resource coresponding to key in this category's inherited resource bundle. See also {@link #getResourceBundle}.

If the resource cannot be found, then an {@link #error error} message will be logged complaining about the missing resource. */ protected String getResourceBundleString(String key) { ResourceBundle rb = getResourceBundle(); // This is one of the rare cases where we can use logging in order // to report errors from within log4j. if(rb == null) { //if(!hierarchy.emittedNoResourceBundleWarning) { //error("No resource bundle has been set for category "+name); //hierarchy.emittedNoResourceBundleWarning = true; //} return null; } else { try { return rb.getString(key); } catch(MissingResourceException mre) { error("No resource is associated with key \""+key+"\"."); return null; } } } /** Log a message object with the {@link Level#INFO INFO} Level.

This method first checks if this category is INFO enabled by comparing the level of this category with {@link Level#INFO INFO} Level. If the category is INFO enabled, then it converts the message object passed as parameter to a string by invoking the appropriate {@link org.apache.log4j.or.ObjectRenderer}. It proceeds to call all the registered appenders in this category and also higher in the hierarchy depending on the value of the additivity flag.

WARNING 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. @param message the message object to log */ public void info(Object message) { 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 INFO level including the stack trace of the {@link Throwable} t passed as parameter.

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; if(Level.INFO.isGreaterOrEqual(this.getEffectiveLevel())) forcedLog(FQCN, Level.INFO, message, t); } /** Is the appender passed as parameter attached to this category? */ public boolean isAttached(Appender appender) { if(appender == null || aai == null) return false; else { return aai.isAttached(appender); } } /** * Check whether this category is enabled for the DEBUG * Level. * *

This function is intended to lessen the computational cost of * disabled log debug statements. * *

For some cat Category object, when you write, *

    *      cat.debug("This is entry number: " + i );
    *  
* *

You incur the cost constructing the message, concatenatiion in * this case, regardless of whether the message is logged or not. * *

If you are worried about speed, then you should write *

    * 	 if(cat.isDebugEnabled()) {
    * 	   cat.debug("This is entry number: " + i );
    * 	 }
    *  
* *

This way you will not incur the cost of parameter * construction if debugging is disabled for cat. On * the other hand, if the cat is debug enabled, you * will incur the cost of evaluating whether the category is debug * enabled twice. Once in isDebugEnabled and once in * the debug. This is an insignificant overhead * since evaluating a category takes about 1%% of the time it * takes to actually log. * * @return boolean - true if this category is debug * enabled, false otherwise. * */ public boolean isDebugEnabled() { if(repository.isDisabled( Level.DEBUG_INT)) 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 level. */ public boolean isEnabledFor(Priority level) { if(repository.isDisabled(level.level)) return false; return level.isGreaterOrEqual(this.getEffectiveLevel()); } /** Check whether this category is enabled for the info Level. See also {@link #isDebugEnabled}. @return boolean - true if this category is enabled for level info, false otherwise. */ public boolean isInfoEnabled() { if(repository.isDisabled(Level.INFO_INT)) return false; return Level.INFO.isGreaterOrEqual(this.getEffectiveLevel()); } /** Log a localized message. The user supplied parameter key is replaced by its localized version from the resource bundle. @see #setResourceBundle @since 0.8.4 */ public void l7dlog(Priority priority, String key, Throwable t) { if(repository.isDisabled(priority.level)) { return; } if(priority.isGreaterOrEqual(this.getEffectiveLevel())) { String msg = getResourceBundleString(key); // if message corresponding to 'key' could not be found in the // resource bundle, then default to 'key'. if(msg == null) { msg = key; } forcedLog(FQCN, priority, msg, t); } } /** Log a localized and parameterized message. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using {@link java.text.MessageFormat#format(String,Object[])} method with the user supplied object array params. @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) msg = key; else msg = java.text.MessageFormat.format(pattern, params); forcedLog(FQCN, priority, msg, t); } } /** This generic form is intended to be used by wrappers. */ public void log(Priority priority, Object message, Throwable t) { if(repository.isDisabled(priority.level)) { return; } if(priority.isGreaterOrEqual(this.getEffectiveLevel())) forcedLog(FQCN, priority, message, t); } /** This generic form is intended to be used by wrappers. */ public void log(Priority priority, Object message) { if(repository.isDisabled(priority.level)) { return; } if(priority.isGreaterOrEqual(this.getEffectiveLevel())) forcedLog(FQCN, priority, message, null); } /** This is the most generic printing method. It is intended to be invoked by wrapper 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. @param t The throwable of the logging request, may be null. */ public void log(String callerFQCN, Priority level, Object message, Throwable t) { if(repository.isDisabled(level.level)) { return; } if(level.isGreaterOrEqual(this.getEffectiveLevel())) { forcedLog(callerFQCN, level, message, t); } } /** * LoggerRepository forgot the fireRemoveAppenderEvent method, * if using the stock Hierarchy implementation, then call its fireRemove. * Custom repositories can implement HierarchyEventListener if they * want remove notifications. * @param appender appender, may be null. */ private void fireRemoveAppenderEvent(final Appender appender) { if (appender != null) { if (repository instanceof Hierarchy) { ((Hierarchy) repository).fireRemoveAppenderEvent(this, appender); } else if (repository instanceof HierarchyEventListener) { ((HierarchyEventListener) repository).removeAppenderEvent(this, appender); } } } /** Remove all previously added appenders from this Category instance.

This is useful when re-reading configuration information. */ synchronized public void removeAllAppenders() { if(aai != null) { Vector appenders = new Vector(); for (Enumeration iter = aai.getAllAppenders(); iter != null && iter.hasMoreElements();) { appenders.add(iter.nextElement()); } aai.removeAllAppenders(); for(Enumeration iter = appenders.elements(); iter.hasMoreElements();) { fireRemoveAppenderEvent((Appender) iter.nextElement()); } aai = null; } } /** Remove the appender passed as parameter form the list of appenders. @since 0.8.2 */ synchronized public void removeAppender(Appender appender) { if(appender == null || aai == null) return; boolean wasAttached = aai.isAttached(appender); aai.removeAppender(appender); if (wasAttached) { fireRemoveAppenderEvent(appender); } } /** Remove the appender with the name passed as parameter form the list of appenders. @since 0.8.2 */ synchronized public void removeAppender(String name) { if(name == null || aai == null) return; Appender appender = aai.getAppender(name); aai.removeAppender(name); if (appender != null) { fireRemoveAppenderEvent(appender); } } /** Set the additivity flag for this Category instance. @since 0.8.1 */ public void setAdditivity(boolean additive) { this.additive = additive; } /** Only the Hiearchy class can set the hiearchy of a category. Default package access is MANDATORY here. */ final void setHierarchy(LoggerRepository repository) { this.repository = repository; } /** Set the level of this Category. If you are passing any of Level.DEBUG, Level.INFO, Level.WARN, Level.ERROR, Level.FATAL as a parameter, you need to case them as Level.

As in

    logger.setLevel((Level) Level.DEBUG); 

Null values are admitted. */ public void setLevel(Level level) { this.level = level; } /** Set the level of this Category.

Null values are admitted. @deprecated Please use {@link #setLevel} instead. */ public void setPriority(Priority priority) { this.level = (Level) priority; } /** Set the resource bundle to be used with localized logging methods {@link #l7dlog(Priority,String,Throwable)} and {@link #l7dlog(Priority,String,Object[],Throwable)}. @since 0.8.4 */ public void setResourceBundle(ResourceBundle bundle) { resourceBundle = bundle; } /** Calling this method will safely close and remove all appenders in all the categories including root contained in the default hierachy.

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 lost.

The shutdown 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. @deprecated Please use {@link LogManager#shutdown()} instead. @since 1.0 */ public static void shutdown() { LogManager.shutdown(); } /** Log a message object with the {@link Level#WARN WARN} Level.

This method first checks if this category is WARN enabled by comparing the level of this category with {@link Level#WARN WARN} Level. If the category is WARN enabled, then it converts the message object passed as parameter to a string by invoking the appropriate {@link org.apache.log4j.or.ObjectRenderer}. It proceeds to call all the registered appenders in this category and also higher in the hieararchy depending on the value of the additivity flag.

WARNING 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 #warn(Object, Throwable)} form instead.

@param message the message object to log. */ public void warn(Object message) { if(repository.isDisabled( Level.WARN_INT)) return; if(Level.WARN.isGreaterOrEqual(this.getEffectiveLevel())) forcedLog(FQCN, Level.WARN, message, null); } /** Log a message with the WARN level including the stack trace of the {@link Throwable} t passed as parameter.

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(Level.WARN.isGreaterOrEqual(this.getEffectiveLevel())) forcedLog(FQCN, Level.WARN, message, t); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/Dispatcher.java0000644000175000017500000000703111751454711024407 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.helpers.AppenderAttachableImpl; import org.apache.log4j.spi.LoggingEvent; /** * Obsolete AsyncAppender dispatcher provided for compatibility only. * * @deprecated Since 1.3. */ class Dispatcher extends Thread { /** * @deprecated */ private org.apache.log4j.helpers.BoundedFIFO bf; private AppenderAttachableImpl aai; private boolean interrupted = false; AsyncAppender container; /** * * @param bf * @param container * @deprecated */ Dispatcher(org.apache.log4j.helpers.BoundedFIFO bf, AsyncAppender container) { this.bf = bf; this.container = container; this.aai = container.aai; // It is the user's responsibility to close appenders before // exiting. this.setDaemon(true); // set the dispatcher priority to lowest possible value this.setPriority(Thread.MIN_PRIORITY); this.setName("Dispatcher-" + getName()); // set the dispatcher priority to MIN_PRIORITY plus or minus 2 // depending on the direction of MIN to MAX_PRIORITY. //+ (Thread.MAX_PRIORITY > Thread.MIN_PRIORITY ? 1 : -1)*2); } void close() { synchronized (bf) { 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) { bf.notify(); } } } /** * The dispatching strategy is to wait until there are events in the 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. * *

* Other approaches might yield better results. *

*/ public void run() { //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) { //cat.info("Exiting."); break; } try { //LogLog.debug("Waiting for new event to dispatch."); bf.wait(); } catch (InterruptedException e) { break; } } event = bf.get(); if (bf.wasFull()) { //LogLog.debug("Notifying AsyncAppender about freed space."); bf.notify(); } } // synchronized synchronized (container.aai) { if ((aai != null) && (event != null)) { aai.appendLoopOnAppenders(event); } } } // while // close and remove all appenders aai.removeAllAppenders(); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/HTMLLayout.java0000644000175000017500000002116711751454711024271 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.helpers.Transform; /** * This layout outputs events in a HTML table. * * Appenders using this layout should have their encoding * set to UTF-8 or UTF-16, otherwise events containing * non ASCII characters could result in corrupted * log files. * * @author Ceki Gülcü */ public class HTMLLayout extends Layout { protected final int BUF_SIZE = 256; protected final int MAX_CAPACITY = 1024; static String TRACE_PREFIX = "
    "; // output buffer appended to when format() is invoked private StringBuffer sbuf = new StringBuffer(BUF_SIZE); /** A string constant used in naming the option for setting the the location information flag. Current value of this string constant is LocationInfo.

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 near term. */ public static final String LOCATION_INFO_OPTION = "LocationInfo"; /** A string constant used in naming the option for setting the the HTML document title. Current value of this string constant is Title. */ public static final String TITLE_OPTION = "Title"; // Print no location info by default boolean locationInfo = false; String title = "Log4J Log Messages"; /** The LocationInfo option takes a boolean value. By 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.

If you are embedding this layout within an {@link org.apache.log4j.net.SMTPAppender} then make sure to set the LocationInfo option of that appender as well. */ public void setLocationInfo(boolean flag) { locationInfo = flag; } /** Returns the current value of the LocationInfo option. */ public boolean getLocationInfo() { return locationInfo; } /** The Title option takes a String value. This option sets the document title of the generated HTML document.

Defaults to 'Log4J Log Messages'. */ public void setTitle(String title) { this.title = title; } /** Returns the current value of the Title option. */ public String getTitle() { return title; } /** Returns the content type output by this layout, i.e "text/html". */ public String getContentType() { return "text/html"; } /** No options to activate. */ public void activateOptions() { } public String format(LoggingEvent event) { if(sbuf.capacity() > MAX_CAPACITY) { sbuf = new StringBuffer(BUF_SIZE); } else { sbuf.setLength(0); } sbuf.append(Layout.LINE_SEP + "" + Layout.LINE_SEP); sbuf.append(""); sbuf.append(event.timeStamp - LoggingEvent.getStartTime()); sbuf.append("" + Layout.LINE_SEP); String escapedThread = Transform.escapeTags(event.getThreadName()); sbuf.append(""); sbuf.append(escapedThread); sbuf.append("" + Layout.LINE_SEP); sbuf.append(""); if (event.getLevel().equals(Level.DEBUG)) { sbuf.append(""); sbuf.append(Transform.escapeTags(String.valueOf(event.getLevel()))); sbuf.append(""); } else if(event.getLevel().isGreaterOrEqual(Level.WARN)) { sbuf.append(""); sbuf.append(Transform.escapeTags(String.valueOf(event.getLevel()))); sbuf.append(""); } else { sbuf.append(Transform.escapeTags(String.valueOf(event.getLevel()))); } sbuf.append("" + Layout.LINE_SEP); String escapedLogger = Transform.escapeTags(event.getLoggerName()); sbuf.append(""); sbuf.append(escapedLogger); sbuf.append("" + Layout.LINE_SEP); if(locationInfo) { LocationInfo locInfo = event.getLocationInformation(); sbuf.append(""); sbuf.append(Transform.escapeTags(locInfo.getFileName())); sbuf.append(':'); sbuf.append(locInfo.getLineNumber()); sbuf.append("" + Layout.LINE_SEP); } sbuf.append(""); sbuf.append(Transform.escapeTags(event.getRenderedMessage())); sbuf.append("" + Layout.LINE_SEP); sbuf.append("" + Layout.LINE_SEP); if (event.getNDC() != null) { sbuf.append(""); sbuf.append("NDC: " + Transform.escapeTags(event.getNDC())); sbuf.append("" + Layout.LINE_SEP); } String[] s = event.getThrowableStrRep(); if(s != null) { sbuf.append(""); appendThrowableAsHTML(s, sbuf); sbuf.append("" + Layout.LINE_SEP); } return sbuf.toString(); } void appendThrowableAsHTML(String[] s, StringBuffer sbuf) { if(s != null) { int len = s.length; if(len == 0) return; sbuf.append(Transform.escapeTags(s[0])); sbuf.append(Layout.LINE_SEP); for(int i = 1; i < len; i++) { sbuf.append(TRACE_PREFIX); sbuf.append(Transform.escapeTags(s[i])); sbuf.append(Layout.LINE_SEP); } } } /** Returns appropriate HTML headers. */ public String getHeader() { StringBuffer sbuf = new StringBuffer(); sbuf.append("" + Layout.LINE_SEP); sbuf.append("" + Layout.LINE_SEP); sbuf.append("" + Layout.LINE_SEP); sbuf.append("" + title + "" + Layout.LINE_SEP); sbuf.append("" + Layout.LINE_SEP); sbuf.append("" + Layout.LINE_SEP); sbuf.append("" + Layout.LINE_SEP); sbuf.append("


" + Layout.LINE_SEP); sbuf.append("Log session start time " + new java.util.Date() + "
" + Layout.LINE_SEP); sbuf.append("
" + Layout.LINE_SEP); sbuf.append("" + Layout.LINE_SEP); sbuf.append("" + Layout.LINE_SEP); sbuf.append("" + Layout.LINE_SEP); sbuf.append("" + Layout.LINE_SEP); sbuf.append("" + Layout.LINE_SEP); sbuf.append("" + Layout.LINE_SEP); if(locationInfo) { sbuf.append("" + Layout.LINE_SEP); } sbuf.append("" + Layout.LINE_SEP); sbuf.append("" + Layout.LINE_SEP); return sbuf.toString(); } /** Returns the appropriate HTML footers. */ public String getFooter() { StringBuffer sbuf = new StringBuffer(); sbuf.append("
TimeThreadLevelCategoryFile:LineMessage
" + Layout.LINE_SEP); sbuf.append("
" + Layout.LINE_SEP); sbuf.append(""); return sbuf.toString(); } /** The HTML layout handles the throwable contained in logging events. Hence, this method return false. */ public boolean ignoresThrowable() { return false; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/Priority.java0000644000175000017500000001144411751454711024145 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Contributors: Kitching Simon package org.apache.log4j; /** Refrain from using this class directly, use the {@link Level} class instead. @author Ceki Gülcü */ public class Priority { transient int level; transient String levelStr; transient int syslogEquivalent; public final static int OFF_INT = Integer.MAX_VALUE; public final static int FATAL_INT = 50000; public final static int ERROR_INT = 40000; public final static int WARN_INT = 30000; public final static int INFO_INT = 20000; public final static int DEBUG_INT = 10000; //public final static int FINE_INT = DEBUG_INT; public final static int ALL_INT = Integer.MIN_VALUE; /** * @deprecated Use {@link Level#FATAL} instead. */ final static public Priority FATAL = new Level(FATAL_INT, "FATAL", 0); /** * @deprecated Use {@link Level#ERROR} instead. */ final static public Priority ERROR = new Level(ERROR_INT, "ERROR", 3); /** * @deprecated Use {@link Level#WARN} instead. */ final static public Priority WARN = new Level(WARN_INT, "WARN", 4); /** * @deprecated Use {@link Level#INFO} instead. */ final static public Priority INFO = new Level(INFO_INT, "INFO", 6); /** * @deprecated Use {@link Level#DEBUG} instead. */ final static public Priority DEBUG = new Level(DEBUG_INT, "DEBUG", 7); /** * Default constructor for deserialization. */ protected Priority() { level = DEBUG_INT; levelStr = "DEBUG"; syslogEquivalent = 7; } /** Instantiate a level object. */ protected Priority(int level, String levelStr, int syslogEquivalent) { this.level = level; this.levelStr = levelStr; this.syslogEquivalent = syslogEquivalent; } /** Two priorities are equal if their level fields are equal. @since 1.2 */ public boolean equals(Object o) { if(o instanceof Priority) { Priority r = (Priority) o; return (this.level == r.level); } else { return false; } } /** Return the syslog equivalent of this priority as an integer. */ public final int getSyslogEquivalent() { return syslogEquivalent; } /** Returns true if this level has a higher or equal level than the level passed as argument, false otherwise.

You should think twice before overriding the default implementation of isGreaterOrEqual method. */ public boolean isGreaterOrEqual(Priority r) { return level >= r.level; } /** Return all possible priorities as an array of Level objects in descending order. @deprecated This method will be removed with no replacement. */ public static Priority[] getAllPossiblePriorities() { return new Priority[] {Priority.FATAL, Priority.ERROR, Level.WARN, Priority.INFO, Priority.DEBUG}; } /** Returns the string representation of this priority. */ final public String toString() { return levelStr; } /** Returns the integer representation of this level. */ public final int toInt() { return level; } /** * @deprecated Please use the {@link Level#toLevel(String)} method instead. */ public static Priority toPriority(String sArg) { return Level.toLevel(sArg); } /** * @deprecated Please use the {@link Level#toLevel(int)} method instead. */ public static Priority toPriority(int val) { return toPriority(val, Priority.DEBUG); } /** * @deprecated Please use the {@link Level#toLevel(int, Level)} method instead. */ public static Priority toPriority(int val, Priority defaultPriority) { return Level.toLevel(val, (Level) defaultPriority); } /** * @deprecated Please use the {@link Level#toLevel(String, Level)} method instead. */ public static Priority toPriority(String sArg, Priority defaultPriority) { return Level.toLevel(sArg, (Level) defaultPriority); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/DefaultThrowableRenderer.java0000644000175000017500000000504111751454711027243 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.spi.ThrowableRenderer; import java.io.StringWriter; import java.io.PrintWriter; import java.io.LineNumberReader; import java.io.StringReader; import java.io.IOException; import java.io.InterruptedIOException; import java.util.ArrayList; /** * Default implementation of ThrowableRenderer using * Throwable.printStackTrace. * * @since 1.2.16 */ public final class DefaultThrowableRenderer implements ThrowableRenderer { /** * Construct new instance. */ public DefaultThrowableRenderer() { } /** * {@inheritDoc} */ public String[] doRender(final Throwable throwable) { return render(throwable); } /** * Render throwable using Throwable.printStackTrace. * @param throwable throwable, may not be null. * @return string representation. */ public static String[] render(final Throwable throwable) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); try { throwable.printStackTrace(pw); } catch(RuntimeException ex) { } pw.flush(); LineNumberReader reader = new LineNumberReader( new StringReader(sw.toString())); ArrayList lines = new ArrayList(); try { String line = reader.readLine(); while(line != null) { lines.add(line); line = reader.readLine(); } } catch(IOException ex) { if (ex instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } lines.add(ex.toString()); } String[] tempRep = new String[lines.size()]; lines.toArray(tempRep); return tempRep; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/BasicConfigurator.java0000644000175000017500000000443411751454711025731 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Contibutors: "Luke Blanshard" // "Mark DONSZELMANN" // "Muly Oved" package org.apache.log4j; /** Use this class to quickly configure the package.

For file based configuration see {@link PropertyConfigurator}. For XML based configuration see {@link org.apache.log4j.xml.DOMConfigurator DOMConfigurator}. @since 0.8.1 @author Ceki Gülcü */ public class BasicConfigurator { protected BasicConfigurator() { } /** Add a {@link ConsoleAppender} that uses {@link PatternLayout} using the {@link PatternLayout#TTCC_CONVERSION_PATTERN} and prints to System.out to the root category. */ static public void configure() { Logger root = Logger.getRootLogger(); root.addAppender(new ConsoleAppender( new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN))); } /** Add appender to the root category. @param appender The appender to add to the root category. */ static public void configure(Appender appender) { Logger root = Logger.getRootLogger(); root.addAppender(appender); } /** Reset the default hierarchy to its defaut. It is equivalent to calling Category.getDefaultHierarchy().resetConfiguration(). See {@link Hierarchy#resetConfiguration()} for more details. */ public static void resetConfiguration() { LogManager.resetConfiguration(); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/0000755000175000017500000000000012126647422022250 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/RootCategory.java0000644000175000017500000000355211751454706025545 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.helpers.LogLog; // Contibutors: Mathias Bogaert /** * @deprecated Replaced by {@link RootLogger}. */ final public class RootCategory extends Logger { /** The root category names itself as "root". However, the root category cannot be retrieved by name. */ public RootCategory(Level level) { super("root"); setLevel(level); } /** Return the assigned level value without walking the category hierarchy. */ final public Level getChainedLevel() { return level; } /** Setting a null value to the level of the root category may have catastrophic results. We prevent this here. @since 0.8.3 */ final public void setLevel(Level level) { if(level == null) { LogLog.error("You have tried to set a null level to root.", new Throwable()); } else { this.level = level; } } final public void setPriority(Level level) { setLevel(level); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/package.html0000644000175000017500000000161211751454706024535 0ustar tonytony Contains part of the System Programming Interface (SPI) needed to extend log4j. apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/ThrowableInformation.java0000644000175000017500000000567111751454706027265 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; import org.apache.log4j.Category; import org.apache.log4j.DefaultThrowableRenderer; /** * ThrowableInformation is log4j's internal representation of * throwables. It essentially consists of a string array, called * 'rep', where the first element, that is rep[0], represents the * string representation of the throwable (i.e. the value you get * when you do throwable.toString()) and subsequent elements * correspond the stack trace with the top most entry of the stack * corresponding to the second entry of the 'rep' array that is * rep[1]. * * @author Ceki Gülcü * * */ public class ThrowableInformation implements java.io.Serializable { static final long serialVersionUID = -4748765566864322735L; private transient Throwable throwable; private transient Category category; private String[] rep; public ThrowableInformation(Throwable throwable) { this.throwable = throwable; } /** * Create a new instance. * @param throwable throwable, may not be null. * @param category category used to obtain ThrowableRenderer, may be null. * @since 1.2.16 */ public ThrowableInformation(Throwable throwable, Category category) { this.throwable = throwable; this.category = category; } /** * Create new instance. * @since 1.2.15 * @param r String representation of throwable. */ public ThrowableInformation(final String[] r) { if (r != null) { rep = (String[]) r.clone(); } } public Throwable getThrowable() { return throwable; } public synchronized String[] getThrowableStrRep() { if(rep == null) { ThrowableRenderer renderer = null; if (category != null) { LoggerRepository repo = category.getLoggerRepository(); if (repo instanceof ThrowableRendererSupport) { renderer = ((ThrowableRendererSupport) repo).getThrowableRenderer(); } } if (renderer == null) { rep = DefaultThrowableRenderer.render(throwable); } else { rep = renderer.doRender(throwable); } } return (String[]) rep.clone(); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/ThrowableRendererSupport.java0000644000175000017500000000241611751454706030135 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; /** * Implemented by logger repositories that support configurable * rendering of Throwables. * * @since 1.2.16 */ public interface ThrowableRendererSupport { /** * Get throwable renderer. * @return throwable renderer, may be null. */ ThrowableRenderer getThrowableRenderer(); /** * Set throwable renderer. * @param renderer renderer, may be null. */ void setThrowableRenderer(ThrowableRenderer renderer); } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/LoggerRepository.java0000644000175000017500000000600611751454706026440 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; import java.util.Enumeration; import org.apache.log4j.Appender; import org.apache.log4j.Category; import org.apache.log4j.Level; import org.apache.log4j.Logger; /** A LoggerRepository is used to create and retrieve Loggers. The relation between loggers in a repository depends on the repository but typically loggers are arranged in a named hierarchy.

In addition to the creational methods, a LoggerRepository can be queried for existing loggers, can act as a point of registry for events related to loggers. @author Ceki Gülcü @since 1.2 */ public interface LoggerRepository { /** Add a {@link HierarchyEventListener} event to the repository. */ public void addHierarchyEventListener(HierarchyEventListener listener); /** Returns whether this repository is disabled for a given level. The answer depends on the repository threshold and the level parameter. See also {@link #setThreshold} method. */ boolean isDisabled(int level); /** Set the repository-wide threshold. All logging requests below the threshold are immediately dropped. By default, the threshold is set to Level.ALL which has the lowest possible rank. */ public void setThreshold(Level level); /** Another form of {@link #setThreshold(Level)} accepting a string parameter instead of a Level. */ public void setThreshold(String val); public void emitNoAppenderWarning(Category cat); /** Get the repository-wide threshold. See {@link #setThreshold(Level)} for an explanation. */ public Level getThreshold(); public Logger getLogger(String name); public Logger getLogger(String name, LoggerFactory factory); public Logger getRootLogger(); public abstract Logger exists(String name); public abstract void shutdown(); public Enumeration getCurrentLoggers(); /** Deprecated. Please use {@link #getCurrentLoggers} instead. */ public Enumeration getCurrentCategories(); public abstract void fireAddAppenderEvent(Category logger, Appender appender); public abstract void resetConfiguration(); } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/LoggingEvent.java0000644000175000017500000004662411751454706025523 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; import java.io.InterruptedIOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import java.util.Set; import org.apache.log4j.Category; import org.apache.log4j.Level; import org.apache.log4j.MDC; import org.apache.log4j.NDC; import org.apache.log4j.Priority; import org.apache.log4j.helpers.Loader; import org.apache.log4j.helpers.LogLog; // Contributors: Nelson Minar // Wolf Siberski // Anders Kristensen /** The internal representation of logging events. When an affirmative decision is made to log then a LoggingEvent instance is created. This instance is passed around to the different log4j components.

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 { private static long startTime = System.currentTimeMillis(); /** Fully qualified name of the calling category class. */ transient public final String fqnOfCategoryClass; /** * The category of the logging event. This field is not serialized * for performance reasons. * *

It is set by the LoggingEvent constructor or set by a remote * entity after deserialization. * * @deprecated This field will be marked as private or be completely * removed in future releases. Please do not use it. * */ transient private Category logger; /** *

The category (logger) name. * * @deprecated This field will be marked as private in future * releases. Please do not access it directly. Use the {@link * #getLoggerName} method instead. * */ final public 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. * *

This field should not be accessed directly. You shoud use the * {@link #getLevel} method instead. * * @deprecated This field will be marked as private in future * releases. Please do not access it directly. Use the {@link * #getLevel} method instead. * */ transient public Priority level; /** The nested diagnostic context (NDC) of logging event. */ private String ndc; /** The mapped diagnostic context (MDC) of logging event. */ private Hashtable mdcCopy; /** Have we tried to do an NDC lookup? If we did, there is no need * to do it again. Note that its value is always false when * serialized. Thus, a receiving SocketNode will never use it's own * (incorrect) NDC. See also writeObject method. */ private boolean ndcLookupRequired = true; /** Have we tried to do an MDC lookup? If we did, there is no need * to do it again. Note that its value is always false when * serialized. See also the getMDC and getMDCCopy methods. */ private boolean mdcCopyLookupRequired = true; /** The application supplied message of logging event. */ transient private Object message; /** The application supplied message rendered through the log4j objet rendering mechanism.*/ private String renderedMessage; /** The name of thread in which this logging event was generated. */ private String threadName; /** This variable contains information about this event's throwable */ private ThrowableInformation throwableInfo; /** The number of milliseconds elapsed from 1/1/1970 until logging event was created. */ public final long timeStamp; /** Location information for the caller. */ private LocationInfo locationInfo; // Serialization static final long serialVersionUID = -868428216207166145L; static final Integer[] PARAM_ARRAY = new Integer[1]; static final String TO_LEVEL = "toLevel"; static final Class[] TO_LEVEL_PARAMS = new Class[] {int.class}; static final Hashtable methodCache = new Hashtable(3); // use a tiny table /** Instantiate a LoggingEvent from the supplied parameters.

Except {@link #timeStamp} all the other fields of LoggingEvent are filled when actually needed.

@param logger The logger generating this event. @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, Priority level, Object message, Throwable throwable) { this.fqnOfCategoryClass = fqnOfCategoryClass; this.logger = logger; this.categoryName = logger.getName(); this.level = level; this.message = message; if(throwable != null) { this.throwableInfo = new ThrowableInformation(throwable, logger); } timeStamp = System.currentTimeMillis(); } /** Instantiate a LoggingEvent from the supplied parameters.

Except {@link #timeStamp} all the other fields of LoggingEvent are filled when actually needed.

@param logger The logger generating this event. @param timeStamp the timestamp of this logging event @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 level, Object message, Throwable throwable) { this.fqnOfCategoryClass = fqnOfCategoryClass; this.logger = logger; this.categoryName = logger.getName(); this.level = level; this.message = message; if(throwable != null) { this.throwableInfo = new ThrowableInformation(throwable, logger); } this.timeStamp = timeStamp; } /** Create new instance. @since 1.2.15 @param fqnOfCategoryClass Fully qualified class name of Logger implementation. @param logger The logger generating this event. @param timeStamp the timestamp of this logging event @param level The level of this event. @param message The message of this event. @param threadName thread name @param throwable The throwable of this event. @param ndc Nested diagnostic context @param info Location info @param properties MDC properties */ public LoggingEvent(final String fqnOfCategoryClass, final Category logger, final long timeStamp, final Level level, final Object message, final String threadName, final ThrowableInformation throwable, final String ndc, final LocationInfo info, final java.util.Map properties) { super(); this.fqnOfCategoryClass = fqnOfCategoryClass; this.logger = logger; if (logger != null) { categoryName = logger.getName(); } else { categoryName = null; } this.level = level; this.message = message; if(throwable != null) { this.throwableInfo = throwable; } this.timeStamp = timeStamp; this.threadName = threadName; ndcLookupRequired = false; this.ndc = ndc; this.locationInfo = info; mdcCopyLookupRequired = false; if (properties != null) { mdcCopy = new java.util.Hashtable(properties); } } /** Set the location information for this logging event. The collected information is cached for future use. */ public LocationInfo getLocationInformation() { if(locationInfo == null) { locationInfo = new LocationInfo(new Throwable(), fqnOfCategoryClass); } return locationInfo; } /** * Return the level of this event. Use this form instead of directly * accessing the level field. */ public Level getLevel() { return (Level) level; } /** * Return the name of the logger. Use this form instead of directly * accessing the categoryName field. */ public String getLoggerName() { return categoryName; } /** * Gets the logger of the event. * Use should be restricted to cloning events. * @since 1.2.15 */ public Category getLogger() { return logger; } /** Return the message for this logging event.

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. @since 1.1 */ public Object getMessage() { if(message != null) { return message; } else { return getRenderedMessage(); } } /** * This method returns the NDC for this event. It will return the * correct content even if the event was generated in a different * thread or even on a different machine. The {@link NDC#get} method * should never be called directly. */ public String getNDC() { if(ndcLookupRequired) { ndcLookupRequired = false; ndc = NDC.get(); } return ndc; } /** Returns the the context corresponding to the key parameter. If there is a local MDC copy, possibly because we are in a logging server or running inside AsyncAppender, then we search for the key in MDC copy, if a value is found it is returned. Otherwise, if the search in MDC copy returns a null result, then the current thread's MDC is used.

Note that both the local MDC copy and the current thread's MDC are searched. */ public Object getMDC(String key) { Object r; // Note the mdcCopy is used if it exists. Otherwise we use the MDC // that is associated with the thread. if(mdcCopy != null) { r = mdcCopy.get(key); if(r != null) { return r; } } return MDC.get(key); } /** Obtain a copy of this thread's MDC prior to serialization or asynchronous logging. */ public void getMDCCopy() { if(mdcCopyLookupRequired) { mdcCopyLookupRequired = false; // the clone call is required for asynchronous logging. // See also bug #5932. Hashtable t = (Hashtable) MDC.getContext(); if(t != null) { mdcCopy = (Hashtable) t.clone(); } } } public String getRenderedMessage() { if(renderedMessage == null && message != null) { if(message instanceof String) renderedMessage = (String) message; else { LoggerRepository repository = logger.getLoggerRepository(); if(repository instanceof RendererSupport) { RendererSupport rs = (RendererSupport) repository; renderedMessage= rs.getRendererMap().findAndRender(message); } else { renderedMessage = message.toString(); } } } return renderedMessage; } /** Returns the time when the application started, in milliseconds elapsed since 01.01.1970. */ public static long getStartTime() { return startTime; } public String getThreadName() { if(threadName == null) threadName = (Thread.currentThread()).getName(); return threadName; } /** Returns the throwable information contained within this event. May be null if there is no such information.

Note that the {@link Throwable} object contained within a {@link ThrowableInformation} does not survive serialization. @since 1.1 */ public ThrowableInformation getThrowableInformation() { return throwableInfo; } /** Return this event's throwable's string[] representaion. */ public String[] getThrowableStrRep() { if(throwableInfo == null) return null; else return throwableInfo.getThrowableStrRep(); } private void readLevel(ObjectInputStream ois) throws java.io.IOException, ClassNotFoundException { int p = ois.readInt(); try { String className = (String) ois.readObject(); if(className == null) { level = Level.toLevel(p); } else { Method m = (Method) methodCache.get(className); if(m == null) { Class clazz = Loader.loadClass(className); // Note that we use Class.getDeclaredMethod instead of // Class.getMethod. This assumes that the Level subclass // implements the toLevel(int) method which is a // requirement. Actually, it does not make sense for Level // subclasses NOT to implement this method. Also note that // only Level can be subclassed and not Priority. m = clazz.getDeclaredMethod(TO_LEVEL, TO_LEVEL_PARAMS); methodCache.put(className, m); } level = (Level) m.invoke(null, new Integer[] { new Integer(p) } ); } } catch(InvocationTargetException e) { if (e.getTargetException() instanceof InterruptedException || e.getTargetException() instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.warn("Level deserialization failed, reverting to default.", e); level = Level.toLevel(p); } catch(NoSuchMethodException e) { LogLog.warn("Level deserialization failed, reverting to default.", e); level = Level.toLevel(p); } catch(IllegalAccessException e) { LogLog.warn("Level deserialization failed, reverting to default.", e); level = Level.toLevel(p); } catch(RuntimeException e) { LogLog.warn("Level deserialization failed, reverting to default.", e); level = Level.toLevel(p); } } private void readObject(ObjectInputStream ois) throws java.io.IOException, ClassNotFoundException { ois.defaultReadObject(); readLevel(ois); // Make sure that no location info is available to Layouts if(locationInfo == null) locationInfo = new LocationInfo(null, null); } private 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 sets the renders the message in case it wasn't up to now. this.getRenderedMessage(); // This call has a side effect of setting this.ndc and // setting ndcLookupRequired to false if not already false. this.getNDC(); // This call has a side effect of setting this.mdcCopy and // setting mdcLookupRequired to false if not already false. this.getMDCCopy(); // This sets the throwable sting representation of the event throwable. this.getThrowableStrRep(); oos.defaultWriteObject(); // serialize this event's level writeLevel(oos); } private void writeLevel(ObjectOutputStream oos) throws java.io.IOException { oos.writeInt(level.toInt()); Class clazz = level.getClass(); if(clazz == Level.class) { oos.writeObject(null); } else { // writing directly the Class object would be nicer, except that // serialized a Class object can not be read back by JDK // 1.1.x. We have to resort to this hack instead. oos.writeObject(clazz.getName()); } } /** * Set value for MDC property. * This adds the specified MDC property to the event. * Access to the MDC is not synchronized, so this * method should only be called when it is known that * no other threads are accessing the MDC. * @since 1.2.15 * @param propName * @param propValue */ public final void setProperty(final String propName, final String propValue) { if (mdcCopy == null) { getMDCCopy(); } if (mdcCopy == null) { mdcCopy = new Hashtable(); } mdcCopy.put(propName, propValue); } /** * Return a property for this event. The return value can be null. * * Equivalent to getMDC(String) in log4j 1.2. Provided * for compatibility with log4j 1.3. * * @param key property name * @return property value or null if property not set * @since 1.2.15 */ public final String getProperty(final String key) { Object value = getMDC(key); String retval = null; if (value != null) { retval = value.toString(); } return retval; } /** * Check for the existence of location information without creating it * (a byproduct of calling getLocationInformation). * @return true if location information has been extracted. * @since 1.2.15 */ public final boolean locationInformationExists() { return (locationInfo != null); } /** * Getter for the event's time stamp. The time stamp is calculated starting * from 1970-01-01 GMT. * @return timestamp * * @since 1.2.15 */ public final long getTimeStamp() { return timeStamp; } /** * Returns the set of the key values in the properties * for the event. * * The returned set is unmodifiable by the caller. * * Provided for compatibility with log4j 1.3 * * @return Set an unmodifiable set of the property keys. * @since 1.2.15 */ public Set getPropertyKeySet() { return getProperties().keySet(); } /** * Returns the set of properties * for the event. * * The returned set is unmodifiable by the caller. * * Provided for compatibility with log4j 1.3 * * @return Set an unmodifiable map of the properties. * @since 1.2.15 */ public Map getProperties() { getMDCCopy(); Map properties; if (mdcCopy == null) { properties = new HashMap(); } else { properties = mdcCopy; } return Collections.unmodifiableMap(properties); } /** * Get the fully qualified name of the calling logger sub-class/wrapper. * Provided for compatibility with log4j 1.3 * @return fully qualified class name, may be null. * @since 1.2.15 */ public String getFQNOfLoggerClass() { return fqnOfCategoryClass; } /** * This removes the specified MDC property from the event. * Access to the MDC is not synchronized, so this * method should only be called when it is known that * no other threads are accessing the MDC. * @param propName the property name to remove * @since 1.2.16 */ public Object removeProperty(String propName) { if (mdcCopy == null) { getMDCCopy(); } if (mdcCopy == null) { mdcCopy = new Hashtable(); } return mdcCopy.remove(propName); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/ThrowableRenderer.java0000644000175000017500000000225611751454706026542 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; /** * Implemented by classes that render instances of * java.lang.Throwable (exceptions and errors) * into a string representation. * * @since 1.2.16 */ public interface ThrowableRenderer { /** * Render Throwable. * @param t throwable, may not be null. * @return String representation. */ public String[] doRender(Throwable t); } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/DefaultRepositorySelector.java0000644000175000017500000000216311751454706030306 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; public class DefaultRepositorySelector implements RepositorySelector { final LoggerRepository repository; public DefaultRepositorySelector(LoggerRepository repository) { this.repository = repository; } public LoggerRepository getLoggerRepository() { return repository; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/Configurator.java0000644000175000017500000000416611751454706025570 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; import java.io.InputStream; import java.net.URL; /** Implemented by classes capable of configuring log4j using a URL. @since 1.0 @author Anders Kristensen */ public interface Configurator { /** Special level value signifying inherited behaviour. The current value of this string constant is inherited. {@link #NULL} is a synonym. */ public static final String INHERITED = "inherited"; /** Special level signifying inherited behaviour, same as {@link #INHERITED}. The current value of this string constant is null. */ public static final String NULL = "null"; /** Interpret a resource pointed by a InputStream and set up log4j accordingly. The configuration is done relative to the hierarchy parameter. @param inputStream The InputStream to parse @param repository The hierarchy to operation upon. @since 1.2.17 */ void doConfigure(InputStream inputStream, LoggerRepository repository); /** Interpret a resource pointed by a URL and set up log4j accordingly. The configuration is done relative to the hierarchy parameter. @param url The URL to parse @param repository The hierarchy to operation upon. */ void doConfigure(URL url, LoggerRepository repository); } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/TriggeringEventEvaluator.java0000644000175000017500000000261211751454706030106 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; /** Implementions of this interface allow certain appenders to decide when to perform an appender specific action.

For example the {@link org.apache.log4j.net.SMTPAppender} sends an email when the {@link #isTriggeringEvent} method returns true and adds the event to an internal buffer when the returned result is false. @author Ceki Gülcü @since version 1.0 */ public interface TriggeringEventEvaluator { /** Is this the triggering event? */ public boolean isTriggeringEvent(LoggingEvent event); } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/RendererSupport.java0000644000175000017500000000206711751454706026267 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; import org.apache.log4j.or.ObjectRenderer; import org.apache.log4j.or.RendererMap; public interface RendererSupport { public RendererMap getRendererMap(); public void setRenderer(Class renderedClass, ObjectRenderer renderer); } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/AppenderAttachable.java0000644000175000017500000000355411751454706026635 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; import org.apache.log4j.Appender; import java.util.Enumeration; /** Interface for attaching appenders to objects. @author Ceki Gülcü @since 0.9.1 */ public interface AppenderAttachable { /** Add an appender. */ public void addAppender(Appender newAppender); /** Get all previously added appenders as an Enumeration. */ public Enumeration getAllAppenders(); /** Get an appender by name. */ public Appender getAppender(String name); /** Returns true if the specified appender is in list of attached attached, false otherwise. @since 1.2 */ public boolean isAttached(Appender appender); /** Remove all previously added appenders. */ void removeAllAppenders(); /** Remove the appender passed as parameter from the list of appenders. */ void removeAppender(Appender appender); /** Remove the appender with the name passed as parameter from the list of appenders. */ void removeAppender(String name); } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/RootLogger.java0000644000175000017500000000411711751454706025205 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.helpers.LogLog; // Contibutors: Mathias Bogaert /** RootLogger sits at the top of the logger hierachy. It is a regular logger except that it provides several guarantees.

First, it cannot be assigned a null level. Second, since root logger cannot have a parent, the {@link #getChainedLevel} method always returns the value of the level field without walking the hierarchy. @author Ceki Gülcü */ public final class RootLogger extends Logger { /** The root logger names itself as "root". However, the root logger cannot be retrieved by name. */ public RootLogger(Level level) { super("root"); setLevel(level); } /** Return the assigned level value without walking the logger hierarchy. */ public final Level getChainedLevel() { return level; } /** Setting a null value to the level of the root logger may have catastrophic results. We prevent this here. @since 0.8.3 */ public final void setLevel(Level level) { if (level == null) { LogLog.error( "You have tried to set a null level to root.", new Throwable()); } else { this.level = level; } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/ErrorHandler.java0000644000175000017500000000557511751454706025522 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; import org.apache.log4j.Appender; import org.apache.log4j.Logger; /** Appenders may delegate their error handling to ErrorHandlers.

Error handling is a particularly tedious to get right because by definition errors are hard to predict and to reproduce.

Please take the time to contact the author in case you discover that errors are not properly handled. You are most welcome to suggest new error handling policies or criticize existing policies. @author Ceki Gülcü */ public interface ErrorHandler extends OptionHandler { /** Add a reference to a logger to which the failing appender might be attached to. The failing appender will be searched and replaced only in the loggers you add through this method. @param logger One of the loggers that will be searched for the failing appender in view of replacement. @since 1.2 */ void setLogger(Logger logger); /** Equivalent to the {@link #error(String, Exception, int, LoggingEvent event)} with the the event parameteter set to null. */ void error(String message, Exception e, int errorCode); /** This method is normally used to just print the error message passed as a parameter. */ void error(String message); /** This method is invoked to handle the error. @param message The message assoicated with the error. @param e The Exption that was thrown when the error occured. @param errorCode The error code associated with the error. @param event The logging event that the failing appender is asked to log. @since 1.2 */ void error(String message, Exception e, int errorCode, LoggingEvent event); /** Set the appender for which errors are handled. This method is usually called when the error handler is configured. @since 1.2 */ void setAppender(Appender appender); /** Set the appender to falkback upon in case of failure. @since 1.2 */ void setBackupAppender(Appender appender); } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/ErrorCode.java0000644000175000017500000000236311751454706025007 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; /** This interface defines commonly encoutered error codes. @author Ceki Gülcü @since 0.9.0 */ public interface ErrorCode { public final int GENERIC_FAILURE = 0; public final int WRITE_FAILURE = 1; public final int FLUSH_FAILURE = 2; public final int CLOSE_FAILURE = 3; public final int FILE_OPEN_FAILURE = 4; public final int MISSING_LAYOUT = 5; public final int ADDRESS_PARSE_FAILURE = 6; } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/NOPLogger.java0000644000175000017500000001171511751454706024720 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; import org.apache.log4j.Appender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.Priority; import java.util.Enumeration; import java.util.ResourceBundle; import java.util.Vector; /** * No-operation implementation of Logger used by NOPLoggerRepository. * @since 1.2.15 */ public final class NOPLogger extends Logger { /** * Create instance of Logger. * @param repo repository, may not be null. * @param name name, may not be null, use "root" for root logger. */ public NOPLogger(NOPLoggerRepository repo, final String name) { super(name); this.repository = repo; this.level = Level.OFF; this.parent = this; } /** {@inheritDoc} */ public void addAppender(final Appender newAppender) { } /** {@inheritDoc} */ public void assertLog(final boolean assertion, final String msg) { } /** {@inheritDoc} */ public void callAppenders(final LoggingEvent event) { } /** {@inheritDoc} */ void closeNestedAppenders() { } /** {@inheritDoc} */ public void debug(final Object message) { } /** {@inheritDoc} */ public void debug(final Object message, final Throwable t) { } /** {@inheritDoc} */ public void error(final Object message) { } /** {@inheritDoc} */ public void error(final Object message, final Throwable t) { } /** {@inheritDoc} */ public void fatal(final Object message) { } /** {@inheritDoc} */ public void fatal(final Object message, final Throwable t) { } /** {@inheritDoc} */ public Enumeration getAllAppenders() { return new Vector().elements(); } /** {@inheritDoc} */ public Appender getAppender(final String name) { return null; } /** {@inheritDoc} */ public Level getEffectiveLevel() { return Level.OFF; } /** {@inheritDoc} */ public Priority getChainedPriority() { return getEffectiveLevel(); } /** {@inheritDoc} */ public ResourceBundle getResourceBundle() { return null; } /** {@inheritDoc} */ public void info(final Object message) { } /** {@inheritDoc} */ public void info(final Object message, final Throwable t) { } /** {@inheritDoc} */ public boolean isAttached(Appender appender) { return false; } /** {@inheritDoc} */ public boolean isDebugEnabled() { return false; } /** {@inheritDoc} */ public boolean isEnabledFor(final Priority level) { return false; } /** {@inheritDoc} */ public boolean isInfoEnabled() { return false; } /** {@inheritDoc} */ public void l7dlog(final Priority priority, final String key, final Throwable t) { } /** {@inheritDoc} */ public void l7dlog(final Priority priority, final String key, final Object[] params, final Throwable t) { } /** {@inheritDoc} */ public void log(final Priority priority, final Object message, final Throwable t) { } /** {@inheritDoc} */ public void log(final Priority priority, final Object message) { } /** {@inheritDoc} */ public void log(final String callerFQCN, final Priority level, final Object message, final Throwable t) { } /** {@inheritDoc} */ public void removeAllAppenders() { } /** {@inheritDoc} */ public void removeAppender(Appender appender) { } /** {@inheritDoc} */ public void removeAppender(final String name) { } /** {@inheritDoc} */ public void setLevel(final Level level) { } /** {@inheritDoc} */ public void setPriority(final Priority priority) { } /** {@inheritDoc} */ public void setResourceBundle(final ResourceBundle bundle) { } /** {@inheritDoc} */ public void warn(final Object message) { } /** {@inheritDoc} */ public void warn(final Object message, final Throwable t) { } /** {@inheritDoc} */ public void trace(Object message) { } /** {@inheritDoc} */ public void trace(Object message, Throwable t) { } /** {@inheritDoc} */ public boolean isTraceEnabled() { return false; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/LocationInfo.java0000644000175000017500000003110611751454706025504 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Contributors: Mathias Rupprecht package org.apache.log4j.spi; import org.apache.log4j.Layout; import org.apache.log4j.helpers.LogLog; import java.io.PrintWriter; import java.io.StringWriter; import java.io.InterruptedIOException; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; /** The internal representation of caller location information. @since 0.8.3 */ public class LocationInfo implements java.io.Serializable { /** Caller's line number. */ transient String lineNumber; /** Caller's file name. */ transient String fileName; /** Caller's fully qualified class name. */ transient String className; /** Caller's method name. */ transient String methodName; /** All available caller information, in the format fully.qualified.classname.of.caller.methodName(Filename.java:line) */ public String fullInfo; private static StringWriter sw = new StringWriter(); private static PrintWriter pw = new PrintWriter(sw); private static Method getStackTraceMethod; private static Method getClassNameMethod; private static Method getMethodNameMethod; private static Method getFileNameMethod; private static Method getLineNumberMethod; /** When location information is not available the constant NA is returned. Current value of this string constant is ?. */ public final static String NA = "?"; static final long serialVersionUID = -1325822038990805636L; /** * NA_LOCATION_INFO is provided for compatibility with log4j 1.3. * @since 1.2.15 */ public static final LocationInfo NA_LOCATION_INFO = new LocationInfo(NA, NA, NA, NA); // Check if we are running in IBM's visual age. static boolean inVisualAge = false; static { try { inVisualAge = Class.forName("com.ibm.uvm.tools.DebugSupport") != null; LogLog.debug("Detected IBM VisualAge environment."); } catch(Throwable e) { // nothing to do } try { Class[] noArgs = null; getStackTraceMethod = Throwable.class.getMethod("getStackTrace", noArgs); Class stackTraceElementClass = Class.forName("java.lang.StackTraceElement"); getClassNameMethod = stackTraceElementClass.getMethod("getClassName", noArgs); getMethodNameMethod = stackTraceElementClass.getMethod("getMethodName", noArgs); getFileNameMethod = stackTraceElementClass.getMethod("getFileName", noArgs); getLineNumberMethod = stackTraceElementClass.getMethod("getLineNumber", noArgs); } catch(ClassNotFoundException ex) { LogLog.debug("LocationInfo will use pre-JDK 1.4 methods to determine location."); } catch(NoSuchMethodException ex) { LogLog.debug("LocationInfo will use pre-JDK 1.4 methods to determine location."); } } /** Instantiate location information based on a Throwable. We expect the Throwable t, to be in the format

        java.lang.Throwable
        ...
          at org.apache.log4j.PatternLayout.format(PatternLayout.java:413)
          at org.apache.log4j.FileAppender.doAppend(FileAppender.java:183)
        at org.apache.log4j.Category.callAppenders(Category.java:131)
        at org.apache.log4j.Category.log(Category.java:512)
        at callers.fully.qualified.className.methodName(FileName.java:74)
	...
       

However, we can also deal with JIT compilers that "lose" the location information, especially between the parentheses. @param t throwable used to determine location, may be null. @param fqnOfCallingClass class name of first class considered part of the logging framework. Location will be site that calls a method on this class. */ public LocationInfo(Throwable t, String fqnOfCallingClass) { if(t == null || fqnOfCallingClass == null) return; if (getLineNumberMethod != null) { try { Object[] noArgs = null; Object[] elements = (Object[]) getStackTraceMethod.invoke(t, noArgs); String prevClass = NA; for(int i = elements.length - 1; i >= 0; i--) { String thisClass = (String) getClassNameMethod.invoke(elements[i], noArgs); if(fqnOfCallingClass.equals(thisClass)) { int caller = i + 1; if (caller < elements.length) { className = prevClass; methodName = (String) getMethodNameMethod.invoke(elements[caller], noArgs); fileName = (String) getFileNameMethod.invoke(elements[caller], noArgs); if (fileName == null) { fileName = NA; } int line = ((Integer) getLineNumberMethod.invoke(elements[caller], noArgs)).intValue(); if (line < 0) { lineNumber = NA; } else { lineNumber = String.valueOf(line); } StringBuffer buf = new StringBuffer(); buf.append(className); buf.append("."); buf.append(methodName); buf.append("("); buf.append(fileName); buf.append(":"); buf.append(lineNumber); buf.append(")"); this.fullInfo = buf.toString(); } return; } prevClass = thisClass; } return; } catch(IllegalAccessException ex) { LogLog.debug("LocationInfo failed using JDK 1.4 methods", ex); } catch(InvocationTargetException ex) { if (ex.getTargetException() instanceof InterruptedException || ex.getTargetException() instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.debug("LocationInfo failed using JDK 1.4 methods", ex); } catch(RuntimeException ex) { LogLog.debug("LocationInfo failed using JDK 1.4 methods", ex); } } String s; // Protect against multiple access to sw. synchronized(sw) { t.printStackTrace(pw); s = sw.toString(); sw.getBuffer().setLength(0); } //System.out.println("s is ["+s+"]."); int ibegin, iend; // Given the current structure of the package, the line // containing "org.apache.log4j.Category." should be printed just // before the caller. // 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. ibegin = s.lastIndexOf(fqnOfCallingClass); if(ibegin == -1) return; // // if the next character after the class name exists // but is not a period, see if the classname is // followed by a period earlier in the trace. // Minimizes mistakeningly matching on a class whose // name is a substring of the desired class. // See bug 44888. if (ibegin + fqnOfCallingClass.length() < s.length() && s.charAt(ibegin + fqnOfCallingClass.length()) != '.') { int i = s.lastIndexOf(fqnOfCallingClass + "."); if (i != -1) { ibegin = i; } } 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) return; // 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) return; // Add 3 to skip "at "; ibegin += 3; } // everything between is the requested stack item this.fullInfo = s.substring(ibegin, iend); } /** * Appends a location fragment to a buffer to build the * full location info. * @param buf StringBuffer to receive content. * @param fragment fragment of location (class, method, file, line), * if null the value of NA will be appended. * @since 1.2.15 */ private static final void appendFragment(final StringBuffer buf, final String fragment) { if (fragment == null) { buf.append(NA); } else { buf.append(fragment); } } /** * Create new instance. * @param file source file name * @param classname class name * @param method method * @param line source line number * * @since 1.2.15 */ public LocationInfo( final String file, final String classname, final String method, final String line) { this.fileName = file; this.className = classname; this.methodName = method; this.lineNumber = line; StringBuffer buf = new StringBuffer(); appendFragment(buf, classname); buf.append("."); appendFragment(buf, method); buf.append("("); appendFragment(buf, file); buf.append(":"); appendFragment(buf, line); buf.append(")"); this.fullInfo = buf.toString(); } /** Return the fully qualified class name of the caller making the logging request. */ public 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) className = NA; else { iend =fullInfo.lastIndexOf('.', iend); // This is because a stack trace in VisualAge looks like: //java.lang.RuntimeException // java.lang.Throwable() // java.lang.Exception() // java.lang.RuntimeException() // void test.test.B.print() // void test.test.A.printIndirect() // void test.test.Run.main(java.lang.String []) int ibegin = 0; if (inVisualAge) { ibegin = fullInfo.lastIndexOf(' ', iend)+1; } if(iend == -1) className = NA; else className = this.fullInfo.substring(ibegin, iend); } } return className; } /** Return the file name of the caller.

This information is not always available. */ public String getFileName() { if(fullInfo == null) return NA; if(fileName == null) { 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; } /** Returns the line number of the caller.

This information is not always available. */ public String getLineNumber() { if(fullInfo == null) return NA; if(lineNumber == null) { int iend = fullInfo.lastIndexOf(')'); int ibegin = fullInfo.lastIndexOf(':', iend -1); if(ibegin == -1) lineNumber = NA; else lineNumber = this.fullInfo.substring(ibegin + 1, iend); } return lineNumber; } /** Returns the method name of the caller. */ public String getMethodName() { if(fullInfo == null) return NA; if(methodName == null) { int iend = fullInfo.lastIndexOf('('); int ibegin = fullInfo.lastIndexOf('.', iend); if(ibegin == -1) methodName = NA; else methodName = this.fullInfo.substring(ibegin + 1, iend); } return methodName; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/OptionHandler.java0000644000175000017500000000414211751454706025666 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; /** A string based interface to configure package components. @author Ceki Gülcü @author Anders Kristensen @since 0.8.1 */ public interface OptionHandler { /** Activate the options that were previously set with calls to option setters.

This allows to defer activiation of the options until all options have been set. This is required for components which have related options that remain ambigous until all are set.

For example, the FileAppender has the {@link org.apache.log4j.FileAppender#setFile File} and {@link org.apache.log4j.FileAppender#setAppend Append} options both of which are ambigous until the other is also set. */ void activateOptions(); /** Return list of strings that the OptionHandler instance recognizes. @deprecated We now use JavaBeans style getters/setters. */ // String[] getOptionStrings(); /** Set option to value.

The handling of each option depends on the OptionHandler 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); } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/VectorWriter.java0000644000175000017500000000435011751454706025560 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; import java.io.PrintWriter; import java.util.Vector; /** * VectorWriter is an obsolete class provided only for * binary compatibility with earlier versions of log4j and should not be used. * * @deprecated */ class VectorWriter extends PrintWriter { private Vector v; /** * @deprecated */ VectorWriter() { super(new NullWriter()); v = new Vector(); } public void print(Object o) { v.addElement(String.valueOf(o)); } public void print(char[] chars) { v.addElement(new String(chars)); } public void print(String s) { v.addElement(s); } public void println(Object o) { v.addElement(String.valueOf(o)); } // JDK 1.1.x apprenly uses this form of println while in // printStackTrace() public void println(char[] chars) { v.addElement(new String(chars)); } public void println(String s) { v.addElement(s); } public void write(char[] chars) { v.addElement(new String(chars)); } public void write(char[] chars, int off, int len) { v.addElement(new String(chars, off, len)); } public void write(String s, int off, int len) { v.addElement(s.substring(off, off+len)); } public void write(String s) { v.addElement(s); } public String[] toStringArray() { int len = v.size(); String[] sa = new String[len]; for(int i = 0; i < len; i++) { sa[i] = (String) v.elementAt(i); } return sa; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/HierarchyEventListener.java0000644000175000017500000000242211751454706027545 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; import org.apache.log4j.Appender; import org.apache.log4j.Category; /** Listen to events occuring within a {@link org.apache.log4j.Hierarchy Hierarchy}. @author Ceki Gülcü @since 1.2 */ public interface HierarchyEventListener { //public //void categoryCreationEvent(Category cat); public void addAppenderEvent(Category cat, Appender appender); public void removeAppenderEvent(Category cat, Appender appender); } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/NOPLoggerRepository.java0000644000175000017500000000563411751454706027023 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; import org.apache.log4j.Level; import org.apache.log4j.Category; import org.apache.log4j.Logger; import org.apache.log4j.Appender; import java.util.Enumeration; import java.util.Vector; /** * No-operation implementation of LoggerRepository which is used when * LogManager.repositorySelector is erroneously nulled during class reloading. * @since 1.2.15 */ public final class NOPLoggerRepository implements LoggerRepository { /** * {@inheritDoc} */ public void addHierarchyEventListener(final HierarchyEventListener listener) { } /** * {@inheritDoc} */ public boolean isDisabled(final int level) { return true; } /** * {@inheritDoc} */ public void setThreshold(final Level level) { } /** * {@inheritDoc} */ public void setThreshold(final String val) { } /** * {@inheritDoc} */ public void emitNoAppenderWarning(final Category cat) { } /** * {@inheritDoc} */ public Level getThreshold() { return Level.OFF; } /** * {@inheritDoc} */ public Logger getLogger(final String name) { return new NOPLogger(this, name); } /** * {@inheritDoc} */ public Logger getLogger(final String name, final LoggerFactory factory) { return new NOPLogger(this, name); } /** * {@inheritDoc} */ public Logger getRootLogger() { return new NOPLogger(this, "root"); } /** * {@inheritDoc} */ public Logger exists(final String name) { return null; } /** * {@inheritDoc} */ public void shutdown() { } /** * {@inheritDoc} */ public Enumeration getCurrentLoggers() { return new Vector().elements(); } /** * {@inheritDoc} */ public Enumeration getCurrentCategories() { return getCurrentLoggers(); } /** * {@inheritDoc} */ public void fireAddAppenderEvent(Category logger, Appender appender) { } /** * {@inheritDoc} */ public void resetConfiguration() { } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/NullWriter.java0000644000175000017500000000227411751454706025233 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; import java.io.Writer; /** * NullWriter is an obsolete class provided only for * binary compatibility with earlier versions of log4j and should not be used. * * @deprecated */ class NullWriter extends Writer { public void close() { // blank } public void flush() { // blank } public void write(char[] cbuf, int off, int len) { // blank } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/Filter.java0000644000175000017500000001005311751454706024343 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; /** Users should extend this class to implement customized logging event filtering. Note that {@link org.apache.log4j.Category} and {@link org.apache.log4j.AppenderSkeleton}, the parent class of all standard appenders, have built-in filtering rules. It is suggested that you first use and understand the built-in rules before rushing to write your own custom filters.

This abstract class assumes and also imposes that filters be organized in a linear chain. The {@link #decide decide(LoggingEvent)} method of each filter is called sequentially, in the order of their addition to the chain.

The {@link #decide decide(LoggingEvent)} method must return one of the integer constants {@link #DENY}, {@link #NEUTRAL} or {@link #ACCEPT}.

If the value {@link #DENY} is returned, then the log event is dropped immediately without consulting with the remaining filters.

If the value {@link #NEUTRAL} is returned, then the next filter in the chain is consulted. If there are no more filters in the chain, then the log event is logged. Thus, in the presence of no filters, the default behaviour is to log all logging events.

If the value {@link #ACCEPT} is returned, then the log event is logged without consulting the remaining filters.

The philosophy of log4j filters is largely inspired from the Linux ipchains.

Note that filtering is only supported by the {@link org.apache.log4j.xml.DOMConfigurator DOMConfigurator}. The {@link org.apache.log4j.PropertyConfigurator PropertyConfigurator} does not support filters. @author Ceki Gülcü @since 0.9.0 */ public abstract class Filter implements OptionHandler { /** Points to the next filter in the filter chain. @deprecated As of 1.2.12, use {@link #getNext} and {@link #setNext} instead */ public Filter next; /** The log event must be dropped immediately without consulting with the remaining filters, if any, in the chain. */ public static final int DENY = -1; /** This filter is neutral with respect to the log event. The remaining filters, if any, should be consulted for a final decision. */ public static final int NEUTRAL = 0; /** The log event must be logged immediately without consulting with the remaining filters, if any, in the chain. */ public static final int ACCEPT = 1; /** Usually filters options become active when set. We provide a default do-nothing implementation for convenience. */ public void activateOptions() { } /**

If the decision is DENY, then the event will be dropped. If the decision is NEUTRAL, then the next filter, if any, will be invoked. If the decision is ACCEPT then the event will be logged without consulting with other filters in the chain. @param event The LoggingEvent to decide upon. @return decision The decision of the filter. */ abstract public int decide(LoggingEvent event); /** * Set the next filter pointer. */ public void setNext(Filter next) { this.next = next; } /** * Return the pointer to the next filter; */ public Filter getNext() { return next; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/RepositorySelector.java0000644000175000017500000000311511751454706026777 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; /** The LogManager uses one (and only one) RepositorySelector implementation to select the {@link LoggerRepository} for a particular application context.

It is the responsability of the RepositorySelector implementation to track the application context. Log4j makes no assumptions about the application context or on its management.

See also {@link org.apache.log4j.LogManager LogManager}. @author Ceki Gülcü @since 1.2 */ public interface RepositorySelector { /** Returns a {@link LoggerRepository} depending on the context. Implementors must make sure that a valid (non-null) LoggerRepository is returned. */ public LoggerRepository getLoggerRepository(); } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/spi/LoggerFactory.java0000644000175000017500000000225011751454706025665 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; import org.apache.log4j.Logger; /** Implement this interface to create new instances of Logger or a sub-class of Logger.

See examples/subclass/MyLogger.java for an example. @author Ceki Gülcü @since version 0.8.5 */ public interface LoggerFactory { public Logger makeNewLoggerInstance(String name); } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/FileAppender.java0000644000175000017500000002327611751454711024670 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InterruptedIOException; import java.io.Writer; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.helpers.QuietWriter; import org.apache.log4j.spi.ErrorCode; // Contibutors: Jens Uwe Pipka // Ben Sandee /** * FileAppender appends log events to a file. * *

Support for java.io.Writer 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 { /** Controls file truncatation. The default value for this variable * is true, meaning that by default a * FileAppender will append to an existing file and not * truncate it. * *

This option is meaningful only if the FileAppender opens the * file. */ protected boolean fileAppend = true; /** The name of the log file. */ protected String fileName = null; /** Do we do bufferedIO? */ protected boolean bufferedIO = false; /** * Determines the size of IO buffer be. Default is 8K. */ protected int bufferSize = 8*1024; /** The default constructor does not do anything. */ public FileAppender() { } /** Instantiate a FileAppender and open the file designated by filename. The opened filename will become the output destination for this appender.

If the append parameter is true, the file will be appended to. Otherwise, the file designated by filename will be truncated before being opened.

If the bufferedIO parameter is true, then buffered IO will be used to write to the output file. */ public FileAppender(Layout layout, String filename, boolean append, boolean bufferedIO, int bufferSize) throws IOException { this.layout = layout; this.setFile(filename, append, bufferedIO, bufferSize); } /** Instantiate a FileAppender and open the file designated by filename. The opened filename will become the output destination for this appender.

If the append parameter is true, the file will be appended to. Otherwise, the file designated by filename will be truncated before being opened. */ public FileAppender(Layout layout, String filename, boolean append) throws IOException { this.layout = layout; this.setFile(filename, append, false, bufferSize); } /** Instantiate a FileAppender and open the file designated by filename. The opened filename will become the output destination for this appender.

The file will be appended to. */ public FileAppender(Layout layout, String filename) throws IOException { this(layout, filename, true); } /** The File property takes a string value which should be the name of the file to append to.

Note that the special values "System.out" or "System.err" are no longer honored.

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 // trailing spaces in file names. String val = file.trim(); fileName = val; } /** Returns the value of the Append option. */ public boolean getAppend() { return fileAppend; } /** Returns the value of the File option. */ public String getFile() { return fileName; } /** If the value of File is not null, then {@link #setFile} is called with the values of File and Append properties. @since 0.8.1 */ public void activateOptions() { if(fileName != null) { try { setFile(fileName, fileAppend, bufferedIO, bufferSize); } catch(java.io.IOException e) { errorHandler.error("setFile("+fileName+","+fileAppend+") call failed.", e, ErrorCode.FILE_OPEN_FAILURE); } } else { //LogLog.error("File option not set for appender ["+name+"]."); LogLog.warn("File option not set for appender ["+name+"]."); LogLog.warn("Are you using FileAppender instead of ConsoleAppender?"); } } /** Closes the previously opened file. */ protected void closeFile() { if(this.qw != null) { try { this.qw.close(); } catch(java.io.IOException e) { if (e instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } // Exceptionally, it does not make sense to delegate to an // ErrorHandler. Since a closed appender is basically dead. LogLog.error("Could not close " + qw, e); } } } /** Get the value of the BufferedIO option.

BufferedIO will significatnly increase performance on heavily loaded systems. */ public boolean getBufferedIO() { return this.bufferedIO; } /** Get the size of the IO buffer. */ public int getBufferSize() { return this.bufferSize; } /** The Append option takes a boolean value. It is set to true by default. If true, then File will be opened in append mode by {@link #setFile setFile} (see above). Otherwise, {@link #setFile setFile} will open File in truncate mode.

Note: Actual opening of the file is made when {@link #activateOptions} is called, not when the options are set. */ public void setAppend(boolean flag) { fileAppend = flag; } /** The BufferedIO option takes a boolean value. It is set to false by default. If true, then File will be opened and the resulting {@link java.io.Writer} wrapped around a {@link BufferedWriter}. BufferedIO will significatnly increase performance on heavily loaded systems. */ public void setBufferedIO(boolean bufferedIO) { this.bufferedIO = bufferedIO; if(bufferedIO) { immediateFlush = false; } } /** Set the size of the IO buffer. */ public void setBufferSize(int bufferSize) { this.bufferSize = bufferSize; } /**

Sets and opens the file where the log output will go. The specified file must be writable.

If there was already an opened file, then the previous file is closed first.

Do not use this method directly. To configure a FileAppender or one of its subclasses, set its properties one by one and then call activateOptions. @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) throws IOException { LogLog.debug("setFile called: "+fileName+", "+append); // It does not make sense to have immediate flush and bufferedIO. if(bufferedIO) { setImmediateFlush(false); } reset(); FileOutputStream ostream = null; try { // // attempt to create file // ostream = new FileOutputStream(fileName, append); } catch(FileNotFoundException ex) { // // if parent directory does not exist then // attempt to create it and try to create file // see bug 9150 // String parentName = new File(fileName).getParent(); if (parentName != null) { File parentDir = new File(parentName); if(!parentDir.exists() && parentDir.mkdirs()) { ostream = new FileOutputStream(fileName, append); } else { throw ex; } } else { throw ex; } } Writer fw = createWriter(ostream); if(bufferedIO) { fw = new BufferedWriter(fw, bufferSize); } this.setQWForFiles(fw); this.fileName = fileName; this.fileAppend = append; this.bufferedIO = bufferedIO; this.bufferSize = bufferSize; writeHeader(); LogLog.debug("setFile ended"); } /** Sets the quiet writer being used. This method is overriden by {@link RollingFileAppender}. */ protected void setQWForFiles(Writer writer) { this.qw = new QuietWriter(writer, errorHandler); } /** Close any previously opened file and call the parent's reset. */ protected void reset() { closeFile(); this.fileName = null; super.reset(); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/chainsaw/0000755000175000017500000000000012126647422023252 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/chainsaw/package.html0000644000175000017500000000702111751454711025533 0ustar tonytony Chainsaw Tool

Chainsaw is a GUI log viewer and filter for the log4j package. By default it listens for LoggingEvent objects sent using the SocketAppender and displays them in a table. The events can be filtered based on:

  • Level
  • Thread name
  • Logger
  • Message
  • NDC

All the details for each event can be displayed by selecting the event in the table.

Chainsaw also supports loading a events logged to a file using the XMLLayout format. This is great for analysing log files, and means you do not need to keep Chainsaw running continously. It is easy to add support for loading events from other sources like JDBC.

A picture is worth a thousand words:

Screen shot of chainsaw.

Finally, why is it called chainsaw? Because it cuts your log (file) down to size. :-)

Requirements

Chainsaw is based on the Swing API which requires JDK 1.2 or later.

Running chainsaw

Setup

You need to include the log4j.jar in the classpath.

Usage

The command line usage is:

  java -D<property>=<value> org.apache.log4j.chainsaw.Main 

The default behaviour of chainsaw can be changed by setting system properties using the -D<property>=<value> arguments to java. The following table describes what properties can be set:

Property Description
chainsaw.port Indicates which port to listen for connections on. Defaults to "4445".

Configuring Log4J

You will need to configure log4j to send logging events to Chainsaw. Here is a sample log4j.properties file for sending logging events to Chainsaw.

log4j.rootLogger=DEBUG, CHAINSAW_CLIENT

log4j.appender.CHAINSAW_CLIENT=org.apache.log4j.net.SocketAppender
log4j.appender.CHAINSAW_CLIENT.RemoteHost=localhost
log4j.appender.CHAINSAW_CLIENT.Port=4445
log4j.appender.CHAINSAW_CLIENT.LocationInfo=true
apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/chainsaw/LoggingReceiver.java0000644000175000017500000001027611751454711027176 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.chainsaw; import java.io.EOFException; import java.io.IOException; import java.io.ObjectInputStream; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; /** * A daemon thread the processes connections from a * org.apache.log4j.net.SocketAppender.html. * * @author Oliver Burn */ class LoggingReceiver extends Thread { /** used to log messages **/ private static final Logger LOG = Logger.getLogger(LoggingReceiver.class); /** * Helper that actually processes a client connection. It receives events * and adds them to the supplied model. * * @author Oliver Burn */ private class Slurper implements Runnable { /** socket connection to read events from **/ private final Socket mClient; /** * Creates a new Slurper instance. * * @param aClient socket to receive events from */ Slurper(Socket aClient) { mClient = aClient; } /** loops getting the events **/ public void run() { LOG.debug("Starting to get data"); try { final ObjectInputStream ois = new ObjectInputStream(mClient.getInputStream()); while (true) { final LoggingEvent event = (LoggingEvent) ois.readObject(); mModel.addEvent(new EventDetails(event)); } } catch (EOFException e) { LOG.info("Reached EOF, closing connection"); } catch (SocketException e) { LOG.info("Caught SocketException, closing connection"); } catch (IOException e) { LOG.warn("Got IOException, closing connection", e); } catch (ClassNotFoundException e) { LOG.warn("Got ClassNotFoundException, closing connection", e); } try { mClient.close(); } catch (IOException e) { LOG.warn("Error closing connection", e); } } } /** where to put the events **/ private MyTableModel mModel; /** server for listening for connections **/ private ServerSocket mSvrSock; /** * Creates a new LoggingReceiver instance. * * @param aModel model to place put received into * @param aPort port to listen on * @throws IOException if an error occurs */ LoggingReceiver(MyTableModel aModel, int aPort) throws IOException { setDaemon(true); mModel = aModel; mSvrSock = new ServerSocket(aPort); } /** Listens for client connections **/ public void run() { LOG.info("Thread started"); try { while (true) { LOG.debug("Waiting for a connection"); final Socket client = mSvrSock.accept(); LOG.debug("Got a connection from " + client.getInetAddress().getHostName()); final Thread t = new Thread(new Slurper(client)); t.setDaemon(true); t.start(); } } catch (IOException e) { LOG.error("Error in accepting connections, stopping.", e); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/chainsaw/MyTableModel.java0000644000175000017500000003026711751454711026443 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.chainsaw; import java.text.DateFormat; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import javax.swing.table.AbstractTableModel; import org.apache.log4j.Priority; import org.apache.log4j.Logger; /** * Represents a list of EventDetails objects that are sorted on * logging time. Methods are provided to filter the events that are visible. * * @author Oliver Burn */ class MyTableModel extends AbstractTableModel { /** used to log messages **/ private static final Logger LOG = Logger.getLogger(MyTableModel.class); /** use the compare logging events **/ private static final Comparator MY_COMP = new Comparator() { /** @see Comparator **/ public int compare(Object aObj1, Object aObj2) { if ((aObj1 == null) && (aObj2 == null)) { return 0; // treat as equal } else if (aObj1 == null) { return -1; // null less than everything } else if (aObj2 == null) { return 1; // think about it. :-> } // will assume only have LoggingEvent final EventDetails le1 = (EventDetails) aObj1; final EventDetails le2 = (EventDetails) aObj2; if (le1.getTimeStamp() < le2.getTimeStamp()) { return 1; } // assume not two events are logged at exactly the same time return -1; } }; /** * Helper that actually processes incoming events. * @author Oliver Burn */ private class Processor implements Runnable { /** loops getting the events **/ public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { // ignore } synchronized (mLock) { if (mPaused) { continue; } boolean toHead = true; // were events added to head boolean needUpdate = false; final Iterator it = mPendingEvents.iterator(); while (it.hasNext()) { final EventDetails event = (EventDetails) it.next(); mAllEvents.add(event); toHead = toHead && (event == mAllEvents.first()); needUpdate = needUpdate || matchFilter(event); } mPendingEvents.clear(); if (needUpdate) { updateFilteredEvents(toHead); } } } } } /** names of the columns in the table **/ private static final String[] COL_NAMES = { "Time", "Priority", "Trace", "Category", "NDC", "Message"}; /** definition of an empty list **/ private static final EventDetails[] EMPTY_LIST = new EventDetails[] {}; /** used to format dates **/ private static final DateFormat DATE_FORMATTER = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM); /** the lock to control access **/ private final Object mLock = new Object(); /** set of all logged events - not filtered **/ private final SortedSet mAllEvents = new TreeSet(MY_COMP); /** events that are visible after filtering **/ private EventDetails[] mFilteredEvents = EMPTY_LIST; /** list of events that are buffered for processing **/ private final List mPendingEvents = new ArrayList(); /** indicates whether event collection is paused to the UI **/ private boolean mPaused = false; /** filter for the thread **/ private String mThreadFilter = ""; /** filter for the message **/ private String mMessageFilter = ""; /** filter for the NDC **/ private String mNDCFilter = ""; /** filter for the category **/ private String mCategoryFilter = ""; /** filter for the priority **/ private Priority mPriorityFilter = Priority.DEBUG; /** * Creates a new MyTableModel instance. * */ MyTableModel() { final Thread t = new Thread(new Processor()); t.setDaemon(true); t.start(); } //////////////////////////////////////////////////////////////////////////// // Table Methods //////////////////////////////////////////////////////////////////////////// /** @see javax.swing.table.TableModel **/ public int getRowCount() { synchronized (mLock) { return mFilteredEvents.length; } } /** @see javax.swing.table.TableModel **/ public int getColumnCount() { // does not need to be synchronized return COL_NAMES.length; } /** @see javax.swing.table.TableModel **/ public String getColumnName(int aCol) { // does not need to be synchronized return COL_NAMES[aCol]; } /** @see javax.swing.table.TableModel **/ public Class getColumnClass(int aCol) { // does not need to be synchronized return (aCol == 2) ? Boolean.class : Object.class; } /** @see javax.swing.table.TableModel **/ public Object getValueAt(int aRow, int aCol) { synchronized (mLock) { final EventDetails event = mFilteredEvents[aRow]; if (aCol == 0) { return DATE_FORMATTER.format(new Date(event.getTimeStamp())); } else if (aCol == 1) { return event.getPriority(); } else if (aCol == 2) { return (event.getThrowableStrRep() == null) ? Boolean.FALSE : Boolean.TRUE; } else if (aCol == 3) { return event.getCategoryName(); } else if (aCol == 4) { return event.getNDC(); } return event.getMessage(); } } //////////////////////////////////////////////////////////////////////////// // Public Methods //////////////////////////////////////////////////////////////////////////// /** * Sets the priority to filter events on. Only events of equal or higher * property are now displayed. * * @param aPriority the priority to filter on */ public void setPriorityFilter(Priority aPriority) { synchronized (mLock) { mPriorityFilter = aPriority; updateFilteredEvents(false); } } /** * Set the filter for the thread field. * * @param aStr the string to match */ public void setThreadFilter(String aStr) { synchronized (mLock) { mThreadFilter = aStr.trim(); updateFilteredEvents(false); } } /** * Set the filter for the message field. * * @param aStr the string to match */ public void setMessageFilter(String aStr) { synchronized (mLock) { mMessageFilter = aStr.trim(); updateFilteredEvents(false); } } /** * Set the filter for the NDC field. * * @param aStr the string to match */ public void setNDCFilter(String aStr) { synchronized (mLock) { mNDCFilter = aStr.trim(); updateFilteredEvents(false); } } /** * Set the filter for the category field. * * @param aStr the string to match */ public void setCategoryFilter(String aStr) { synchronized (mLock) { mCategoryFilter = aStr.trim(); updateFilteredEvents(false); } } /** * Add an event to the list. * * @param aEvent a EventDetails value */ public void addEvent(EventDetails aEvent) { synchronized (mLock) { mPendingEvents.add(aEvent); } } /** * Clear the list of all events. */ public void clear() { synchronized (mLock) { mAllEvents.clear(); mFilteredEvents = new EventDetails[0]; mPendingEvents.clear(); fireTableDataChanged(); } } /** Toggle whether collecting events **/ public void toggle() { synchronized (mLock) { mPaused = !mPaused; } } /** @return whether currently paused collecting events **/ public boolean isPaused() { synchronized (mLock) { return mPaused; } } /** * Get the throwable information at a specified row in the filtered events. * * @param aRow the row index of the event * @return the throwable information */ public EventDetails getEventDetails(int aRow) { synchronized (mLock) { return mFilteredEvents[aRow]; } } //////////////////////////////////////////////////////////////////////////// // Private methods //////////////////////////////////////////////////////////////////////////// /** * Update the filtered events data structure. * @param aInsertedToFront indicates whether events were added to front of * the events. If true, then the current first event must still exist * in the list after the filter is applied. */ private void updateFilteredEvents(boolean aInsertedToFront) { final long start = System.currentTimeMillis(); final List filtered = new ArrayList(); final int size = mAllEvents.size(); final Iterator it = mAllEvents.iterator(); while (it.hasNext()) { final EventDetails event = (EventDetails) it.next(); if (matchFilter(event)) { filtered.add(event); } } final EventDetails lastFirst = (mFilteredEvents.length == 0) ? null : mFilteredEvents[0]; mFilteredEvents = (EventDetails[]) filtered.toArray(EMPTY_LIST); if (aInsertedToFront && (lastFirst != null)) { final int index = filtered.indexOf(lastFirst); if (index < 1) { LOG.warn("In strange state"); fireTableDataChanged(); } else { fireTableRowsInserted(0, index - 1); } } else { fireTableDataChanged(); } final long end = System.currentTimeMillis(); LOG.debug("Total time [ms]: " + (end - start) + " in update, size: " + size); } /** * Returns whether an event matches the filters. * * @param aEvent the event to check for a match * @return whether the event matches */ private boolean matchFilter(EventDetails aEvent) { if (aEvent.getPriority().isGreaterOrEqual(mPriorityFilter) && (aEvent.getThreadName().indexOf(mThreadFilter) >= 0) && (aEvent.getCategoryName().indexOf(mCategoryFilter) >= 0) && ((mNDCFilter.length() == 0) || ((aEvent.getNDC() != null) && (aEvent.getNDC().indexOf(mNDCFilter) >= 0)))) { final String rm = aEvent.getMessage(); if (rm == null) { // only match if we have not filtering in place return (mMessageFilter.length() == 0); } else { return (rm.indexOf(mMessageFilter) >= 0); } } return false; // by default not match } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/chainsaw/ExitAction.java0000644000175000017500000000310211751454711026160 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.chainsaw; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import org.apache.log4j.Logger; /** * Encapsulates the action to exit. * * @author Oliver Burn * @version 1.0 */ class ExitAction extends AbstractAction { /** use to log messages **/ private static final Logger LOG = Logger.getLogger(ExitAction.class); /** The instance to share **/ public static final ExitAction INSTANCE = new ExitAction(); /** Stop people creating instances **/ private ExitAction() {} /** * Will shutdown the application. * @param aIgnore ignored */ public void actionPerformed(ActionEvent aIgnore) { LOG.info("shutting down"); System.exit(0); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/chainsaw/doc-files/0000755000175000017500000000000012126647422025117 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/chainsaw/doc-files/screen_01.png0000644000175000017500000005515611751454710027417 0ustar tonytony‰PNG  IHDRŽvŸ#K pHYsttÞfx IDATxœí?¨,Ç•ÿ't¨P©À$ØÀ†M$P Á8°Á¹¼ÀËÃy81æá`y8x  oƒ6ØÁ‚œì`a^ð…J*tØ¿`fzjªÎ9uªªÿÔô|>|izªëÏ©êêîï­Ûwîîëÿw@!„B¨7}ðþ»¯ÿßaè‰Çß<^¬êê®!„B¡QXU„B!Ô©«ú½ï6­Þxûé÷¾ÿÙo‡û×Û·åíoöÆž~ïíÏÞøÁÓ7Þ~úÆN)çý§oüÀÒ›ï>}ãOßx÷²Þ>;í¿ûôÍwŸÉÛ;mßLöOÛ ·Ï®öxÙ¾•ì¿õÃgoþPßþûã›?|öÖ¿?{ë²ÿøV¸ýw}ûþ¸} ÷ß·ïëÛ…í;ï?¾óáóÓþ‡ï|ø\Þ~$oß÷?zþÞGÏßùèñ½Ëþyû™íQïüǸÿbL|ï“™í'ÏôÉ‹÷>¹Ú?møÉþG?yñ£ŸìÇýÓög¹íÏöülÿ£Ÿ½øàgûNû§~žÛ^ë㟿ºì?y•Ù>‘·?Ùü‹qû*Ùõñ/,}úù«ñêãÏ/ûçí§ýÏ_}úùéöÓÏ_}úŸ_|üù«Oÿó´/lO ÷Oúé/¿øô?¿øô——ýxûËhû—Ëþ¯þrÜþ4Ù?m¥mÿòÓ_ÿå§¿úâ§¿þËOõ—‡_)§ý‡_ÿå§¿Ö·¿ ·_÷~ý—‡ß|uÚþFßþVÞ~6nûÕg¿ýêá·áþyû;aûY¸ë—ýßÿCÜ>÷ÿÕSyû§ÿõÏ~ÿÕÓÿ÷ãíQŸý×eÿ¢?„ÛC²xú‡<ûÃáé®öOÛ—™íQO_^ö/úcnûÇó?~}Þ9<þñëg<<÷ÿôufû§ËöñjÿëÇÿþúñO‡Çÿ÷“íµž‡û·ß$ûß<þYÞ>ÿó×Ïÿç›Ç?ýüNûçí7—}]/¾üæùÿ|óüËË~¼ýò›_~ûüËhÿÛ_~óâ¯ß>ÿò›=í Û¿jÛo÷ÿûí‹¿~óâÇýdû¿úöo§íþ¿Ýÿí»pÿ´ý›¾ýûeûê²ÿÝ«1åïß©Û ÛWáþ?¿{õÏwÆý½úçw¯þOÞ~1îÿßw_\¶ÿºÚý¯Wÿ×»2VUxY`·;m;cÊ0 ÃðÆ÷Ÿ~ïûŸ¶¢ ]é÷ÏNôâJŸŽÞôʉ¦®ôÚ¡¾yåMŸ%~ô¼}7Ù÷é›ï>{3ð¦WNôÝg+}vI9ë­pÿ‡úö‡ãþcàJ/Ûȉ¦®Tp¨G={çâJ?ºRá~øü‹+=&ûº7}ï£çï|øü²ô >\©äMßK\é{]ûÑÓ~ìDírJùÑ'/ÞûäEàJ_œ¶‘M\é>‘\é¯=èeÿ£~ôÇ×~Ôò¦ûqÿäD²÷c©®ôìAvò£Â6ëJ~t¢¯WzÖ/ôí/NûŸ†~4ÜŽô²Þ~~Ùÿ4r¥Ÿ‹~ô‹Ø•~~íGo*mÏô²ÚþtÜœhêJyv¢¡+ýÕµM·¿êW7ýêAÛþ&ãP?ûíW¿ù*ð£_]¶¿MöoúYâJ?ûmàA/ûÉVô£¿ <èïÎN4t¥¿—œhâJŸþ>²¤‡À›ÄíŃþ×µ½é!ð£‡q{ÒKšó¦£}9úÑd«»Ò“ýãÙ‰žS.ʺÒ?]ûÑÿþft¨šnÿ|Ù¹Ò?KNô´xÐ?ó"ô£áöʉ~{µÿå˜òí‹È•~©ûÑ“+ý6Þÿë·ûp?ëJc‡úÝþâM¿ÛkÛ¿eê«¿·ÿÛw7ýî²ý{²ŸxÓÀ‰þëÕ%åìAÿ~íGƒíŃž÷/Û£ ÷£íë}qv¨ÇýÕèÔV5p¥bÊe u[ë©Â6ZC U¼žú˜¬§>6®§¾³­õÔij–­§ ÛÉÖSSÿzóë©_í+k¨%ë©ñjê\YO ÖSÚÖS?»ì5Ýzj°†ªxÖ_O½¸Øózjg ×S…õÔÜJjÇë©Ò¶·õÔo“õÔok×S¿KÖS%çºàzê«¶õÔ`õT]OWU‹þÂéƒ÷?(Í_×J¹U–QÃí™üzê÷ÖS%‡úf¸5ÖSÓµUÿzê»Õë©Wû7}˳žzåP“õÔGk=5ëPõÔtm5·žú^¼_¶žzZCý(ZOM¶Æzê4¬§~Ò°žúã†õÔŸT®§~üóWWû¥ë©?×S?ö¯§>×S¿HÖS3[}=5XCýü y[ºž¯­–¬§þRXO}p®§Êõ«ÏzjΡZë©éÚª=5^[-YOý]Ãzêï ÖSŸ%ûEë©ÏÂõÔ?­§~}µžzN©YOýã×Ézêµ Wú§«õÔçEë©ÿݰžúç†õÔÿiXOý²a=õ²ý®x=Uu¨ß…ë©ù­¹žú*]Oý{Ãzê?‹×SÃUÕÁý§JGËXš¿®•†UÕО*«ª¼«ºùwUgœwUyW•wUyWu+k«¼«Ê»ª÷û®jµUÝé¬dUÍ%Õ!xW5NûéX[ø®j”òÆÛOÃ"£½ª*ø8úÑq?j7ZO½J?ûÑ«”{vþxZO=},yWu,2Õ»ªÇ G?v0zWõ˜8Ừ§ %‡zÚá]UÞUå]UÞUå]UÞUå]ÕWuXܪ†yÒ”«ºÛ=Š  çUÕc‘p=u†7Þ¾¤+©§”` õʪë©çÄÏ «%¾ùîÓaÂõ԰พzJ‰œë¿‰ÎÕõ®ê©ÈDïª^\éõzjä_«§câTïªVõäVÏ)¼«Ê»ª¼«Ê»ª›YOå]UÞUå]Õz«*f󬪆Þ4r®ÅVu´¤é_ýûÇUÕÑkŽ®ôèP£ôѼŽïªŽ/¦ó¼¶¦„ÆôÍΆ¿ß?»ÒgÁÑ+oúfàMß¼ò¦§wUƒ£ÞwUÇ"Ñ»ªÃ5ãzê0®ª÷G¾«zI üèÉG&5®ÿ¼zš6­­žÕUÕãêiZÉ{s~t½ÿÂþÈq=õ¼ÿâ’È»ª¼«Ê»ª¼«Ê»ª¼«Ê»ªý½«ÚbU£EÙ¦F?ª­ªŽGÅUÕpmuWUÏïª?F«­o\­ª&k¨iŠò®êxô¸3¾«zJ÷ê SÊõªªó]ÕS‘ëõÔSâÙ¹?^ÒÏ«ª§ôózê[—µß ß ˆÞU=&ŽÎõ”çýÀ×¾•­­†é§"ú›ï|$zÙ`ÿ£ËþXð¸†zJý+ïªò®ê­­ò®*ïªö³¶Ê»ª¼«:ŸUߨ´ªáêiHèS‡ó»ªÇ”ôo§Ä†ó»ªã~êM¯VUÆ4x‡Õó®ê)ç»ñ kôÀUÙè·ÿÁ»ªq+ŽwU‰ãïúOyÂÓkW:¿ñ¿ä‘\iö]ÕSÎ÷¯VXß vŽ®ôô1ù^ÕKú‡ÒþÅ›žÞU=~ W[CWzJ¹ö¦ï+¬Áïªò®*ïªò®*ïªò®*ïªöþ®j«ªCø@à\#Ÿ:èïªÿöLßU$´wU#ÿ:$‹©—"ï v<¾ŸzDH)ü^ÕS©ëwUǪ®«ºª*\÷®ê11u®Wé «ªãßþ‡1hoDßU=í$xÖq?"zC€wUyWõÞÖSyW•wUûYOå]UÞUÕªNù®ê /¬Fé-爵ö¯ÿêßxW5ZF ÞL}zµ’šì‡õÿfò{ÿðÕK¶æwU‰ãßQò諪á÷\òT½«zÊ­ªž½fôÞªñ=ç Ñê阞~¯ê¥Ôµ7•VU/ß«zNç{UyW•wUyW•wUyW•wU—~WUû[þi­êôß0\ÿU”n¯ªSìwU;Ñ7ªžåwU£ï±J×Véoo©¾™|€ö=W)…ß«zª¹ü]Õ±/Ñ÷ªŽ™ç{WõÒ´ò½ª§Ì¹o­]lähß œëø ã¡ñïý‡dU•ïUå]Õû\[å]UÞUígm•wUïí]ÕR«Z÷eUžµÛiþ¬J|Wµâ{UÇðV¥ïU ¿ùL×ÞU½ì¿Ǫö=BJá÷ª^…ñC!}ü^ÕKŠÃ•^Õðï⻪!ïHéÑ ë:×ä]Uí;ªN)½4|¯j˜rÙ¼iÈÑ}ž÷yW•wUyW•wUyW•wUyWµëwU‹Lg]©2«ª­ª~ïûŸ½±­ÿSUô®jùÿ©zLßUmü?Uß«zq±¹ÿSeüŸU¾Wu멼«Ê»ª¼«Ê»ª¼«z‡ïª>þæÑ©£U-Ê_×Jå¿HMjú®ªìG“íW®ôj=5¿ýh¸=hðª„màJß ¼éµ}–ì{ßU ¿Kõj?ð¦oêp½†zò‹‚C}ŒÞU=hìGÓ­òª†aÿOÕiÉSzWÕð¦Áû©Â»ªÎÿS½«*¼¥Ê»ª¼«Ê»ª¼«Ê»ª¼«Ê»ª³½«úÁû̪ºVŠßU<«è\£ïRýÞ¶ÖV殺®­FcüϪgk«É:kìY£¦µÿYÕÉÚ*ïªò®êý¬­ò®*ïªö³¶Ê»ª÷ð®jÏÊXÕRïªfVUßnX[ýº¶úFvmõ݆µU÷»ªÂö‡òÚêe9ÑÔ• õ1}WU^O5×Vß¹¸Ri=µdmõ²ÿQÍÚêÕoü?zλª¼«Ê»ª¼«Ê»ª¼«Ê»ªË¼«Ú³T«ŠB!„P¬êá5B!„Bk «ŠB!„:V!„Bu*¬*B!„êTXU„B!Ô©°ª!„B¨SaUB!„P§*°ª»kÆ”p!„B¡©TlUÅZ°ª!„Bhr5YUqU5ZyE!„B¨N[ÕÔ³®ÞC„B!t£šø]U¬*B!„šJ³¬ªòB!„j׌/ „B!Ô"ÞUE!„BŠo@!„BŠÿV…B!„:V!„Bu*¬*B!„êTXU„B!Ô©°ª!„B¨SaUB!„P§R­êþå!„B¡Ū*B!„êTXU„B!Ô©°ª!„B¨SaUB!„P§ª´ªOö£*Z-*UÝ B!„ºiÕXÕÐ;VøÈÒ"XU„B¡ûT±U5ŒcºÔ:îG;ÚG»’ìQ„B!´%MfU ‡*ºU±6ÍÕŽ"„B¡)cUÓ/b­°ªžDO%ηcWÿ®Z„B!Ô(¯U5,éÂV5t«¬¤"„BmU·jUÃC¸U„B¡MªÞªš])ïª"„B!CMVõ ü">MÌî+¦FAÃì"„B¡[W«UE!„Bh&aUB!„P§Âª"„B¡N…UE!„B «ŠB!„:V!„Bu*¬*B!„êTXU„B!Ô©°ª­zxò°y­>È!„ µº7XÌ{`U'˜+æ9¼>·!„êDÛ¶‡À{`U§™+«‡AB¡ûѶŸÎaï°ªSŽæ&µù"„B7§m?±ªsæ&µù"„B7§m?±ªsæ&µù"„B7§m?±ªsæ&µù"„B7§m?±ªsæ&µù"„B7§m?±ªsæ&µù"„B7§m?±ªsæ&µù"„B7§m?±ªsæ&µù"„B7§m?±ªsæáõaw–~<$&ŽéQY±ªå;ˆB¡Õµí§óÊVõáÉ>Ô˜î÷«+Ÿt°2ŠVÕÞ3‡ «š­Ó£Ô"öwÛB!t‹šã霵QÎqÖÞ­fUíCÕŽ³+«zÐÝgQf»’:9}jÚA„B­®ù¬êÜEJ{×…Uj´æ¥k)Zåbþ(›€xÈÍôœukUîž°ª!„PoZ̪F ¨¡!ÉZˆIz×£UòG!=ëq=u«TíL{¬ê$“Ã3ɰª!„PoêÁªjE¦í]§ïªÎmUýöüÀ$ó#[ V!„êMK¾«j¬©mÙªŠ)†k´ƒoTž­Á~ý`óVµhº „B¨-ü®j‘½™¶w7cU³•”fvþŠ¿Åªjû¥'¾¨ÎÉ…UE!„zÓ’V•UÕu^8˨ž†ŠÞUÎhšž`O~{ÆÌ*¬*B!Ô›xWue«*îg—Z£œv ‡ÄªÚ 9­êö´ù"„B7§ÅÞUÍ.¦ÎáVùoUsæ&µù"„B7§m?±ªsæ&µù"„B7§m?±ªsæ&µù"„B7§ÅžÎé[ ü© Vu®Ñܤ6ßA„Bèæ´í§3Vu®Ñܤ6ßA„Bèæ´í§3Vu®Ñܤ6ßA„Bèæ´í§3Vu®Ñܤ6ßA„Bèæ´í§3Vu®Ñܤ6ßA„Bèæ´í§3VuâÑ ¬ª"„Bݨø³*¬ª4B!„Ó«ŠU-M€8¼> ÀUŪ–&ÀV«Z6š €UŪ֌&À`U±ª5£ °XU¬jÍh,V«Z3š €UŪ֌&À`U'°ªOö¡Æ”pç¸_ýÞ¨†ÁÊÔŒU€Å˜Üªî”9l•Û}-bUíCæ2*ÞƒUÝívÇíq'ÚhgZ«*:Ô{´ª‘CÖD£t-ÅhB[µõÔi$j5kVU4©¸U˜Š ­ªfISÿåÔb§ò¸ë[UÑS¦ÓiUms©µ’ ÒoUÇi¤í´°¤UÕÖ\íœ7cUmû8‡UµkÐZŒ¶sbU`EV·ªáÇÛ¶ªbJö7õs[Uí­;6¬*ôÀòVUûu¿fj7kU³•LbUz°ªÐ9k­ªŠ¥îѪ.ü€gyÕŽ« ‹±ä7d]é–­ª¸ï_ά°ªb+Q¢ó­ÑªÌÍÂß«š=$/ÜžU½+aU`1øoUXÕšÑX¬*Vµf4`ò?«JéÄ\÷±ªÓŒ&À°ªŠU­M€ÀªbUkF`°ªXÕâÑ ¬ª"„Bݨø³*¬ª4B!„Ó«ŠU-M€8¼> |¯*Vµt4àÿV…U­M€ÀªbUkF`°ªXÕšÑX¬*Vµf4«ŠU­M€ÀªbUkFsdwfÉY»ps°XÕ¼U}x²5¦„;Çý†¯ê·sö0šGB˸¤}ĪÜ íVu—°®•ÒÌÕq¿ÞªjÆ1õ¬åñ]ù]£ž–V¦ÍAò‹‘sV[û鬑SÌ`L‹Àí2•UÕ>ö é­jäPÓ5QOŠVytHl˨S[ñ5ÊŠ5hVuD\müeiN±T¶8Ü4³ZÕt©ÕÞ«j÷¾³[UÑÆÑcUîÓŽÇ(e,åVXÕt¥3<Ô’â·ªÞé}3ŸUÕS«êO\ÓªÚïªNnUE×XÔŠ?ѧmU£”Ý5i~Î(OZ\¬³úz€®˜û€heÔp¥‘íΪŠþ2ûÛö«ÚØÊºV5j~[)æKaU¶Í¬V•:TÍ€¦Åjoê:-©'½®•¹­êàð”C‰­Ì&bUîÉWUÅô¬Uì©QíYUlüU¾ߪFEŒ€ß«š¦ûFÎ!0©šmµ‹Àí²–UÕ\©ÓÔvgUÅ}óÓòG‰ÎVìØìxê¬*À|ÌgUÉ/ñ³f4ªJL\ÁªÞDÏê/ëÉU€Åà¿Umʪr_5eñ&À`U·fU—M€˜ãÚe?‡¹:îcU§M€`U«Z3š €UŪ֌&À`U±ªÅ£yÜ"„B- ¬*VµLëýd÷V«ŠB!Ô©°ªXU„B¡Nõ°õ÷±ª!„B7¬õÞ>Xˆc7±ª­ZýÇ„BÝ•V7?K «Úª¾¬ –âðú0l÷-ÕTXÕVaU`16ýU©°ª­ÂªÀb`U±ªeªÀb`U±ªeªÀb`U±ªeªÀb`U±ªeªÀb`U±ªeªÀb`UW°ªOö¡Æ”pç¸_]yú1mT )W?V«ºšUµy\£QCèwE,ÚYO»XUX ¬jVU[ûŒ¤¥‹5k-z‚<§cU`!°ª=ZÕƒ¾Òé´˜v…þz¤t¬*,VµÓwU­êáüªkµUՃǪÀB`UofUUs·Zåv~¬*ôVõf¬j¶’4« 7 VõƬjÑ;¦šUÕl«¯~¬*,VµS«*îg—ZÓtñ}mÖW?V«Ê«*V«ŠU-V«ŠU-V«ŠU-V«ŠU-V«ŠU-V«ŠU-ÓÓ‡ã!„BhaU±ªeZ÷§+¸7V7?‹ «ÚªÕ´B!„Ð]iu󳤰ª­zà]UXŠÃëÃÀª*VÕ/¬*,ÆïªbU‹„U€ÅÀªbUË„U€ÅÀªbUË„U€ÅÀªbUË„U€ÅÀªbUË„U€ÅÀªbUË„U€ÅÀªf¬êÓ}¨1%Ü9îWÙ¾}X‰˜Ò›°ª°XU—UUL›àY mV@«ZlU#‡­¹FéZŠ˜î,8Iâ!Y›ÆªÀŠ`U[­ªèù Sè·ªÙª²‰Ù˜ubU`°ª¼«ÚhUG[é©Ö^Õš¨pºš°ª°XÕYVU ƒ¨UuP¬ªö«ù¨N#1ëJµ†°ª°.XÕ_H‹héöª­b3Ë«þÔ¬=½n« U]ÿ]UÍbÖyMgb‘©ÅªÀ*`U'°ªâ~v©5-婪:Ñãe}1cU`!°ª÷õߪR#[^V«z_Võ ¬¿–ǪÀB`UïΪ6 « ‹UŪ– « ‹UŪ– « ‹UŪ– « ‹UŪ–éáÉÃq‹B!´€°ªXÕ2­ûÓÜ«›ŸÅ„UE!„B «ŠB!„:UUE!„Bha¹¬*B!„Bk «ŠB!„:•jUWÿF„B!tÏ}©lUW÷Ñ!„Bèn…UE!„B «ŠB!„:V!„BuªJ«úðd©=”I*A!„B›Q“U0ŽÉ+D!„B·®É¬j”2~LW^£CF±B!„ºÍkU ‡*ºÕ´*1B!„º¹¬jú/YÅwUÔ™˜5¦«ÿ_Z„B!4“ʬjdE+iÿfßoUÒ¢,B!„º-jU²žœ¸U„B¡»Ò,Võ˜Ë–Œ !„BhÚƪ¹/æ S<ûÚQ„B!´aµZU„B!„fV!„Bu*¬*B!„êTXU„B!Ô©°ª!„B¨SaUB!„P§Âª"„B¡N…UE!„BªÒªPÈÓ‡µC°è0¼C¨†ù¼ 8-Œ~r!«ººË¾-op«‡qCáuBÕb>oCœG„Z„UíZßà: ¯Ãªóyâ<"Ô"¬j×êü×ax†„Pµ˜ÏÛç¡mÙªî$Žé«»ÿôƒ–vMÌã®Ò"EáA.6b(”ÿ¤ÜÐ%³1m`>§“'¼ÕØ7‡Åîskç±[ mF[¶ª£nwâf½àݜʪ®2þ<œ OJöÝîtëÚÀ|N½¦öS±ññÖgàÎc·Š&Ø6~¶A‘îѪF7Êpf‹wÕ§~U Ók8}D[-[ixvœéÊJ:ì'‚G‚Gö:D4ÔöÇè|9çÛ–\ȬÚÀ|'F´StèµóØ­l«jܯ¹ÛšP÷nUµý´à*S°Úª:ûbäôô½Úªf£ª><<2ÆÐyF´£Îù¶ú•u+ÚÀ|žÊªÞ´6p»U8Á¢É–u-‰ÙÛšP÷nUÅ<ýÌ¿ºwU'¼펷¬ªÙŒXöDðHðÈ9™K­jE"·u[˜ÏÎA³‡nZ8ݪŪ¦GíVÞúTÙÀyìV¥ŽºU›ŠÛšPXU!O´ÎÈåOÏTVUì‹ß£T„—ÿ¨¹4Ô4[öDðHðKÒôŒDSB;;‡’ù–~D©60ŸÅ 6eW¼ýN¨ œÇn•u¨Î§IéÍÓšJwaUoW«ßà&±ªw5bw®¢;5·õ¬˜ÏÛçq“⶘°ª]kÝÜ-.avÒæe/Œ¥V¼1Ÿ·!ÎãfTw»Cªv­Îop†×aHU‹ù¼ qjÑ¢VõØ*RçƒÖax†„Pµ˜ÏÛç¡-gU(dÿr¿v†×aHÕ0Ÿ·ç …ýËýÓ~¬ê¢t~ƒ«Ïù#Ô’!tóypZ­*«ª=Òù ®ÅªÚªgKç#PóypZXÓªîv;ñãøçuÑQ1±´ˆ@¶ˆvÔnÂÌ(xäxƒÓz~4Šš+ê…^Y«Z´ÔÂ#ad’S\Q¤´`uÕ8¯¾É­(Å|ÞœG€V³ªšïí”æ±*ŠdЊ1ÖÖY¹FjU³]vöÂî~QxNôVµ[±ª Sw%NÛ®æó6à<´Ð‹U-²˜ÕE¢{5ÔƒÇóÙjd­ªÓÅz"ïÁªŽ³b«*Úqqâ…‰ÚÏiÎA@#gÔXÖ>ÝÙÒRZYÿøE¢£F³Mø‹”…ö1ÛÁÒ^gÊ|ñ” Xœ­ÀyhA³ªÇé\V5½/g9FNgº}(=jgŽòì²¥Æ\ú8O›6FU #›Ù^)£MŸßQ†êœóD @ºº:µDÛèØ!Ù§Oó=Ù°Ä¢ye ´EÄΡ:/ùºZFR»!`q¶ç Ѫ†nª/«ÚXÄyÈ.RÔ„a¶`d¼<æfHž!bg0Fx¥¤V5 oB«:R4yZŠ—&§ ;EÃüµU„mOçpÙÁd£²›6†B‹Êï/«ãlì&gpZH­jjo&¶ª1¥¢ˆóP‘õ¬Èï/XdUSKjŒŒQ•Ÿ©¬jäS¬ª†vŠEfÔVvz¦<‘‹•8=œÖnÑPxâô_AÙœÝGuÀâlÎ#@ ‘UÝ)LlU+WÆG‘çC7›§¢g[í«ªZsFU~&´ªZ†êl›’<-ÅK ¿’ /¬Á_[]Øb$E‘Û‰öø;ë‡Âg¶§9ÅRXÕ;„óÐB_Vå± E®K,’ây’•SԄߪÚUi‡œƒ6œ-£Œ^⻪b†ê*,BÖªúësúõ×_ÚO£þH*"O»ÐUéå_4tí‰XU8mtgU‡óý=º¡‡ÔIÑ*1\…X[ZƒUÈ´VÕS¤ˆÎ¿W5dñ\ØûÑŽQ§Ó(žÖ–=ZÝ…trŠ}Ñ*ÌõDuAœ“Ùë¥n(Œ =tæÔºi ~Ì,Î6à<´À«êšÎop-Võðú`ÿcÕ…CÊ¢™ gN­¸¿Z¸C:¿€Î#@ XÕ®éüWÞ|“ᶬ*>l:¿€Î#@ XÕ®éü×ax†P óypZXÔªî_îB!„òëáIXU]”}ß?‹w^‡!TÃ|ÞœG€ŽVõðzp «º ßàªÃ³ÿ ê¨º ÓùˆÁ|ÞœG€F«ºyð«º(ßàZ¬ª¡z¶t>bE0Ÿ·ç …5­ªö“Îo|¬+b-b|£Ñ„XöÀ78­×éG£¡ì÷8Vü5ú|VµÃ/«º9&9ÅÕßQÐø… ³â¼ú&o´¢óypZ­jhXõý‰¬ªæ;E;¥y¬Š"Ù´"F †µuV®‘ZÕl—½°»_^XÕ¸«º0uWâ´íúa>oÎ#@ ѪêÓýèJÅý¹¬j‘Ŭ.¥Ø«¡þ<žÏ®P#kU.Öùö¬ªhÇʼn&j?{¤9eœQCbYûtgkHKieýãc‰ŽýÍ6á/R:ÚÇlK{aœ){ðÅS6`q¶ç …ômJ«šÞ—³#§¿ˆ3Ý>”µ3GyvÙRã .}œ§M£*†‘Í쯔¬ªsž¤"ÍlõÔ©%ÚFÇÉ>}šïɆm$Í+c¦-"vÖÕyÉ×…Ô2’Ú ‹³ 8-ˆïªjk«ë[ÕÆ"ÎCv‘¢&ì³#ãå17Còü ó8ƒ1Â+eI«:R4yZŠ—&§ ;EÃüµ5ZU#1E,[áJí¦¡Ð¢òûËê8»‰ÅÙœG€VxWµâ1 ¦¬bUÅ ¥ùý‹¬jjI‘1ªòƒU]تj§x«¶>$ø­ª1K³E¢úýCá‰ÓesVtS»ú°8Û€óРïªÚ7zíqe|ô‰p>t³y*Zq¶Õ¾ªª5gTå«:I¢áW²áþ̶e‰b$E‘Û‰öø;ë‡Âg¶§9ÅRXÕ;„óÐÂ:ïª)² E®K,’ây’•SԄߪÚUi‡œƒ6œ~°ƒ±Ã+¢«wUÓÄARbN£þúK»àiÔIEäi£*½ü‹†®=« ç uÞU=¢Ý¦wgÒ”1½¢HŠV‰á*ÄÚÒzìì¨B¦µªž"EôlUÉ‹çÂÞvŒ:íœFñ´¶ìÑê.¤“Sì‹Vaö¨'ª¨ âœÌ^/uCaTèé 3§ÖMcðÓ`Ž`q¶ç þ[U×t~ƒk±ª‡×û«.RÍL8sjÅýÕÂÒùœpZÀªvMç7¸êðæ› ·eUñ©`ÓùœpZ8ZU¿°ª‹Òù ®Ãð:  æó6à<´°¹xò°¹wªÉªú›A!„Bh¶ªG3éÔžUÕeØ÷ý³x‡áu@5ÌçmÀyh«Ú5ßàªÃ³ÿ ê¨º ÓùˆÁ|ÞœG€°ª]Óù ®ÅªÚªgKç#PóypZXÓªj_0éüÆÇº"FÙ"Æ×1MeÿüxƒÓz~4Ê~cÅ_£ÏgU;ü²ª›c’S\ý_˜0+ΫoòF+J1Ÿ·ç …Õ¬ªæ;E;¥y¬Š"Ù´"F †µuV®‘ZÕl—½°»_^XÕ¸«º0uWâ´íúa>oÎ#@ ½XÕ"‹Y]$J±WCý1x<Ÿ]¡FÖª:]¬'òíYUÑŽ‹/LÔ~öHsÊ9£†Ä²öéÎÖ–ÒÊúÇÇ(5ú›mÂ_¤t(´Ù–öÂ8Söà‹§lÀâlÎ#@ ëXÕô¾œ}ä9ýEœéö¡ô¨9ʳ È–opéãoÎ#@ XÕ®éü×bUí Õ³¥ó(‚ù¼ 8-¬iUµ/˜t~ãc]#€lãë&ŒÀ²~¼Ái½N? e¿Ç±â¯Ñ糪~YÕÍ1É)®þŽ‚Æ/L˜çÕ7y£¥˜ÏÛ`<¥WeøŒó4Tš¿”U®€Õ¬ªæ;E;¥y¬Š"Ù´"F †µuV®‘ZÕl—½°»_^†=†UmçV¬êÂÔ]‰Ó¶ë‡ù¼ ¶aU׺vz±ªE³ºH”b\löo¸CزVÕéb=‘÷`UÇY±ð« µŸ=Òœƒ2€FΨ!±¬}º³5¤¥´²þñ1ŠDGþf›ð) íc¶ƒ¥½0Δ=øâ)°ª[ÁiU³W‡–-MŸjêjd3LÈ:V5½/g9FNgº}(=ê¹hÓ§TzƒKo+Qöhhõ8{¡…WÊèDÓçw”¡:$ç<ÑÐuj‰öÓÂÉ>}éQgØFbѼ2aÚ"bgP—|]H-#©Ý°ªÛÀcUÓÆ%N5uE*žÕܘUm,âSYÕ0æ(CuH“§¥xi¢áWÒ³&žâtk×Vvz¦<‘‹•øŸÁb»ECá‰ÓesVtSÕ«ºœ«ªži£]&žlžIžfH1ÌÁ:Vµô>nô‰z.ÂöVœmµ¯ªjÍUù™ÐªjªC2nâƒcò´/M4üJ6¼°mua‹‘En'Úãï¬G OœÙžVäKùë°ª[¡ôã¨ó6Õ>u5ð©°<]|Y•Ç.¹.±HŠçIVLQ~«jW¥rÚp¶Œv0vxEˆïªŠªCª°Ùg€¿N1§¿Qý¥]ð4ê¤"ò´ Q•^þECמXÑͬê6Xå]Õ–D±r-`nº³ªÃùþ]3!uER´JČ؊VƒUÈ´VÕS¤ˆÎ¿W5dñ\ØûÑŽQ§Ó(žÖ–=ZÝ…trŠ}Ñ*ÌõDuAœ“Ùë¥n(Œ =tæÔºi ~̬ê6XæßuᙺFåF€™à¿UuM窫zx}°ÿ±êÂ!eñßšµ»|cµp‡t~'œG€°ª]Óù ®:¼ù&ÃmYU|*Øt~'œG€°ª]Óù ®Ãð:  æó6à<´°¨UÝ¿Ü#„B!䫪ý²ïûgñÃë0$€j˜ÏÛ€óÐVµk:¿ÁU‡gÿAÕQu¦ó(‚ù¼ 8-`U»¦ó\‹Uµ3TÏ–ÎG  æó6à<´°¦UM¿ÎmÜѾF±½ˆ@¶ˆvÔnÂ,ûàÇœÖëô£Ñý]zv/ìð*Xæ{UïœINqõw4~a¬¬òÅuÍ1Ÿ·ÁxK¯Êðçi¨4?ÀM°šUÕ|§h§4UQ$€VĈÁ°¶ÎÊ5R«ší²³v÷‹Â««º·bU¦îJœ¶]?Ìçm€Uh¡«Zd1«‹D)öj¨?ç«»ƒd­ªÓÅz"ßžUí¸8ñÂDíg4ç   ‘3jH,kŸîl i)­¬|Œ"ÑQ£¿Ù&üEJ‡Bû˜í`i/Œ3e¾xʬêVpZÕìÕ¡eKÓ§šº=°ŽUMïËÙGŽ‘Ó_Ä™nJz®êôFà)•ÞàÒÛJÔ„=Z=Î^hᕲ€UuΓÔ@¤™£ž:µDûia‡dŸ>Í÷dÃ6‹æ•1Ó;k„ê¼äëBjI톀UÝ«êœ6þ+qª© °:7fU‹8ÙEŠš°#ÌŒnps3$÷ 13#¼R–´ª#E“§¥xi¢q ²S4¬Á_[EØöôp—L6*»ic(´¨üþ²:ÎÆnbU·Ax_ÒnËÎ Ðy›jœÏbåk±‚U­»l&)â<ä:Öå÷,²ªÎ{Ÿv¨âÆ„U$Ñc.Çâ)ýÙ±°i#N­6£ ž"Qýþ¡ðÄé¿‚²9+º©]}XÕmà\UõLí2ñdóLò4Àê¬cUKïãöG‘ñ¨çúloÅÙVûªªÖœQ•¬ê$‰†_ɆÖ௭.l1’¢ÈíD{üõˆCá‰3ÛÓŠœb)Vu+”¾`uÞ¦Ú§.@?tñeU»PäºÄ")ž'Yi0EMø­ª]•vÈ9hÃùç;;¼"ºzW5M”!õ×)æô7꯿´ žFý‘TDžv¡1ªÒË¿hèÚ±ª0¬ô®jK¢X9ÀZtgU‡óý=ºfBꊤh•ˆ±­;;ªi­ª§H=[ÕAòßâ¹°÷££N;§Q<­-{´º éäû¢U˜=ê‰*ê‚8'³×KÝPz:èÌ©uÓü4˜#XÕm°Ì7 ¾ëÂ3uµ ° ü·ª®éüAÕbU¯ö?V]8¤,þ{·öi¬îÎïà„óÐVµk:¿ÁU‡7ßd¸-«ŠO›Îïà„óÐVµk:¿Áu^‡!TÃ|ÞœG€µªû—{„B!„übUµ_ö}ÿ,Þax†P óypZÀªvMç7¸êðì?¨:ªnÂt>bE0Ÿ·ç ¬j×t~ƒk±ªv†êÙÒùˆÁ|ÞœG€Ö´ªé×¹;Ú×(¶1È1¾ŽÑhÂ,ûàûäÛøŒÖw×øûUÍ|VµÃ/«º9Š&ª¿’É .ÿ5«|sd]sÌçmÞÉGì‰aÜù'É_ ߺ «°šUÕ|g˜(^ué~Q‘lZ#ÃÚ:+×­ªviíÌaUbUÛ¹«º0ó]þvý0Ÿ·Á6¬êZ×@/VµÈbV‰RŒ‹Í¾à££†åuV¨¡­ªf‡ÎfÂ[ÌäVuœ ÿ·ª0QûÙ#Í9˜'ÂÓXÖøa,ŠßŽÄî{:ÆøE¢£F³Mø‹”…ö1ÛÁÒ^gÊ|ñ” XÕ­à´ªÙ«CË–¦O5u5²&d«šÞ—³#§¿ˆ3Ý>”õ\´éÀSjóV5}~GªCrÎ-í1PQ§–h?-ìŒi u†m$ÚW™3òl¥EÄΡ:/ùºZFR»!`U·Çª:§ÿJœjêŠLøÈrcVµ±ˆó]¤¨ ;ÂlAñŠî8Q„Ñú™ÐªFaOhUGŠ&OKñÒD1–bÔ௭"ìÒçVvžûŸ£F»iNq(´¨üþ²:ÎÆnbU·Ax_Jù=7üÁœáóY¬Üs`V°ªu—Í$Eœ‡üOǺüþ‚öŸUe­‰˜8á]f*«Þ¯£ Õ!5Nž–⥉s9~o¢?›ã1–ž)Oäb%þg°ØnÑPxâÜ]c„”ÍYÑMqT¬êVp®ªz¦v™x²y&yš!Å80ëXÕÒû¸ýÑ_$B<ê¹Û[q¶u?VUËP’Ýñìäi)^šhœÁlxa þÚêÂ#)ŠÜN´ÇßY8ž8³=­È)–ò×9`U·Bé ÆQçmª}êjàSayºø²*]0Ü¡ßmhxŠÔb¿ùÉ~Y•h÷[Z,bÚwUÅ Õ!UX„ì3À_§˜Óߨ¿þÒ.xõGRyڅƨJ/ÿ¢¡kOΰһª-‰båZ"ÀÜtgU‡óý=ºfBꊤh•ˆ±­;;ªÒïUÕêñ·XDçß«švY<ö~´cÔiç4ЧµeVw!œb_´ ³G=QE]'pöz© £BO9µnƒŸs«º –ù€Áw]x¦®Q¹‘`&øoU]ÓùƒªÅª^쬺pHYü·fí.ßX-Ü!ßÀ ç ¬j×t~ƒ«o¾Ép[VŸ 6ßÀ ç ¬j×t~ƒë0¼C¨†ù¼ 8-,jU÷/÷!„BùµœU=¼P‘ö/÷«Çp[áuBÕb>oCû—ûýËB¨VXÕŽÕùƒª:<ûªŽª›0BEb>oCG«ºzÝ¢°ª½«óU‹Uµ_L9έíBEb>oCXU„ªµ²UÝívâÇñkÛ¢£bbi#€lí¨Ý„˜Qð|†öiOµÖ£/½+ŠÚ ÔdU[2LÒöT4Qý•L^pòiéiqŽËaŽn2Ÿ·¡Ñª–^•Æ’ü3i’Ö•ŒÛ­¡ìC¿úÞh4ÚxjJïHëžßŠŽ·¼¦UíTÔñÔ¦ûEE²hEŒ´s`‡í;C‚UÕÂ. £]XÕžu+VuÅaY2H¬ê= «Z]‰ñ˜®h¨Ñ6ÍdU+ÎZ·7ØÉÇüЕU-²˜ÕEüc—ýȨǶï É«ªÙ¡Ëö}unUE[/N¼0QûÙ#ÍiŸOCbY±”¿‰Ý÷t(Œñ1Šh£-‚Ý„¿HéPh³,í…q¦ìÁOÙ«º9­jöêв¥éSMÝ"…ÚFq#c_Âb7±Ò.4ÏðFÅ=c[ÔSñÓè¸1DE‘‹S¥.Îê9¶šUM§‹xªŒq¯+âLÏÎûâÉž9ÿyªV‡äœ'Ú,Ž[]Z¢x ðTeÔ u†m$ÚW™3òl¥EœCaDn—j<éþ‘ÔnXÕmÈcUÓÆ%N5u³Ú©èT”A»´¨ìnú»ST¤ñ榵ngÇJlÚÎY}5-š sìö¬jcç¡ìŒñç·#Ìô¯hi¥trø&Ð XU{äý§¦èz.J4.þì kð×V¶=mœÃe“ªz(´¨ŒÛ}Kâ„ÝĪnC¡UM9æq^€ÎÛTã|+e_ÝþزÅÅC-w­llž{:òwyª*N‡ÿéXç ZǪÖ]6“qò?ëòû ÚV=SÁõf…U$Ñ8ƒéLoéÖ®­:lí–ê.£ ž"ÕCá‰sw=&vΊnjW%Vur®ªz¦v™x²y&yš!:”ö.=¤ÕiwÁhBëröjòÔYZ¤½§Æ)«ẜöI¯èŽÑº]³­Õ¬ª1ÆXhýEŒ ç,2U+ζ°ªÕ!ÙÏNž–⥉ÆôÜeÄ­][]ØÎÁ©nÂs¬ OœÙžVäôwS»*±ªÛPé ÆQçmª}êV¨b¶g/#Úên:jEoû-ã?áùm¼õ9dzâ>Ÿª—/«òØÏ­>ëž"Î`ŠšÈF˜ý²ªÝn—½Ô'¼iᕪ«wU%µV§˜Óߨ¿þÒ.”Eõ2[Û$O5çPˆ¡ˆêÄŠn†ÂªnC«¼«Ú’(Vî—ÿ’/mÅxø–Ž•ÜÒÌö *­M¬9;Ù»‡óüVÜ«³–Öl«G«:v =azE{µ"bÙzì쨮ÏPÙ÷ª3Æ?-üêÙª¤+A<ö~´cÔiç4ЧµeVw!œEã“=ê‰*ê‚8³×KÝP–NÒ3e~Ì!™ÏèvµÌ7|×…gêjÒ©t¶‹aˆ’­Ù½¢±òŸ1³ÿ¦ä©01ç8TtÍßå´;ÙÑÎŽj¶f±Zþ[UïêüAÕbU¯ö?Víí{Uý·TíÒX-ºCu~@Nñߪ4qDYaU{W窆ðö?V=ÿ{ÕŽFl«ÊmÙêü€œÂª†ò,4"4 «Ú»:Pu^‡!!T-æó6t´ª¡Z-hU÷/÷!„BùµœUõüÎBö/÷k‡`Ñax†P óypZÀªvMç7¸êðì?¨:ªnÂt>bE0Ÿ·ç ¬j×t~ƒk±ªv†êÙÒùˆÁ|ÞœG€Ö´ª»ÝNü8þm`tTL,-b-¢µ›03 op»k´ÖwZœÙÖ³ÌgU³4x$ŒMT%“lŸ‡¥8¯¾É­(¥Ý& ¾®ªðÞÛ€³_¥GWïÚHxµæ& fŽà£ú—¿vV³ªšå­•æ·*ŠdЊ1h×­¶ã¦{nÆXU3‡U=F…UmçV¬êÂL{ Ôµë'{h§±æI¬ê$9§²ªSÙ†U]ëÚèŪYÌê"QŠq±Ù|tÔ°¼Î 5îÍªŽ³b«*þ4"N¼0QûÙ#Í9(ãiäŒË?ŒEñÛ‘Ø}O‡Â£HtÔèo¶ ‘Ò¡Ð>f;XÚ ãLÙƒ/ž²¡ð`Ç ¶R˜¸u/:)žØ´¶ºêÚˆÓª²³¥ébxÙq0*7˜›u¬jtm ú™Fœæôq¦Û‡Ò£ž‹6½xJmÞª¦ƒ(CuHÎy¢ =*êÔí§…’}6³³Âé9¯2gäÙ&J‹ˆ5Bu^òu!µŒ¤vCðÜŠb¨˜ÎѰ‹—ž”º1ì­k#«êì²ÿJœjêŠØG¦åƬjcç!»HQv„Ù‚â›jžªŒÆ½” ­jÔµ ­êHÑäi)^šèyÖjéa þÚ*Â.}neçyµÿ°ë‡B‹*û®K%Ü÷7IDAT4Â+-ž}WÕ3íV*:[×/㤤7·l„ž£«wmÄ8¥ }eM5Ÿíîd¯J€iYÁªÖ]6“qÊ^‡Q†Òüþ‚öšŠx¿Ó"´ïŒuLeUÓø±ªbŠvÓ­][uØé™òD.Vâk3Ü?ž8³×ˆ?gE7ÅQÜ¿WqîÛçÎ?bÎIå9)ioÎ#@ G«šýkìÐ?`U—£ó\‹Uµ3TÏ–ÎG  æó6à<´p´ªþüSZUí{éįmÓK‹d‹hGí&ŒÀü7j|¡øybf£`óYÕ¿¬êæ(š¨þJ&/¸ü†¯òÅuÍiw€ ƒ¯«*¼÷¶àìWéÑÕ»6žG­¹I‚™#x€Õ­êÒ/h–K´Všßª(’ @+bÄ Ýì°=7¸0Ýsû3ƪ¬jÏÜŠU]˜i/ºvýdïí4Ö<‰U$çTVuªâ!XU€z±ªE³ºH”b\Ìö5,¯³B ¬j)aHâO#âÄ µŸ=Òœƒ2žFΨ!±¬ñÃX¿‰Ý÷t(Œñ1ŠDGþf›ð) íc¶ƒ¥½0Δ=øâ) ïv b+E‰[gñ¢“â‰Mk««®8­ªÑ);[š.†—£r€YǪFׯ _iÄiNgº}(=깪Ó§Vµ”tÄìy’>ÒÌÆQOZ¢ý´°C²ÏfvVø/=çUæŒ<ÛDi±³F¨ÎK¾.¤–‘Ônž;@Q ³Â9vñÒ“R7†½umÄcU]ö_‰SM]€Õ¹1«ÚXÄyÈ.RÔ„a¶ ø¦š§*ã£qg/å&¬êHÑäi)^šèyÖjéa þÚ*¶g‹s¸ì`êf©g(´¨²éºD#¼ÒâÙwU=Øn¥¢³uý2NJzsËFè9ºz×FŒóXzÚWÖTóÙîÀ¬`Uë.›IŠ8e/Ñ(Ci~A{ME¼ßiÚwÆ:°ª“$zžµãGñ$¦[»¶ê°Ó™æ‰\¬Äÿ Öf¸(=tmĹªê™6ZØÎ˜ý£jt`a"«ºS˜Øªz.È!¹µþ"âQÏõÙÞŠ³­¬Uu†”½ÕÖU$Ñ8#ÙðÂüµÕ…-FR¹h¿³q(ªÓž—[9ËÑl_7€NXÔª¦žÒ¹ïO?šÍÆ9äì²Ö][QO]ÓÓCv Ù¥™>¦M ‰bCbÙÂÚ<­k)vñêñÌöÚ¨³¨Gif#ò–1˜œ¥WUÃ<éÓWÛ÷'ŠDG³ƒ=˜³‰áÖî²³N1§¿¸Ö‘tXüų4²56dät6ä:ícËÈ×?aœç] À_'ÀL¬óÀÿ‰¤¾gƒ‹‹q¶Ìtæ‹uj¥¢¨œç]Ì™usÓõ iÙêDc¡¡îW‘´xu¢Ø´1ø=ª½¢Ù ùyªÖ=¶/ÛÐ$3¤"§˜î7 XUX%¾¬jÕ¶¹L ¥ñŒ¯3»FQ£Ñ~‘ÑF@«3ŠßÙºÖ¯ì~E´<ÕÎdKyÂÖ—Ÿ!u9ÅtÿlñÏ%€™Xâ_¤OèôPº¯¥øs¦!¥jã"V’JìŽؘíD9ýýƒƒÔÒw’M1Š{FÏè»'{èŒ:ÃFµ»däÓ"ZN±õ¨¡!9MžàÅî;{dÄãI/=G3qÿXu'QQɱMÞº˜Ó(Ž]€­r3V5›b”ÝIËZKâ·×bN­8‹[°mnê ¿vÄÌÜ(7cUàÞÀª@§`U S°ªÐ)XUè¬*t V:eb«ºØ—ÒóU©›gúUÕùLdúÈçh:áV­*,Ãb?LÛPEm=üßÝûœá¥ÿ|.ú¸½¡[òŠóüç--Ü"‹ZUñ¹’&fSüùÓx6öT[çpµê´çåVÎr49×  ´áb芇®«±YΪ¦VÒÞ1öýùíM9ŸRE ‰EŒ†üƒžq+ê‹h G›®¨¡ºþÒñœÊª†V;%{Þ «êi±ÚªÚÙ:œÿ° wgU³û}ZÕA²,ÙøµU%±ªÒŽ4ZÕ©,ÝÜõG#S4ÎíÖÕlœcRUXU£-ÿ|³ç¹Ñ´Ïäó–aÑ/«Ú]#&¦eí"Î~¦ùã+/ ©£F×Ät±B ÚøhûQ‘©mÖúÅ¥MÊ8OÛzEY#~±N±GZ¿²¥J[û`t3Û‹4Ý ¬K/ÿ†Ç3Ü3MTæ?À­€U½SxTÃ=Ãü¸°ªw„øÛ[€;ùp‹`U S°ªÐ)XUè¬*t V:« ‚U€NÁª@§`U S°ªÐ)XUè¬*t V:eb«ºË±@—´¶–ŒÚ™ÞªŽ;á~”27Z[XU€b®RSˆU€"V°ªÑ‚kš½0`ï§ù‡ä=1ªlX—¥­ªÇ­î’·¢ÄpÇ“¿"¬Î:/îÐv–‘¯Mëo´ªÐ[°ªZ¶l…!­ SsVµt¿(ô Võ”®… k1‹UM±¥ì$ŒâƒÃݦµùc[€uá«@§`U S°ªÐ)XUè¬*t V:« ‚U€NÁª@§`U S°ªÐ)XUè¬*t V:« Ò‹UÝív»ÝΟ›§«: ƒfI±ª÷ V:ez«:þÊ>úÝ}øQüµ>VBfYU\i˜.îk)v:l›¹¬jѾ–b§À¶Áª@§¬cUyW²ÌõgUá_V‰\•æ 1ÒàNèè˪B°ªÐ)XUè¬*t V:« ‚U€NÁª@§`U S°ªÐ)XUè¬*t V:« ‚U€NÁª@§`U S°ªÐ)XUè¬*t V:« ‚U€NÁª@§LcU[„B!„¦U«U=˜ƒV«ŠB!„Ьª"„B¡NUlUB!„ZLV!„B¡å…UE!„BʲªëüÝÀÕª"„B!Ôƒ°ª!„B¨S]¬êãoB!„êJ¼ÿÁîƒ÷?@!„B¨Cý9îö&r;E]IEND®B`‚apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/chainsaw/Main.java0000644000175000017500000001476611751454711025017 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.chainsaw; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import java.util.Properties; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; /** * The main application. * * @author Oliver Burn */ public class Main extends JFrame { /** the default port number to listen on **/ private static final int DEFAULT_PORT = 4445; /** name of property for port name **/ public static final String PORT_PROP_NAME = "chainsaw.port"; /** use to log messages **/ private static final Logger LOG = Logger.getLogger(Main.class); /** * Creates a new Main instance. */ private Main() { super("CHAINSAW - Log4J Log Viewer"); // create the all important model final MyTableModel model = new MyTableModel(); //Create the menu bar. final JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); final JMenu menu = new JMenu("File"); menuBar.add(menu); try { final LoadXMLAction lxa = new LoadXMLAction(this, model); final JMenuItem loadMenuItem = new JMenuItem("Load file..."); menu.add(loadMenuItem); loadMenuItem.addActionListener(lxa); } catch (NoClassDefFoundError e) { LOG.info("Missing classes for XML parser", e); JOptionPane.showMessageDialog( this, "XML parser not in classpath - unable to load XML events.", "CHAINSAW", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { LOG.info("Unable to create the action to load XML files", e); JOptionPane.showMessageDialog( this, "Unable to create a XML parser - unable to load XML events.", "CHAINSAW", JOptionPane.ERROR_MESSAGE); } final JMenuItem exitMenuItem = new JMenuItem("Exit"); menu.add(exitMenuItem); exitMenuItem.addActionListener(ExitAction.INSTANCE); // Add control panel final ControlPanel cp = new ControlPanel(model); getContentPane().add(cp, BorderLayout.NORTH); // Create the table final JTable table = new JTable(model); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); final JScrollPane scrollPane = new JScrollPane(table); scrollPane.setBorder(BorderFactory.createTitledBorder("Events: ")); scrollPane.setPreferredSize(new Dimension(900, 300)); // Create the details final JPanel details = new DetailPanel(table, model); details.setPreferredSize(new Dimension(900, 300)); // Add the table and stack trace into a splitter final JSplitPane jsp = new JSplitPane(JSplitPane.VERTICAL_SPLIT, scrollPane, details); getContentPane().add(jsp, BorderLayout.CENTER); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent aEvent) { ExitAction.INSTANCE.actionPerformed(null); } }); pack(); setVisible(true); setupReceiver(model); } /** * Setup recieving messages. * * @param aModel a MyTableModel value */ private void setupReceiver(MyTableModel aModel) { int port = DEFAULT_PORT; final String strRep = System.getProperty(PORT_PROP_NAME); if (strRep != null) { try { port = Integer.parseInt(strRep); } catch (NumberFormatException nfe) { LOG.fatal("Unable to parse " + PORT_PROP_NAME + " property with value " + strRep + "."); JOptionPane.showMessageDialog( this, "Unable to parse port number from '" + strRep + "', quitting.", "CHAINSAW", JOptionPane.ERROR_MESSAGE); System.exit(1); } } try { final LoggingReceiver lr = new LoggingReceiver(aModel, port); lr.start(); } catch (IOException e) { LOG.fatal("Unable to connect to socket server, quiting", e); JOptionPane.showMessageDialog( this, "Unable to create socket on port " + port + ", quitting.", "CHAINSAW", JOptionPane.ERROR_MESSAGE); System.exit(1); } } //////////////////////////////////////////////////////////////////////////// // static methods //////////////////////////////////////////////////////////////////////////// /** initialise log4j **/ private static void initLog4J() { final Properties props = new Properties(); props.setProperty("log4j.rootLogger", "DEBUG, A1"); props.setProperty("log4j.appender.A1", "org.apache.log4j.ConsoleAppender"); props.setProperty("log4j.appender.A1.layout", "org.apache.log4j.TTCCLayout"); PropertyConfigurator.configure(props); } /** * The main method. * * @param aArgs ignored */ public static void main(String[] aArgs) { initLog4J(); new Main(); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/chainsaw/ControlPanel.java0000644000175000017500000001741611751454711026526 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.chainsaw; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import org.apache.log4j.Logger; import org.apache.log4j.Priority; import org.apache.log4j.Level; /** * Represents the controls for filtering, pausing, exiting, etc. * * @author Oliver Burn */ class ControlPanel extends JPanel { /** use the log messages **/ private static final Logger LOG = Logger.getLogger(ControlPanel.class); /** * Creates a new ControlPanel instance. * * @param aModel the model to control */ ControlPanel(final MyTableModel aModel) { setBorder(BorderFactory.createTitledBorder("Controls: ")); final GridBagLayout gridbag = new GridBagLayout(); final GridBagConstraints c = new GridBagConstraints(); setLayout(gridbag); // Pad everything c.ipadx = 5; c.ipady = 5; // Add the 1st column of labels c.gridx = 0; c.anchor = GridBagConstraints.EAST; c.gridy = 0; JLabel label = new JLabel("Filter Level:"); gridbag.setConstraints(label, c); add(label); c.gridy++; label = new JLabel("Filter Thread:"); gridbag.setConstraints(label, c); add(label); c.gridy++; label = new JLabel("Filter Logger:"); gridbag.setConstraints(label, c); add(label); c.gridy++; label = new JLabel("Filter NDC:"); gridbag.setConstraints(label, c); add(label); c.gridy++; label = new JLabel("Filter Message:"); gridbag.setConstraints(label, c); add(label); // Add the 2nd column of filters c.weightx = 1; //c.weighty = 1; c.gridx = 1; c.anchor = GridBagConstraints.WEST; c.gridy = 0; final Level[] allPriorities = new Level[] {Level.FATAL, Level.ERROR, Level.WARN, Level.INFO, Level.DEBUG, Level.TRACE }; final JComboBox priorities = new JComboBox(allPriorities); final Level lowest = allPriorities[allPriorities.length - 1]; priorities.setSelectedItem(lowest); aModel.setPriorityFilter(lowest); gridbag.setConstraints(priorities, c); add(priorities); priorities.setEditable(false); priorities.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent aEvent) { aModel.setPriorityFilter( (Priority) priorities.getSelectedItem()); } }); c.fill = GridBagConstraints.HORIZONTAL; c.gridy++; final JTextField threadField = new JTextField(""); threadField.getDocument().addDocumentListener(new DocumentListener () { public void insertUpdate(DocumentEvent aEvent) { aModel.setThreadFilter(threadField.getText()); } public void removeUpdate(DocumentEvent aEvente) { aModel.setThreadFilter(threadField.getText()); } public void changedUpdate(DocumentEvent aEvent) { aModel.setThreadFilter(threadField.getText()); } }); gridbag.setConstraints(threadField, c); add(threadField); c.gridy++; final JTextField catField = new JTextField(""); catField.getDocument().addDocumentListener(new DocumentListener () { public void insertUpdate(DocumentEvent aEvent) { aModel.setCategoryFilter(catField.getText()); } public void removeUpdate(DocumentEvent aEvent) { aModel.setCategoryFilter(catField.getText()); } public void changedUpdate(DocumentEvent aEvent) { aModel.setCategoryFilter(catField.getText()); } }); gridbag.setConstraints(catField, c); add(catField); c.gridy++; final JTextField ndcField = new JTextField(""); ndcField.getDocument().addDocumentListener(new DocumentListener () { public void insertUpdate(DocumentEvent aEvent) { aModel.setNDCFilter(ndcField.getText()); } public void removeUpdate(DocumentEvent aEvent) { aModel.setNDCFilter(ndcField.getText()); } public void changedUpdate(DocumentEvent aEvent) { aModel.setNDCFilter(ndcField.getText()); } }); gridbag.setConstraints(ndcField, c); add(ndcField); c.gridy++; final JTextField msgField = new JTextField(""); msgField.getDocument().addDocumentListener(new DocumentListener () { public void insertUpdate(DocumentEvent aEvent) { aModel.setMessageFilter(msgField.getText()); } public void removeUpdate(DocumentEvent aEvent) { aModel.setMessageFilter(msgField.getText()); } public void changedUpdate(DocumentEvent aEvent) { aModel.setMessageFilter(msgField.getText()); } }); gridbag.setConstraints(msgField, c); add(msgField); // Add the 3rd column of buttons c.weightx = 0; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.EAST; c.gridx = 2; c.gridy = 0; final JButton exitButton = new JButton("Exit"); exitButton.setMnemonic('x'); exitButton.addActionListener(ExitAction.INSTANCE); gridbag.setConstraints(exitButton, c); add(exitButton); c.gridy++; final JButton clearButton = new JButton("Clear"); clearButton.setMnemonic('c'); clearButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent aEvent) { aModel.clear(); } }); gridbag.setConstraints(clearButton, c); add(clearButton); c.gridy++; final JButton toggleButton = new JButton("Pause"); toggleButton.setMnemonic('p'); toggleButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent aEvent) { aModel.toggle(); toggleButton.setText( aModel.isPaused() ? "Resume" : "Pause"); } }); gridbag.setConstraints(toggleButton, c); add(toggleButton); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/chainsaw/DetailPanel.java0000644000175000017500000001303711751454711026303 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.chainsaw; import java.awt.BorderLayout; import java.text.MessageFormat; import java.util.Date; import javax.swing.BorderFactory; import javax.swing.JEditorPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.apache.log4j.Logger; /** * A panel for showing a stack trace. * * @author Oliver Burn */ class DetailPanel extends JPanel implements ListSelectionListener { /** used to log events **/ private static final Logger LOG = Logger.getLogger(DetailPanel.class); /** used to format the logging event **/ private static final MessageFormat FORMATTER = new MessageFormat( "Time: {0,time,medium}" + "  Priority: {1}" + "  Thread: {2}" + "  NDC: {3}" + "
Logger: {4}" + "
Location: {5}" + "
Message:" + "
{6}
" + "Throwable:" + "
{7}
"); /** the model for the data to render **/ private final MyTableModel mModel; /** pane for rendering detail **/ private final JEditorPane mDetails; /** * Creates a new DetailPanel instance. * * @param aTable the table to listen for selections on * @param aModel the model backing the table */ DetailPanel(JTable aTable, final MyTableModel aModel) { mModel = aModel; setLayout(new BorderLayout()); setBorder(BorderFactory.createTitledBorder("Details: ")); mDetails = new JEditorPane(); mDetails.setEditable(false); mDetails.setContentType("text/html"); add(new JScrollPane(mDetails), BorderLayout.CENTER); final ListSelectionModel rowSM = aTable.getSelectionModel(); rowSM.addListSelectionListener(this); } /** @see ListSelectionListener **/ public void valueChanged(ListSelectionEvent aEvent) { //Ignore extra messages. if (aEvent.getValueIsAdjusting()) { return; } final ListSelectionModel lsm = (ListSelectionModel) aEvent.getSource(); if (lsm.isSelectionEmpty()) { mDetails.setText("Nothing selected"); } else { final int selectedRow = lsm.getMinSelectionIndex(); final EventDetails e = mModel.getEventDetails(selectedRow); final Object[] args = { new Date(e.getTimeStamp()), e.getPriority(), escape(e.getThreadName()), escape(e.getNDC()), escape(e.getCategoryName()), escape(e.getLocationDetails()), escape(e.getMessage()), escape(getThrowableStrRep(e)) }; mDetails.setText(FORMATTER.format(args)); mDetails.setCaretPosition(0); } } //////////////////////////////////////////////////////////////////////////// // Private methods //////////////////////////////////////////////////////////////////////////// /** * Returns a string representation of a throwable. * * @param aEvent contains the throwable information * @return a String value */ private static String getThrowableStrRep(EventDetails aEvent) { final String[] strs = aEvent.getThrowableStrRep(); if (strs == null) { return null; } final StringBuffer sb = new StringBuffer(); for (int i = 0; i < strs.length; i++) { sb.append(strs[i]).append("\n"); } return sb.toString(); } /** * Escape <, > & and " as their entities. It is very * dumb about & handling. * @param aStr the String to escape. * @return the escaped String */ private String escape(String aStr) { if (aStr == null) { return null; } final StringBuffer buf = new StringBuffer(); for (int i = 0; i < aStr.length(); i++) { char c = aStr.charAt(i); switch (c) { case '<': buf.append("<"); break; case '>': buf.append(">"); break; case '\"': buf.append("""); break; case '&': buf.append("&"); break; default: buf.append(c); break; } } return buf.toString(); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/chainsaw/XMLFileHandler.java0000644000175000017500000001356511751454711026665 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.chainsaw; import java.util.StringTokenizer; import org.apache.log4j.Level; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * A content handler for document containing Log4J events logged using the * XMLLayout class. It will create events and add them to a supplied model. * * @author Oliver Burn * @version 1.0 */ class XMLFileHandler extends DefaultHandler { /** represents the event tag **/ private static final String TAG_EVENT = "log4j:event"; /** represents the message tag **/ private static final String TAG_MESSAGE = "log4j:message"; /** represents the ndc tag **/ private static final String TAG_NDC = "log4j:NDC"; /** represents the throwable tag **/ private static final String TAG_THROWABLE = "log4j:throwable"; /** represents the location info tag **/ private static final String TAG_LOCATION_INFO = "log4j:locationInfo"; /** where to put the events **/ private final MyTableModel mModel; /** the number of events in the document **/ private int mNumEvents; /** the time of the event **/ private long mTimeStamp; /** the priority (level) of the event **/ private Level mLevel; /** the category of the event **/ private String mCategoryName; /** the NDC for the event **/ private String mNDC; /** the thread for the event **/ private String mThreadName; /** the msg for the event **/ private String mMessage; /** the throwable details the event **/ private String[] mThrowableStrRep; /** the location details for the event **/ private String mLocationDetails; /** buffer for collecting text **/ private final StringBuffer mBuf = new StringBuffer(); /** * Creates a new XMLFileHandler instance. * * @param aModel where to add the events */ XMLFileHandler(MyTableModel aModel) { mModel = aModel; } /** @see DefaultHandler **/ public void startDocument() throws SAXException { mNumEvents = 0; } /** @see DefaultHandler **/ public void characters(char[] aChars, int aStart, int aLength) { mBuf.append(String.valueOf(aChars, aStart, aLength)); } /** @see DefaultHandler **/ public void endElement(String aNamespaceURI, String aLocalName, String aQName) { if (TAG_EVENT.equals(aQName)) { addEvent(); resetData(); } else if (TAG_NDC.equals(aQName)) { mNDC = mBuf.toString(); } else if (TAG_MESSAGE.equals(aQName)) { mMessage = mBuf.toString(); } else if (TAG_THROWABLE.equals(aQName)) { final StringTokenizer st = new StringTokenizer(mBuf.toString(), "\n\t"); mThrowableStrRep = new String[st.countTokens()]; if (mThrowableStrRep.length > 0) { mThrowableStrRep[0] = st.nextToken(); for (int i = 1; i < mThrowableStrRep.length; i++) { mThrowableStrRep[i] = "\t" + st.nextToken(); } } } } /** @see DefaultHandler **/ public void startElement(String aNamespaceURI, String aLocalName, String aQName, Attributes aAtts) { mBuf.setLength(0); if (TAG_EVENT.equals(aQName)) { mThreadName = aAtts.getValue("thread"); mTimeStamp = Long.parseLong(aAtts.getValue("timestamp")); mCategoryName = aAtts.getValue("logger"); mLevel = Level.toLevel(aAtts.getValue("level")); } else if (TAG_LOCATION_INFO.equals(aQName)) { mLocationDetails = aAtts.getValue("class") + "." + aAtts.getValue("method") + "(" + aAtts.getValue("file") + ":" + aAtts.getValue("line") + ")"; } } /** @return the number of events in the document **/ int getNumEvents() { return mNumEvents; } //////////////////////////////////////////////////////////////////////////// // Private methods //////////////////////////////////////////////////////////////////////////// /** Add an event to the model **/ private void addEvent() { mModel.addEvent(new EventDetails(mTimeStamp, mLevel, mCategoryName, mNDC, mThreadName, mMessage, mThrowableStrRep, mLocationDetails)); mNumEvents++; } /** Reset the data for an event **/ private void resetData() { mTimeStamp = 0; mLevel = null; mCategoryName = null; mNDC = null; mThreadName = null; mMessage = null; mThrowableStrRep = null; mLocationDetails = null; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/chainsaw/LoadXMLAction.java0000644000175000017500000001152511751454711026517 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.chainsaw; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import java.io.StringReader; import javax.swing.AbstractAction; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import org.apache.log4j.Logger; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /** * Encapsulates the action to load an XML file. * * @author Oliver Burn * @version 1.0 */ class LoadXMLAction extends AbstractAction { /** use to log messages **/ private static final Logger LOG = Logger.getLogger(LoadXMLAction.class); /** the parent frame **/ private final JFrame mParent; /** * the file chooser - configured to allow only the selection of a * single file. */ private final JFileChooser mChooser = new JFileChooser(); { mChooser.setMultiSelectionEnabled(false); mChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); } /** parser to read XML files **/ private final XMLReader mParser; /** the content handler **/ private final XMLFileHandler mHandler; /** * Creates a new LoadXMLAction instance. * * @param aParent the parent frame * @param aModel the model to add events to * @exception SAXException if an error occurs * @throws ParserConfigurationException if an error occurs */ LoadXMLAction(JFrame aParent, MyTableModel aModel) throws SAXException, ParserConfigurationException { mParent = aParent; mHandler = new XMLFileHandler(aModel); mParser = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); mParser.setContentHandler(mHandler); } /** * Prompts the user for a file to load events from. * @param aIgnore an ActionEvent value */ public void actionPerformed(ActionEvent aIgnore) { LOG.info("load file called"); if (mChooser.showOpenDialog(mParent) == JFileChooser.APPROVE_OPTION) { LOG.info("Need to load a file"); final File chosen = mChooser.getSelectedFile(); LOG.info("loading the contents of " + chosen.getAbsolutePath()); try { final int num = loadFile(chosen.getAbsolutePath()); JOptionPane.showMessageDialog( mParent, "Loaded " + num + " events.", "CHAINSAW", JOptionPane.INFORMATION_MESSAGE); } catch (Exception e) { LOG.warn("caught an exception loading the file", e); JOptionPane.showMessageDialog( mParent, "Error parsing file - " + e.getMessage(), "CHAINSAW", JOptionPane.ERROR_MESSAGE); } } } /** * Loads the contents of file into the model * * @param aFile the file to extract events from * @return the number of events loaded * @throws SAXException if an error occurs * @throws IOException if an error occurs */ private int loadFile(String aFile) throws SAXException, IOException { synchronized (mParser) { // Create a dummy document to parse the file final StringBuffer buf = new StringBuffer(); buf.append("\n"); buf.append("]>\n"); buf.append("\n"); buf.append("&data;\n"); buf.append("\n"); final InputSource is = new InputSource(new StringReader(buf.toString())); mParser.parse(is); return mHandler.getNumEvents(); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/chainsaw/EventDetails.java0000644000175000017500000001014511751454711026505 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.chainsaw; import org.apache.log4j.Priority; import org.apache.log4j.spi.LoggingEvent; /** * Represents the details of a logging event. It is intended to overcome the * problem that a LoggingEvent cannot be constructed with purely fake data. * * @author Oliver Burn * @version 1.0 */ class EventDetails { /** the time of the event **/ private final long mTimeStamp; /** the priority of the event **/ private final Priority mPriority; /** the category of the event **/ private final String mCategoryName; /** the NDC for the event **/ private final String mNDC; /** the thread for the event **/ private final String mThreadName; /** the msg for the event **/ private final String mMessage; /** the throwable details the event **/ private final String[] mThrowableStrRep; /** the location details for the event **/ private final String mLocationDetails; /** * Creates a new EventDetails instance. * @param aTimeStamp a long value * @param aPriority a Priority value * @param aCategoryName a String value * @param aNDC a String value * @param aThreadName a String value * @param aMessage a String value * @param aThrowableStrRep a String[] value * @param aLocationDetails a String value */ EventDetails(long aTimeStamp, Priority aPriority, String aCategoryName, String aNDC, String aThreadName, String aMessage, String[] aThrowableStrRep, String aLocationDetails) { mTimeStamp = aTimeStamp; mPriority = aPriority; mCategoryName = aCategoryName; mNDC = aNDC; mThreadName = aThreadName; mMessage = aMessage; mThrowableStrRep = aThrowableStrRep; mLocationDetails = aLocationDetails; } /** * Creates a new EventDetails instance. * * @param aEvent a LoggingEvent value */ EventDetails(LoggingEvent aEvent) { this(aEvent.timeStamp, aEvent.getLevel(), aEvent.getLoggerName(), aEvent.getNDC(), aEvent.getThreadName(), aEvent.getRenderedMessage(), aEvent.getThrowableStrRep(), (aEvent.getLocationInformation() == null) ? null : aEvent.getLocationInformation().fullInfo); } /** @see #mTimeStamp **/ long getTimeStamp() { return mTimeStamp; } /** @see #mPriority **/ Priority getPriority() { return mPriority; } /** @see #mCategoryName **/ String getCategoryName() { return mCategoryName; } /** @see #mNDC **/ String getNDC() { return mNDC; } /** @see #mThreadName **/ String getThreadName() { return mThreadName; } /** @see #mMessage **/ String getMessage() { return mMessage; } /** @see #mLocationDetails **/ String getLocationDetails(){ return mLocationDetails; } /** @see #mThrowableStrRep **/ String[] getThrowableStrRep() { return mThrowableStrRep; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/CategoryKey.java0000644000175000017500000000263411751454711024553 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; /** CategoryKey is a wrapper for String that apparently accellerated hash table lookup in early JVM's. @author Ceki Gülcü */ class CategoryKey { String name; int hashCache; CategoryKey(String name) { this.name = name; hashCache = name.hashCode(); } final public int hashCode() { return hashCache; } final public boolean equals(Object rArg) { if(this == rArg) return true; if(rArg != null && CategoryKey.class == rArg.getClass()) return name.equals(((CategoryKey)rArg ).name); else return false; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/config/0000755000175000017500000000000012126647422022722 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/config/package.html0000644000175000017500000000153611751454711025210 0ustar tonytony Package used in getting/setting component properties. apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/config/PropertyGetter.java0000644000175000017500000000721711751454711026573 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.config; import org.apache.log4j.Priority; import org.apache.log4j.helpers.LogLog; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.InterruptedIOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** 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 { BeanInfo bi = Introspector.getBeanInfo(obj.getClass()); props = bi.getPropertyDescriptors(); this.obj = obj; } public static void getProperties(Object obj, PropertyCallback callback, String prefix) { try { new PropertyGetter(obj).getProperties(callback, prefix); } catch (IntrospectionException ex) { LogLog.error("Failed to introspect object " + obj, ex); } } public void getProperties(PropertyCallback callback, String prefix) { for (int i = 0; i < props.length; i++) { Method getter = props[i].getReadMethod(); if (getter == null) continue; if (!isHandledType(getter.getReturnType())) { //System.err.println("Ignoring " + props[i].getName() +" " + getter.getReturnType()); continue; } String name = props[i].getName(); try { Object result = getter.invoke(obj, NULL_ARG); //System.err.println("PROP " + name +": " + result); if (result != null) { callback.foundProperty(obj, prefix, name, result); } } catch (IllegalAccessException ex) { LogLog.warn("Failed to get value of property " + name); } catch (InvocationTargetException ex) { if (ex.getTargetException() instanceof InterruptedException || ex.getTargetException() instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.warn("Failed to get value of property " + name); } catch (RuntimeException ex) { LogLog.warn("Failed to get value of property " + name); } } } protected boolean isHandledType(Class type) { return String.class.isAssignableFrom(type) || Integer.TYPE.isAssignableFrom(type) || Long.TYPE.isAssignableFrom(type) || Boolean.TYPE.isAssignableFrom(type) || Priority.class.isAssignableFrom(type); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/config/PropertySetter.java0000644000175000017500000002446211751454711026610 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Contributors: Georg Lundesgaard package org.apache.log4j.config; import org.apache.log4j.Appender; import org.apache.log4j.Level; import org.apache.log4j.Priority; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.helpers.OptionConverter; import org.apache.log4j.spi.OptionHandler; import org.apache.log4j.spi.ErrorHandler; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.InterruptedIOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Enumeration; import java.util.Properties; /** General purpose Object property setter. Clients repeatedly invokes {@link #setProperty setProperty(name,value)} in order to invoke setters on the Object specified in the constructor. This class relies on the JavaBeans {@link Introspector} to analyze the given Object Class using reflection.

Usage:

     PropertySetter ps = new PropertySetter(anObject);
     ps.set("name", "Joe");
     ps.set("age", "32");
     ps.set("isMale", "true");
   
will cause the invocations anObject.setName("Joe"), anObject.setAge(32), and setMale(true) if such methods exist with those signatures. Otherwise an {@link IntrospectionException} are thrown. @author Anders Kristensen @since 1.1 */ public class PropertySetter { protected Object obj; protected PropertyDescriptor[] props; /** Create a new PropertySetter for the specified Object. This is done in prepartion for invoking {@link #setProperty} one or more times. @param obj the object for which to set properties */ public PropertySetter(Object obj) { this.obj = obj; } /** Uses JavaBeans {@link Introspector} to computer setters of object to be configured. */ protected void introspect() { try { BeanInfo bi = Introspector.getBeanInfo(obj.getClass()); props = bi.getPropertyDescriptors(); } catch (IntrospectionException ex) { LogLog.error("Failed to introspect "+obj+": " + ex.getMessage()); props = new PropertyDescriptor[0]; } } /** Set the properties of an object passed as a parameter in one go. The properties are parsed relative to a prefix. @param obj The object to configure. @param properties A java.util.Properties containing keys and values. @param prefix Only keys having the specified prefix will be set. */ public static void setProperties(Object obj, Properties properties, String prefix) { new PropertySetter(obj).setProperties(properties, prefix); } /** Set the properites for the object that match the prefix passed as parameter. */ public void setProperties(Properties properties, String prefix) { int len = prefix.length(); for (Enumeration e = properties.propertyNames(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); // handle only properties that start with the desired frefix. if (key.startsWith(prefix)) { // ignore key if it contains dots after the prefix if (key.indexOf('.', len + 1) > 0) { //System.err.println("----------Ignoring---["+key // +"], prefix=["+prefix+"]."); continue; } String value = OptionConverter.findAndSubst(key, properties); key = key.substring(len); if (("layout".equals(key) || "errorhandler".equals(key)) && obj instanceof Appender) { continue; } // // if the property type is an OptionHandler // (for example, triggeringPolicy of org.apache.log4j.rolling.RollingFileAppender) PropertyDescriptor prop = getPropertyDescriptor(Introspector.decapitalize(key)); if (prop != null && OptionHandler.class.isAssignableFrom(prop.getPropertyType()) && prop.getWriteMethod() != null) { OptionHandler opt = (OptionHandler) OptionConverter.instantiateByKey(properties, prefix + key, prop.getPropertyType(), null); PropertySetter setter = new PropertySetter(opt); setter.setProperties(properties, prefix + key + "."); try { prop.getWriteMethod().invoke(this.obj, new Object[] { opt }); } catch(IllegalAccessException ex) { LogLog.warn("Failed to set property [" + key + "] to value \"" + value + "\". ", ex); } catch(InvocationTargetException ex) { if (ex.getTargetException() instanceof InterruptedException || ex.getTargetException() instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.warn("Failed to set property [" + key + "] to value \"" + value + "\". ", ex); } catch(RuntimeException ex) { LogLog.warn("Failed to set property [" + key + "] to value \"" + value + "\". ", ex); } continue; } setProperty(key, value); } } activate(); } /** Set a property on this PropertySetter's Object. If successful, this method will invoke a setter method on the underlying Object. The setter is the one for the specified property name and the value is determined partly from the setter argument type and partly from the value specified in the call to this method.

If the setter expects a String no conversion is necessary. If it expects an int, then an attempt is made to convert 'value' to an int using new Integer(value). If the setter expects a boolean, the conversion is by new Boolean(value). @param name name of the property @param value String value of the property */ public void setProperty(String name, String value) { if (value == null) return; name = Introspector.decapitalize(name); PropertyDescriptor prop = getPropertyDescriptor(name); //LogLog.debug("---------Key: "+name+", type="+prop.getPropertyType()); if (prop == null) { LogLog.warn("No such property [" + name + "] in "+ obj.getClass().getName()+"." ); } else { try { setProperty(prop, name, value); } catch (PropertySetterException ex) { LogLog.warn("Failed to set property [" + name + "] to value \"" + value + "\". ", ex.rootCause); } } } /** Set the named property given a {@link PropertyDescriptor}. @param prop A PropertyDescriptor describing the characteristics of the property to set. @param name The named of the property to set. @param value The value of the property. */ public void setProperty(PropertyDescriptor prop, String name, String value) throws PropertySetterException { Method setter = prop.getWriteMethod(); if (setter == null) { throw new PropertySetterException("No setter for property ["+name+"]."); } Class[] paramTypes = setter.getParameterTypes(); if (paramTypes.length != 1) { throw new PropertySetterException("#params for setter != 1"); } Object arg; try { arg = convertArg(value, paramTypes[0]); } catch (Throwable t) { throw new PropertySetterException("Conversion to type ["+paramTypes[0]+ "] failed. Reason: "+t); } if (arg == null) { throw new PropertySetterException( "Conversion to type ["+paramTypes[0]+"] failed."); } LogLog.debug("Setting property [" + name + "] to [" +arg+"]."); try { setter.invoke(obj, new Object[] { arg }); } catch (IllegalAccessException ex) { throw new PropertySetterException(ex); } catch (InvocationTargetException ex) { if (ex.getTargetException() instanceof InterruptedException || ex.getTargetException() instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } throw new PropertySetterException(ex); } catch (RuntimeException ex) { throw new PropertySetterException(ex); } } /** Convert val a String parameter to an object of a given type. */ protected Object convertArg(String val, Class type) { if(val == null) return null; String v = val.trim(); if (String.class.isAssignableFrom(type)) { return val; } else if (Integer.TYPE.isAssignableFrom(type)) { return new Integer(v); } else if (Long.TYPE.isAssignableFrom(type)) { return new Long(v); } else if (Boolean.TYPE.isAssignableFrom(type)) { if ("true".equalsIgnoreCase(v)) { return Boolean.TRUE; } else if ("false".equalsIgnoreCase(v)) { return Boolean.FALSE; } } else if (Priority.class.isAssignableFrom(type)) { return OptionConverter.toLevel(v, (Level) Level.DEBUG); } else if (ErrorHandler.class.isAssignableFrom(type)) { return OptionConverter.instantiateByClassName(v, ErrorHandler.class, null); } return null; } protected PropertyDescriptor getPropertyDescriptor(String name) { if (props == null) introspect(); for (int i = 0; i < props.length; i++) { if (name.equals(props[i].getName())) { return props[i]; } } return null; } public void activate() { if (obj instanceof OptionHandler) { ((OptionHandler) obj).activateOptions(); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/config/PropertyPrinter.java0000644000175000017500000001177711751454711026772 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.config; import org.apache.log4j.Appender; import org.apache.log4j.Category; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import java.io.PrintWriter; import java.util.Enumeration; import java.util.Hashtable; /** Prints the configuration of the log4j default hierarchy (which needs to be auto-initialized) as a propoperties file on a {@link PrintWriter}. @author Anders Kristensen */ public class PropertyPrinter implements PropertyGetter.PropertyCallback { protected int numAppenders = 0; protected Hashtable appenderNames = new Hashtable(); protected Hashtable layoutNames = new Hashtable(); protected PrintWriter out; protected boolean doCapitalize; public PropertyPrinter(PrintWriter out) { this(out, false); } public PropertyPrinter(PrintWriter out, boolean doCapitalize) { this.out = out; this.doCapitalize = doCapitalize; print(out); out.flush(); } protected String genAppName() { return "A" + numAppenders++; } /** * Returns true if the specified appender name is considered to have * been generated, that is, if it is of the form A[0-9]+. */ protected boolean isGenAppName(String name) { if (name.length() < 2 || name.charAt(0) != 'A') return false; for (int i = 0; i < name.length(); i++) { if (name.charAt(i) < '0' || name.charAt(i) > '9') return false; } return true; } /** * Prints the configuration of the default log4j hierarchy as a Java * properties file on the specified Writer. * *

N.B. print() can be invoked only once! */ public void print(PrintWriter out) { printOptions(out, Logger.getRootLogger()); Enumeration cats = LogManager.getCurrentLoggers(); while (cats.hasMoreElements()) { printOptions(out, (Logger) cats.nextElement()); } } /** * @since 1.2.15 */ protected void printOptions(PrintWriter out, Category cat) { Enumeration appenders = cat.getAllAppenders(); Level prio = cat.getLevel(); String appenderString = (prio == null ? "" : prio.toString()); while (appenders.hasMoreElements()) { Appender app = (Appender) appenders.nextElement(); String name; if ((name = (String) appenderNames.get(app)) == null) { // first assign name to the appender if ((name = app.getName()) == null || isGenAppName(name)) { name = genAppName(); } appenderNames.put(app, name); printOptions(out, app, "log4j.appender."+name); if (app.getLayout() != null) { printOptions(out, app.getLayout(), "log4j.appender."+name+".layout"); } } appenderString += ", " + name; } String catKey = (cat == Logger.getRootLogger()) ? "log4j.rootLogger" : "log4j.logger." + cat.getName(); if (appenderString != "") { out.println(catKey + "=" + appenderString); } if (!cat.getAdditivity() && cat != Logger.getRootLogger()) { out.println("log4j.additivity." + cat.getName() + "=false"); } } protected void printOptions(PrintWriter out, Logger cat) { printOptions(out, (Category) cat); } protected void printOptions(PrintWriter out, Object obj, String fullname) { out.println(fullname + "=" + obj.getClass().getName()); PropertyGetter.getProperties(obj, this, fullname + "."); } public void foundProperty(Object obj, String prefix, String name, Object value) { // XXX: Properties encode value.toString() if (obj instanceof Appender && "name".equals(name)) { return; } if (doCapitalize) { name = capitalize(name); } out.println(prefix + name + "=" + value.toString()); } public static String capitalize(String name) { if (Character.isLowerCase(name.charAt(0))) { if (name.length() == 1 || Character.isLowerCase(name.charAt(1))) { StringBuffer newname = new StringBuffer(name); newname.setCharAt(0, Character.toUpperCase(name.charAt(0))); return newname.toString(); } } return name; } // for testing public static void main(String[] args) { new PropertyPrinter(new PrintWriter(System.out)); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/config/PropertySetterException.java0000644000175000017500000000312411751454711030457 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.config; /** * Thrown when an error is encountered whilst attempting to set a property * using the {@link PropertySetter} utility class. * * @author Anders Kristensen * @since 1.1 */ public class PropertySetterException extends Exception { private static final long serialVersionUID = -1352613734254235861L; protected Throwable rootCause; public PropertySetterException(String msg) { super(msg); } public PropertySetterException(Throwable rootCause) { super(); this.rootCause = rootCause; } /** Returns descriptive text on the cause of this exception. */ public String getMessage() { String msg = super.getMessage(); if (msg == null && rootCause != null) { msg = rootCause.getMessage(); } return msg; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/0000755000175000017500000000000012126647422023117 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/package.html0000644000175000017500000000201311751454707025401 0ustar tonytony

This package is used internally.


Last modified: Sat Jul 3 15:12:58 MDT 1999 apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/SyslogQuietWriter.java0000644000175000017500000000302711751454707027456 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import java.io.Writer; import org.apache.log4j.spi.ErrorHandler; /** SyslogQuietWriter extends QuietWriter by prepending the syslog level code before each printed String. @since 0.7.3 */ public class SyslogQuietWriter extends QuietWriter { int syslogFacility; int level; public SyslogQuietWriter(Writer writer, int syslogFacility, ErrorHandler eh) { super(writer, eh); this.syslogFacility = syslogFacility; } public void setLevel(int level) { this.level = level; } public void setSyslogFacility(int syslogFacility) { this.syslogFacility = syslogFacility; } public void write(String string) { super.write("<"+(syslogFacility | level)+">" + string); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/SyslogWriter.java0000644000175000017500000001012611751454707026444 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import java.io.Writer; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.DatagramPacket; import java.net.UnknownHostException; import java.net.SocketException; import java.io.IOException; import java.net.URL; import java.net.MalformedURLException; /** SyslogWriter is a wrapper around the java.net.DatagramSocket class so that it behaves like a java.io.Writer. @since 0.7.3 */ public class SyslogWriter extends Writer { final int SYSLOG_PORT = 514; /** * Host string from last constructed SyslogWriter. * @deprecated */ static String syslogHost; private InetAddress address; private final int port; private DatagramSocket ds; /** * Constructs a new instance of SyslogWriter. * @param syslogHost host name, may not be null. A port * may be specified by following the name or IPv4 literal address with * a colon and a decimal port number. To specify a port with an IPv6 * address, enclose the IPv6 address in square brackets before appending * the colon and decimal port number. */ public SyslogWriter(final String syslogHost) { SyslogWriter.syslogHost = syslogHost; if (syslogHost == null) { throw new NullPointerException("syslogHost"); } String host = syslogHost; int urlPort = -1; // // If not an unbracketed IPv6 address then // parse as a URL // if (host.indexOf("[") != -1 || host.indexOf(':') == host.lastIndexOf(':')) { try { URL url = new URL("http://" + host); if (url.getHost() != null) { host = url.getHost(); // if host is a IPv6 literal, strip off the brackets if(host.startsWith("[") && host.charAt(host.length() - 1) == ']') { host = host.substring(1, host.length() - 1); } urlPort = url.getPort(); } } catch(MalformedURLException e) { LogLog.error("Malformed URL: will attempt to interpret as InetAddress.", e); } } if (urlPort == -1) { urlPort = SYSLOG_PORT; } port = urlPort; try { this.address = InetAddress.getByName(host); } catch (UnknownHostException e) { LogLog.error("Could not find " + host + ". All logging will FAIL.", e); } try { this.ds = new DatagramSocket(); } catch (SocketException e) { e.printStackTrace(); LogLog.error("Could not instantiate DatagramSocket to " + host + ". All logging will FAIL.", e); } } public void write(char[] buf, int off, int len) throws IOException { this.write(new String(buf, off, len)); } public void write(final String string) throws IOException { if(this.ds != null && this.address != null) { byte[] bytes = string.getBytes(); // // syslog packets must be less than 1024 bytes // int bytesLength = bytes.length; if (bytesLength >= 1024) { bytesLength = 1024; } DatagramPacket packet = new DatagramPacket(bytes, bytesLength, address, port); ds.send(packet); } } public void flush() {} public void close() { if (ds != null) { ds.close(); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/RelativeTimeDateFormat.java0000644000175000017500000000370411751454707030334 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import java.util.Date; import java.text.FieldPosition; import java.text.ParsePosition; import java.text.DateFormat; /** Formats a {@link Date} by printing the number of milliseconds elapsed since construction of the format. This is the fastest printing DateFormat in the package. @author Ceki Gülcü @since 0.7.5 */ public class RelativeTimeDateFormat extends DateFormat { private static final long serialVersionUID = 7055751607085611984L; protected final long startTime; public RelativeTimeDateFormat() { this.startTime = System.currentTimeMillis(); } /** Appends to sbuf the number of milliseconds elapsed since the start of the application. @since 0.7.5 */ public StringBuffer format(Date date, StringBuffer sbuf, FieldPosition fieldPosition) { //System.err.println(":"+ date.getTime() + " - " + startTime); return sbuf.append((date.getTime() - startTime)); } /** This method does not do anything but return null. */ public Date parse(java.lang.String s, ParsePosition pos) { return null; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/DateTimeDateFormat.java0000644000175000017500000000457311751454707027443 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import java.util.Calendar; import java.util.TimeZone; import java.util.Date; import java.text.FieldPosition; import java.text.ParsePosition; 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". @author Ceki Gülcü @since 0.7.5 */ public class DateTimeDateFormat extends AbsoluteTimeDateFormat { private static final long serialVersionUID = 5547637772208514971L; String[] shortMonths; public DateTimeDateFormat() { super(); shortMonths = new DateFormatSymbols().getShortMonths(); } public DateTimeDateFormat(TimeZone timeZone) { this(); setCalendar(Calendar.getInstance(timeZone)); } /** Appends to sbuf the date in the format "dd MMM yyyy HH:mm:ss,SSS" for example, "06 Nov 1994 08:49:37,459". @param sbuf the string buffer to write to */ public StringBuffer format(Date date, StringBuffer sbuf, FieldPosition fieldPosition) { calendar.setTime(date); int day = calendar.get(Calendar.DAY_OF_MONTH); if(day < 10) sbuf.append('0'); sbuf.append(day); sbuf.append(' '); sbuf.append(shortMonths[calendar.get(Calendar.MONTH)]); sbuf.append(' '); int year = calendar.get(Calendar.YEAR); sbuf.append(year); sbuf.append(' '); return super.format(date, sbuf, fieldPosition); } /** This method does not do anything but return null. */ public Date parse(java.lang.String s, ParsePosition pos) { return null; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/PatternParser.java0000644000175000017500000003757411751454707026601 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import org.apache.log4j.Layout; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.LocationInfo; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import java.util.Arrays; // Contributors: Nelson Minar <(nelson@monkey.org> // Igor E. Poteryaev // Reinhard Deschler /** Most of the work of the {@link org.apache.log4j.PatternLayout} class is delegated to the PatternParser class.

It is this class that parses conversion patterns and creates a chained list of {@link OptionConverter OptionConverters}. @author James P. Cakalic @author Ceki Gülcü @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 DOT_STATE = 3; private static final int MIN_STATE = 4; private static final int MAX_STATE = 5; static final int FULL_LOCATION_CONVERTER = 1000; 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 RELATIVE_TIME_CONVERTER = 2000; static final int THREAD_CONVERTER = 2001; static final int LEVEL_CONVERTER = 2002; static final int NDC_CONVERTER = 2003; static final int MESSAGE_CONVERTER = 2004; int state; protected StringBuffer currentLiteral = new StringBuffer(32); protected int patternLength; protected int i; PatternConverter head; PatternConverter tail; protected FormattingInfo formattingInfo = new FormattingInfo(); protected String pattern; public PatternParser(String pattern) { this.pattern = pattern; patternLength = pattern.length(); state = LITERAL_STATE; } private void addToList(PatternConverter pc) { if(head == null) { head = tail = pc; } else { tail.next = pc; tail = pc; } } protected String extractOption() { if((i < patternLength) && (pattern.charAt(i) == '{')) { int end = pattern.indexOf('}', i); if (end > i) { String r = pattern.substring(i + 1, end); i = end+1; return r; } } return null; } /** The option is expected to be in decimal and positive. In case of error, zero is returned. */ protected int extractPrecisionOption() { String opt = extractOption(); int r = 0; if(opt != null) { try { r = Integer.parseInt(opt); if(r <= 0) { LogLog.error( "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; } public PatternConverter parse() { char c; i = 0; while(i < patternLength) { c = pattern.charAt(i++); switch(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. switch(pattern.charAt(i)) { case ESCAPE_CHAR: currentLiteral.append(c); i++; // move pointer break; case 'n': currentLiteral.append(Layout.LINE_SEP); i++; // move pointer break; default: if(currentLiteral.length() != 0) { addToList(new LiteralPatternConverter( currentLiteral.toString())); //LogLog.debug("Parsed LITERAL converter: \"" // +currentLiteral+"\"."); } currentLiteral.setLength(0); currentLiteral.append(c); // append % state = CONVERTER_STATE; formattingInfo.reset(); } } else { currentLiteral.append(c); } break; case CONVERTER_STATE: currentLiteral.append(c); switch(c) { case '-': formattingInfo.leftAlign = true; break; case '.': state = DOT_STATE; break; default: if(c >= '0' && c <= '9') { formattingInfo.min = c - '0'; state = MIN_STATE; } else finalizeConverter(c); } // switch break; case MIN_STATE: currentLiteral.append(c); if(c >= '0' && c <= '9') formattingInfo.min = formattingInfo.min*10 + (c - '0'); else if(c == '.') state = DOT_STATE; else { finalizeConverter(c); } break; case DOT_STATE: currentLiteral.append(c); if(c >= '0' && c <= '9') { formattingInfo.max = c - '0'; state = MAX_STATE; } else { LogLog.error("Error occured in position "+i +".\n Was expecting digit, instead got char \""+c+"\"."); state = LITERAL_STATE; } break; case MAX_STATE: currentLiteral.append(c); if(c >= '0' && c <= '9') formattingInfo.max = formattingInfo.max*10 + (c - '0'); else { finalizeConverter(c); state = LITERAL_STATE; } break; } // switch } // while if(currentLiteral.length() != 0) { addToList(new LiteralPatternConverter(currentLiteral.toString())); //LogLog.debug("Parsed LITERAL converter: \""+currentLiteral+"\"."); } return head; } protected void finalizeConverter(char c) { PatternConverter pc = null; switch(c) { case 'c': pc = new CategoryPatternConverter(formattingInfo, extractPrecisionOption()); //LogLog.debug("CATEGORY converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 'C': pc = new ClassNamePatternConverter(formattingInfo, extractPrecisionOption()); //LogLog.debug("CLASS_NAME converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 'd': String dateFormatStr = AbsoluteTimeDateFormat.ISO8601_DATE_FORMAT; DateFormat df; String dOpt = extractOption(); if(dOpt != null) dateFormatStr = dOpt; if(dateFormatStr.equalsIgnoreCase( AbsoluteTimeDateFormat.ISO8601_DATE_FORMAT)) df = new ISO8601DateFormat(); else if(dateFormatStr.equalsIgnoreCase( AbsoluteTimeDateFormat.ABS_TIME_DATE_FORMAT)) df = new AbsoluteTimeDateFormat(); else if(dateFormatStr.equalsIgnoreCase( AbsoluteTimeDateFormat.DATE_AND_TIME_DATE_FORMAT)) df = new DateTimeDateFormat(); else { try { df = new SimpleDateFormat(dateFormatStr); } catch (IllegalArgumentException e) { LogLog.error("Could not instantiate SimpleDateFormat with " + dateFormatStr, e); df = (DateFormat) OptionConverter.instantiateByClassName( "org.apache.log4j.helpers.ISO8601DateFormat", DateFormat.class, null); } } pc = new DatePatternConverter(formattingInfo, df); //LogLog.debug("DATE converter {"+dateFormatStr+"}."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 'F': pc = new LocationPatternConverter(formattingInfo, FILE_LOCATION_CONVERTER); //LogLog.debug("File name converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 'l': pc = new LocationPatternConverter(formattingInfo, FULL_LOCATION_CONVERTER); //LogLog.debug("Location converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 'L': pc = new LocationPatternConverter(formattingInfo, LINE_LOCATION_CONVERTER); //LogLog.debug("LINE NUMBER converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 'm': pc = new BasicPatternConverter(formattingInfo, MESSAGE_CONVERTER); //LogLog.debug("MESSAGE converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 'M': pc = new LocationPatternConverter(formattingInfo, METHOD_LOCATION_CONVERTER); //LogLog.debug("METHOD converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 'p': pc = new BasicPatternConverter(formattingInfo, LEVEL_CONVERTER); //LogLog.debug("LEVEL converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 'r': pc = new BasicPatternConverter(formattingInfo, RELATIVE_TIME_CONVERTER); //LogLog.debug("RELATIVE time converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 't': pc = new BasicPatternConverter(formattingInfo, THREAD_CONVERTER); //LogLog.debug("THREAD converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; /*case 'u': if(i < patternLength) { char cNext = pattern.charAt(i); if(cNext >= '0' && cNext <= '9') { pc = new UserFieldPatternConverter(formattingInfo, cNext - '0'); LogLog.debug("USER converter ["+cNext+"]."); formattingInfo.dump(); currentLiteral.setLength(0); i++; } else LogLog.error("Unexpected char" +cNext+" at position "+i); } break;*/ case 'x': pc = new BasicPatternConverter(formattingInfo, NDC_CONVERTER); //LogLog.debug("NDC converter."); currentLiteral.setLength(0); break; case 'X': String xOpt = extractOption(); pc = new MDCPatternConverter(formattingInfo, xOpt); currentLiteral.setLength(0); break; default: LogLog.error("Unexpected char [" +c+"] at position "+i +" in conversion patterrn."); pc = new LiteralPatternConverter(currentLiteral.toString()); currentLiteral.setLength(0); } addConverter(pc); } protected void addConverter(PatternConverter pc) { currentLiteral.setLength(0); // Add the pattern converter to the list. addToList(pc); // Next pattern is assumed to be a literal. state = LITERAL_STATE; // Reset formatting info formattingInfo.reset(); } // --------------------------------------------------------------------- // PatternConverters // --------------------------------------------------------------------- private static class BasicPatternConverter extends PatternConverter { int type; BasicPatternConverter(FormattingInfo formattingInfo, int type) { super(formattingInfo); this.type = type; } public String convert(LoggingEvent event) { switch(type) { case RELATIVE_TIME_CONVERTER: return (Long.toString(event.timeStamp - LoggingEvent.getStartTime())); case THREAD_CONVERTER: return event.getThreadName(); case LEVEL_CONVERTER: return event.getLevel().toString(); case NDC_CONVERTER: return event.getNDC(); case MESSAGE_CONVERTER: { return event.getRenderedMessage(); } default: return null; } } } private static class LiteralPatternConverter extends PatternConverter { private String literal; LiteralPatternConverter(String value) { literal = value; } public final void format(StringBuffer sbuf, LoggingEvent event) { sbuf.append(literal); } public String convert(LoggingEvent event) { return literal; } } 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; } public String convert(LoggingEvent event) { date.setTime(event.timeStamp); String converted = null; try { converted = df.format(date); } catch (Exception ex) { LogLog.error("Error occured while converting date.", ex); } return converted; } } private static class MDCPatternConverter extends PatternConverter { private String key; MDCPatternConverter(FormattingInfo formattingInfo, String key) { super(formattingInfo); this.key = key; } public String convert(LoggingEvent event) { if (key == null) { StringBuffer buf = new StringBuffer("{"); Map properties = event.getProperties(); if (properties.size() > 0) { Object[] keys = properties.keySet().toArray(); Arrays.sort(keys); for (int i = 0; i < keys.length; i++) { buf.append('{'); buf.append(keys[i]); buf.append(','); buf.append(properties.get(keys[i])); buf.append('}'); } } buf.append('}'); return buf.toString(); } else { Object val = event.getMDC(key); if(val == null) { return null; } else { return val.toString(); } } } } 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: return locationInfo.fullInfo; case METHOD_LOCATION_CONVERTER: return locationInfo.getMethodName(); case LINE_LOCATION_CONVERTER: return locationInfo.getLineNumber(); case FILE_LOCATION_CONVERTER: return locationInfo.getFileName(); default: return null; } } } private static abstract class NamedPatternConverter extends PatternConverter { int precision; NamedPatternConverter(FormattingInfo formattingInfo, int precision) { super(formattingInfo); this.precision = precision; } abstract String getFullyQualifiedName(LoggingEvent event); public String convert(LoggingEvent event) { String n = getFullyQualifiedName(event); if(precision <= 0) return n; else { int len = n.length(); // 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. int end = len -1 ; 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.getLoggerName(); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/QuietWriter.java0000644000175000017500000000405311751454707026255 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import java.io.Writer; import java.io.FilterWriter; import org.apache.log4j.spi.ErrorHandler; import org.apache.log4j.spi.ErrorCode; /** QuietWriter does not throw exceptions when things go wrong. Instead, it delegates error handling to its {@link ErrorHandler}. @author Ceki Gülcü @since 0.7.3 */ public class QuietWriter extends FilterWriter { protected ErrorHandler errorHandler; public QuietWriter(Writer writer, ErrorHandler errorHandler) { super(writer); setErrorHandler(errorHandler); } public void write(String string) { if (string != null) { try { out.write(string); } catch(Exception e) { errorHandler.error("Failed to write ["+string+"].", e, ErrorCode.WRITE_FAILURE); } } } public void flush() { try { out.flush(); } catch(Exception e) { errorHandler.error("Failed to flush writer,", e, ErrorCode.FLUSH_FAILURE); } } public void setErrorHandler(ErrorHandler eh) { if(eh == null) { // This is a programming error on the part of the enclosing appender. throw new IllegalArgumentException("Attempted to set null ErrorHandler."); } else { this.errorHandler = eh; } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/ISO8601DateFormat.java0000644000175000017500000001043311751454707026710 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import java.util.Calendar; import java.util.TimeZone; import java.util.Date; import java.text.FieldPosition; import java.text.ParsePosition; // Contributors: Arndt Schoenewald /** Formats a {@link Date} in the format "yyyy-MM-dd HH:mm:ss,SSS" for example "1999-11-27 15:49:37,459".

Refer to the summary of the International Standard Date and Time Notation for more information on this format. @author Ceki Gülcü @author Andrew Vajoczki @since 0.7.5 */ public class ISO8601DateFormat extends AbsoluteTimeDateFormat { private static final long serialVersionUID = -759840745298755296L; public ISO8601DateFormat() { } public ISO8601DateFormat(TimeZone timeZone) { super(timeZone); } 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 sbuf. For example: "1999-11-27 15:49:37,459". @param sbuf the StringBuffer to write to */ public StringBuffer format(Date date, StringBuffer sbuf, FieldPosition fieldPosition) { long now = date.getTime(); int millis = (int)(now % 1000); if ((now - millis) != lastTime || lastTimeString[0] == 0) { // 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); 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.DECEMBER: month = "-12-"; break; default: month = "-NA-"; break; } sbuf.append(month); int day = calendar.get(Calendar.DAY_OF_MONTH); if(day < 10) sbuf.append('0'); sbuf.append(day); 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(','); // 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'); if (millis < 10) sbuf.append('0'); sbuf.append(millis); return sbuf; } /** This method does not do anything but return null. */ public Date parse(java.lang.String s, ParsePosition pos) { return null; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/LogLog.java0000644000175000017500000001167511751454707025164 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; /** This class used to output log statements from within the log4j package.

Log4j components cannot make log4j logging calls. However, it is sometimes useful for the user to learn about what log4j is doing. You can enable log4j internal logging by defining the log4j.configDebug variable.

All log4j internal debug calls go to System.out where as internal error messages are sent to System.err. All internal messages are prepended with the string "log4j: ". @since 0.8.2 @author Ceki Gülcü */ public class LogLog { /** Defining this value makes log4j print log4j-internal debug statements to System.out.

The value of this string is log4j.debug.

Note that the search for all option names is case sensitive. */ public static final String DEBUG_KEY="log4j.debug"; /** Defining this value makes log4j components print log4j-internal debug statements to System.out.

The value of this string is log4j.configDebug.

Note that the search for all option names is case sensitive. @deprecated Use {@link #DEBUG_KEY} instead. */ public static final String CONFIG_DEBUG_KEY="log4j.configDebug"; protected static boolean debugEnabled = false; /** In quietMode not even errors generate any output. */ private static boolean quietMode = false; private static final String PREFIX = "log4j: "; private static final String ERR_PREFIX = "log4j:ERROR "; private static final String WARN_PREFIX = "log4j:WARN "; static { String key = OptionConverter.getSystemProperty(DEBUG_KEY, null); if(key == null) { key = OptionConverter.getSystemProperty(CONFIG_DEBUG_KEY, null); } if(key != null) { debugEnabled = OptionConverter.toBoolean(key, true); } } /** Allows to enable/disable log4j internal logging. */ static public void setInternalDebugging(boolean enabled) { debugEnabled = enabled; } /** This method is used to output log4j internal debug statements. Output goes to System.out. */ public static void debug(String msg) { if(debugEnabled && !quietMode) { System.out.println(PREFIX+msg); } } /** This method is used to output log4j internal debug statements. Output goes to System.out. */ public static void debug(String msg, Throwable t) { if(debugEnabled && !quietMode) { System.out.println(PREFIX+msg); if(t != null) t.printStackTrace(System.out); } } /** This method is used to output log4j internal error statements. There is no way to disable error statements. Output goes to System.err. */ public static void error(String msg) { if(quietMode) return; System.err.println(ERR_PREFIX+msg); } /** This method is used to output log4j internal error statements. There is no way to disable error statements. Output goes to System.err. */ public static void error(String msg, Throwable t) { if(quietMode) return; System.err.println(ERR_PREFIX+msg); if(t != null) { t.printStackTrace(); } } /** In quite mode no LogLog generates strictly no output, not even for errors. @param quietMode A true for not */ public static void setQuietMode(boolean quietMode) { LogLog.quietMode = quietMode; } /** This method is used to output log4j internal warning statements. There is no way to disable warning statements. Output goes to System.err. */ public static void warn(String msg) { if(quietMode) return; System.err.println(WARN_PREFIX+msg); } /** This method is used to output log4j internal warnings. There is no way to disable warning statements. Output goes to System.err. */ public static void warn(String msg, Throwable t) { if(quietMode) return; System.err.println(WARN_PREFIX+msg); if(t != null) { t.printStackTrace(); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/OnlyOnceErrorHandler.java0000644000175000017500000000553311751454707030033 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import org.apache.log4j.spi.ErrorHandler; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.Logger; import org.apache.log4j.Appender; import java.io.InterruptedIOException; /** The OnlyOnceErrorHandler implements log4j's default error handling policy which consists of emitting a message for the first error in an appender and ignoring all following errors.

The error message is printed on System.err.

This policy aims at protecting an otherwise working application from being flooded with error messages when logging fails. @author Ceki Gülcü @since 0.9.0 */ public class OnlyOnceErrorHandler implements ErrorHandler { final String WARN_PREFIX = "log4j warning: "; final String ERROR_PREFIX = "log4j error: "; boolean firstTime = true; /** Does not do anything. */ public void setLogger(Logger logger) { } /** No options to activate. */ public void activateOptions() { } /** Prints the message and the stack trace of the exception on System.err. */ public void error(String message, Exception e, int errorCode) { error(message, e, errorCode, null); } /** Prints the message and the stack trace of the exception on System.err. */ public void error(String message, Exception e, int errorCode, LoggingEvent event) { if (e instanceof InterruptedIOException || e instanceof InterruptedException) { Thread.currentThread().interrupt(); } if(firstTime) { LogLog.error(message, e); firstTime = false; } } /** Print a the error message passed as parameter on System.err. */ public void error(String message) { if(firstTime) { LogLog.error(message); firstTime = false; } } /** Does not do anything. */ public void setAppender(Appender appender) { } /** Does not do anything. */ public void setBackupAppender(Appender appender) { } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/FormattingInfo.java0000644000175000017500000000254111751454707026717 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; /** FormattingInfo instances contain the information obtained when parsing formatting modifiers in conversion modifiers. @author Jim Cakalic @author Ceki Gülcü @since 0.8.2 */ public class FormattingInfo { int min = -1; int max = 0x7FFFFFFF; boolean leftAlign = false; void reset() { min = -1; max = 0x7FFFFFFF; leftAlign = false; } void dump() { LogLog.debug("min="+min+", max="+max+", leftAlign="+leftAlign); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/UtilLoggingLevel.java0000644000175000017500000001433511751454707027211 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Level; /** * An extension of the Level class that provides support for java.util.logging * Levels. * * * @author Scott Deboy (sdeboy@apache.org) */ public class UtilLoggingLevel extends Level { /** * Serialization version id. */ private static final long serialVersionUID = 909301162611820211L; /** * Numerical value for SEVERE. */ public static final int SEVERE_INT = 22000; /** * Numerical value for WARNING. */ public static final int WARNING_INT = 21000; //INFO level defined in parent as 20000..no need to redefine here /** * Numerical value for CONFIG. */ public static final int CONFIG_INT = 14000; /** * Numerical value for FINE. */ public static final int FINE_INT = 13000; /** * Numerical value for FINER. */ public static final int FINER_INT = 12000; /** * Numerical value for FINEST. */ public static final int FINEST_INT = 11000; /** * Numerical value for UNKNOWN. */ public static final int UNKNOWN_INT = 10000; /** * SEVERE. */ public static final UtilLoggingLevel SEVERE = new UtilLoggingLevel(SEVERE_INT, "SEVERE", 0); /** * WARNING. */ public static final UtilLoggingLevel WARNING = new UtilLoggingLevel(WARNING_INT, "WARNING", 4); /** * INFO. */ //note: we've aligned the int values of the java.util.logging INFO level with log4j's level public static final UtilLoggingLevel INFO = new UtilLoggingLevel(INFO_INT, "INFO", 5); /** * CONFIG. */ public static final UtilLoggingLevel CONFIG = new UtilLoggingLevel(CONFIG_INT, "CONFIG", 6); /** * FINE. */ public static final UtilLoggingLevel FINE = new UtilLoggingLevel(FINE_INT, "FINE", 7); /** * FINER. */ public static final UtilLoggingLevel FINER = new UtilLoggingLevel(FINER_INT, "FINER", 8); /** * FINEST. */ public static final UtilLoggingLevel FINEST = new UtilLoggingLevel(FINEST_INT, "FINEST", 9); /** * Create new instance. * @param level numeric value for level. * @param levelStr symbolic name for level. * @param syslogEquivalent Equivalent syslog severity. */ protected UtilLoggingLevel(final int level, final String levelStr, final int syslogEquivalent) { super(level, levelStr, syslogEquivalent); } /** * Convert an integer passed as argument to a level. If the * conversion fails, then this method returns the specified default. * @param val numeric value. * @param defaultLevel level to be returned if no level matches * numeric value. * @return matching level or default level. */ public static UtilLoggingLevel toLevel(final int val, final UtilLoggingLevel defaultLevel) { switch (val) { case SEVERE_INT: return SEVERE; case WARNING_INT: return WARNING; case INFO_INT: return INFO; case CONFIG_INT: return CONFIG; case FINE_INT: return FINE; case FINER_INT: return FINER; case FINEST_INT: return FINEST; default: return defaultLevel; } } /** * Gets level matching numeric value. * @param val numeric value. * @return matching level or UtilLoggerLevel.FINEST if no match. */ public static Level toLevel(final int val) { return toLevel(val, FINEST); } /** * Gets list of supported levels. * @return list of supported levels. */ public static List getAllPossibleLevels() { ArrayList list = new ArrayList(); list.add(FINE); list.add(FINER); list.add(FINEST); list.add(INFO); list.add(CONFIG); list.add(WARNING); list.add(SEVERE); return list; } /** * Get level with specified symbolic name. * @param s symbolic name. * @return matching level or Level.DEBUG if no match. */ public static Level toLevel(final String s) { return toLevel(s, Level.DEBUG); } /** * Get level with specified symbolic name. * @param sArg symbolic name. * @param defaultLevel level to return if no match. * @return matching level or defaultLevel if no match. */ public static Level toLevel(final String sArg, final Level defaultLevel) { if (sArg == null) { return defaultLevel; } String s = sArg.toUpperCase(); if (s.equals("SEVERE")) { return SEVERE; } //if(s.equals("FINE")) return Level.FINE; if (s.equals("WARNING")) { return WARNING; } if (s.equals("INFO")) { return INFO; } if (s.equals("CONFI")) { return CONFIG; } if (s.equals("FINE")) { return FINE; } if (s.equals("FINER")) { return FINER; } if (s.equals("FINEST")) { return FINEST; } return defaultLevel; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/Transform.java0000644000175000017500000000743311751454707025751 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; /** Utility class for transforming strings. @author Ceki Gülcü @author Michael A. McAngus */ public class Transform { private static final String CDATA_START = ""; private static final String CDATA_PSEUDO_END = "]]>"; private static final String CDATA_EMBEDED_END = CDATA_END + CDATA_PSEUDO_END + CDATA_START; private static final int CDATA_END_LEN = CDATA_END.length(); /** * This method takes a string which may contain HTML tags (ie, * <b>, <table>, etc) and replaces any * '<', '>' , '&' or '"' * characters with respective predefined entity references. * * @param input The text to be converted. * @return The input string with the special characters replaced. * */ static public String escapeTags(final String input) { //Check if the string is null, zero length or devoid of special characters // if so, return what was sent in. if(input == null || input.length() == 0 || (input.indexOf('"') == -1 && input.indexOf('&') == -1 && input.indexOf('<') == -1 && input.indexOf('>') == -1)) { 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); if (ch > '>') { buf.append(ch); } else if(ch == '<') { buf.append("<"); } else if(ch == '>') { buf.append(">"); } else if(ch == '&') { buf.append("&"); } else if(ch == '"') { buf.append("""); } else { buf.append(ch); } } return buf.toString(); } /** * Ensures that embeded CDEnd strings (]]>) are handled properly * within message, NDC and throwable tag text. * * @param buf StringBuffer holding the XML data to this point. The * initial CDStart () of the CDATA * section are the responsibility of the calling method. * @param str The String that is inserted into an existing CDATA Section within buf. * */ static public void appendEscapingCDATA(final StringBuffer buf, final String str) { if (str != null) { int end = str.indexOf(CDATA_END); if (end < 0) { buf.append(str); } else { int start = 0; while (end > -1) { buf.append(str.substring(start, end)); buf.append(CDATA_EMBEDED_END); start = end + CDATA_END_LEN; if (start < str.length()) { end = str.indexOf(CDATA_END, start); } else { return; } } buf.append(str.substring(start)); } } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/DateLayout.java0000644000175000017500000001413111751454707026042 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import org.apache.log4j.Layout; import org.apache.log4j.spi.LoggingEvent; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import java.text.FieldPosition; /** This abstract layout takes care of all the date related options and formatting work. @author Ceki Gülcü */ abstract public class DateLayout extends Layout { /** String constant designating no time information. Current value of this constant is NULL. */ public final static String NULL_DATE_FORMAT = "NULL"; /** String constant designating relative time. Current value of this constant is RELATIVE. */ public final static String RELATIVE_TIME_DATE_FORMAT = "RELATIVE"; protected FieldPosition pos = new FieldPosition(0); /** @deprecated Options are now handled using the JavaBeans paradigm. This constant is not longer needed and will be removed in the near term. */ final static public String DATE_FORMAT_OPTION = "DateFormat"; /** @deprecated Options are now handled using the JavaBeans paradigm. This constant is not longer needed and will be removed in the near term. */ final static public String TIMEZONE_OPTION = "TimeZone"; private String timeZoneID; private String dateFormatOption; protected DateFormat dateFormat; protected Date date = new Date(); /** @deprecated Use the setter method for the option directly instead of the generic setOption method. */ public String[] getOptionStrings() { return new String[] {DATE_FORMAT_OPTION, TIMEZONE_OPTION}; } /** @deprecated Use the setter method for the option directly instead of the generic setOption method. */ public void setOption(String option, String value) { if(option.equalsIgnoreCase(DATE_FORMAT_OPTION)) { dateFormatOption = value.toUpperCase(); } else if(option.equalsIgnoreCase(TIMEZONE_OPTION)) { timeZoneID = value; } } /** The value of the DateFormat option should be either an argument to the constructor of {@link SimpleDateFormat} or one of the srings "NULL", "RELATIVE", "ABSOLUTE", "DATE" or "ISO8601. */ public void setDateFormat(String dateFormat) { if (dateFormat != null) { dateFormatOption = dateFormat; } setDateFormat(dateFormatOption, TimeZone.getDefault()); } /** Returns value of the DateFormat option. */ public String getDateFormat() { return dateFormatOption; } /** The TimeZoneID option is a time zone ID string in the format expected by the {@link TimeZone#getTimeZone} method. */ public void setTimeZone(String timeZone) { this.timeZoneID = timeZone; } /** Returns value of the TimeZone option. */ public String getTimeZone() { return timeZoneID; } public void activateOptions() { setDateFormat(dateFormatOption); if(timeZoneID != null && dateFormat != null) { dateFormat.setTimeZone(TimeZone.getTimeZone(timeZoneID)); } } public void dateFormat(StringBuffer buf, LoggingEvent event) { if(dateFormat != null) { date.setTime(event.timeStamp); dateFormat.format(date, buf, this.pos); buf.append(' '); } } /** Sets the {@link DateFormat} used to format time and date in the zone determined by timeZone. */ public void setDateFormat(DateFormat dateFormat, TimeZone timeZone) { this.dateFormat = dateFormat; this.dateFormat.setTimeZone(timeZone); } /** Sets the DateFormat used to format date and time in the time zone determined by timeZone parameter. The {@link DateFormat} used will depend on the dateFormatType.

The recognized types are {@link #NULL_DATE_FORMAT}, {@link #RELATIVE_TIME_DATE_FORMAT} {@link AbsoluteTimeDateFormat#ABS_TIME_DATE_FORMAT}, {@link AbsoluteTimeDateFormat#DATE_AND_TIME_DATE_FORMAT} and {@link AbsoluteTimeDateFormat#ISO8601_DATE_FORMAT}. If the dateFormatType is not one of the above, then the argument is assumed to be a date pattern for {@link SimpleDateFormat}. */ public void setDateFormat(String dateFormatType, TimeZone timeZone) { if(dateFormatType == null) { this.dateFormat = null; return; } if(dateFormatType.equalsIgnoreCase(NULL_DATE_FORMAT)) { this.dateFormat = null; } else if (dateFormatType.equalsIgnoreCase(RELATIVE_TIME_DATE_FORMAT)) { this.dateFormat = new RelativeTimeDateFormat(); } else if(dateFormatType.equalsIgnoreCase( AbsoluteTimeDateFormat.ABS_TIME_DATE_FORMAT)) { this.dateFormat = new AbsoluteTimeDateFormat(timeZone); } else if(dateFormatType.equalsIgnoreCase( AbsoluteTimeDateFormat.DATE_AND_TIME_DATE_FORMAT)) { this.dateFormat = new DateTimeDateFormat(timeZone); } else if(dateFormatType.equalsIgnoreCase( AbsoluteTimeDateFormat.ISO8601_DATE_FORMAT)) { this.dateFormat = new ISO8601DateFormat(timeZone); } else { this.dateFormat = new SimpleDateFormat(dateFormatType); this.dateFormat.setTimeZone(timeZone); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/AbsoluteTimeDateFormat.java0000644000175000017500000000772411751454707030345 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import java.util.Date; import java.util.Calendar; import java.util.TimeZone; import java.text.FieldPosition; import java.text.ParsePosition; import java.text.DateFormat; /** Formats a {@link Date} in the format "HH:mm:ss,SSS" for example, "15:49:37,459". @author Ceki Gülcü @author Andrew Vajoczki @since 0.7.5 */ public class AbsoluteTimeDateFormat extends DateFormat { private static final long serialVersionUID = -388856345976723342L; /** String constant used to specify {@link org.apache.log4j.helpers.AbsoluteTimeDateFormat} in layouts. Current value is ABSOLUTE. */ public final static String ABS_TIME_DATE_FORMAT = "ABSOLUTE"; /** String constant used to specify {@link org.apache.log4j.helpers.DateTimeDateFormat} in layouts. Current value is DATE. */ public final static String DATE_AND_TIME_DATE_FORMAT = "DATE"; /** String constant used to specify {@link org.apache.log4j.helpers.ISO8601DateFormat} in layouts. Current value is ISO8601. */ public final static String ISO8601_DATE_FORMAT = "ISO8601"; public AbsoluteTimeDateFormat() { setCalendar(Calendar.getInstance()); } public AbsoluteTimeDateFormat(TimeZone timeZone) { setCalendar(Calendar.getInstance(timeZone)); } private static long previousTime; private static char[] previousTimeWithoutMillis = new char[9]; // "HH:mm:ss." /** Appends to sbuf the time in the format "HH:mm:ss,SSS" for example, "15:49:37,459" @param date the date to format @param sbuf the string buffer to write to @param fieldPosition remains untouched */ public StringBuffer format(Date date, StringBuffer sbuf, FieldPosition fieldPosition) { long now = date.getTime(); int millis = (int)(now % 1000); if ((now - millis) != previousTime || previousTimeWithoutMillis[0] == 0) { // 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); int start = sbuf.length(); 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(','); // store the time string for next time to avoid recomputation sbuf.getChars(start, sbuf.length(), previousTimeWithoutMillis, 0); previousTime = now - millis; } else { sbuf.append(previousTimeWithoutMillis); } if(millis < 100) sbuf.append('0'); if(millis < 10) sbuf.append('0'); sbuf.append(millis); return sbuf; } /** This method does not do anything but return null. */ public Date parse(String s, ParsePosition pos) { return null; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/ThreadLocalMap.java0000644000175000017500000000246211751454707026613 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import java.util.Hashtable; /** ThreadLocalMap extends {@link InheritableThreadLocal} to bequeath a copy of the hashtable of the MDC of the parent thread. @author Ceki Gülcü @since 1.2 */ final public class ThreadLocalMap extends InheritableThreadLocal { public final Object childValue(Object parentValue) { Hashtable ht = (Hashtable) parentValue; if(ht != null) { return ht.clone(); } else { return null; } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/AppenderAttachableImpl.java0000644000175000017500000001075011751454707030323 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import org.apache.log4j.spi.AppenderAttachable; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.Appender; import java.util.Vector; import java.util.Enumeration; /** A straightforward implementation of the {@link AppenderAttachable} interface. @author Ceki Gülcü @since version 0.9.1 */ public class AppenderAttachableImpl implements AppenderAttachable { /** Array of appenders. */ protected Vector appenderList; /** Attach an appender. If the appender is already in the list in won't be added again. */ public void addAppender(Appender newAppender) { // Null values for newAppender parameter are strictly forbidden. if(newAppender == null) return; if(appenderList == null) { appenderList = new Vector(1); } if(!appenderList.contains(newAppender)) appenderList.addElement(newAppender); } /** Call the doAppend method on all attached appenders. */ public int appendLoopOnAppenders(LoggingEvent event) { int size = 0; Appender appender; if(appenderList != null) { size = appenderList.size(); for(int i = 0; i < size; i++) { appender = (Appender) appenderList.elementAt(i); appender.doAppend(event); } } return size; } /** Get all attached appenders as an Enumeration. If there are no attached appenders null is returned. @return Enumeration An enumeration of attached appenders. */ public Enumeration getAllAppenders() { if(appenderList == null) return null; else return appenderList.elements(); } /** Look for an attached appender named as name.

Return the appender with that name if in the list. Return null otherwise. */ public Appender getAppender(String name) { if(appenderList == null || name == null) return null; int size = appenderList.size(); Appender appender; for(int i = 0; i < size; i++) { appender = (Appender) appenderList.elementAt(i); if(name.equals(appender.getName())) return appender; } return null; } /** Returns true if the specified appender is in the list of attached appenders, false otherwise. @since 1.2 */ public boolean isAttached(Appender appender) { if(appenderList == null || appender == null) return false; int size = appenderList.size(); Appender a; for(int i = 0; i < size; i++) { a = (Appender) appenderList.elementAt(i); if(a == appender) return true; } return false; } /** * Remove and close all previously attached appenders. * */ public void removeAllAppenders() { if(appenderList != null) { int len = appenderList.size(); for(int i = 0; i < len; i++) { Appender a = (Appender) appenderList.elementAt(i); a.close(); } appenderList.removeAllElements(); appenderList = null; } } /** Remove the appender passed as parameter form the list of attached appenders. */ public void removeAppender(Appender appender) { if(appender == null || appenderList == null) return; appenderList.removeElement(appender); } /** Remove the appender with the name passed as parameter form the list of appenders. */ public void removeAppender(String name) { if(name == null || appenderList == null) return; int size = appenderList.size(); for(int i = 0; i < size; i++) { if(name.equals(((Appender)appenderList.elementAt(i)).getName())) { appenderList.removeElementAt(i); break; } } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/BoundedFIFO.java0000644000175000017500000001123311751454707026013 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Contributors: Mathias Bogaert // joelr@viair.com package org.apache.log4j.helpers; import org.apache.log4j.spi.LoggingEvent; /** BoundedFIFO serves as the bounded first-in-first-out buffer heavily used by the {@link org.apache.log4j.AsyncAppender}. @author Ceki Gülcü @since version 0.9.1 */ public class BoundedFIFO { LoggingEvent[] buf; int numElements = 0; int first = 0; int next = 0; int maxSize; /** Instantiate a new BoundedFIFO with a maximum size passed as argument. */ public BoundedFIFO(int maxSize) { if(maxSize < 1) { throw new IllegalArgumentException("The maxSize argument ("+maxSize+ ") is not a positive integer."); } this.maxSize = maxSize; buf = new LoggingEvent[maxSize]; } /** Get the first element in the buffer. Returns null if there are no elements in the buffer. */ public LoggingEvent get() { if(numElements == 0) return null; LoggingEvent r = buf[first]; buf[first] = null; // help garbage collection if(++first == maxSize) { first = 0; } numElements--; return r; } /** Place a {@link LoggingEvent} in the buffer. If the buffer is full then the event is silently dropped. It is the caller's responsability to make sure that the buffer has free space. */ public void put(LoggingEvent o) { if(numElements != maxSize) { buf[next] = o; if(++next == maxSize) { next = 0; } numElements++; } } /** Get the maximum size of the buffer. */ public int getMaxSize() { return maxSize; } /** Return true if the buffer is full, that is, whether the number of elements in the buffer equals the buffer size. */ public boolean isFull() { return numElements == maxSize; } /** Get the number of elements in the buffer. This number is guaranteed to be in the range 0 to maxSize (inclusive). */ public int length() { return numElements; } int min(int a, int b) { return a < b ? a : b; } /** Resize the buffer to a new size. If the new size is smaller than the old size events might be lost. @since 1.1 */ synchronized public void resize(int newSize) { if(newSize == maxSize) return; LoggingEvent[] tmp = new LoggingEvent[newSize]; // we should not copy beyond the buf array int len1 = maxSize - first; // we should not copy beyond the tmp array len1 = min(len1, newSize); // er.. how much do we actually need to copy? // We should not copy more than the actual number of elements. len1 = min(len1, numElements); // Copy from buf starting a first, to tmp, starting at position 0, len1 elements. System.arraycopy(buf, first, tmp, 0, len1); // Are there any uncopied elements and is there still space in the new array? int len2 = 0; if((len1 < numElements) && (len1 < newSize)) { len2 = numElements - len1; len2 = min(len2, newSize - len1); System.arraycopy(buf, 0, tmp, len1, len2); } this.buf = tmp; this.maxSize = newSize; this.first=0; this.numElements = len1+len2; this.next = this.numElements; if(this.next == this.maxSize) // this should never happen, but again, it just might. this.next = 0; } /** Returns true if there is just one element in the buffer. In other words, if there were no elements before the last {@link #put} operation completed. */ public boolean wasEmpty() { return numElements == 1; } /** Returns true if the number of elements in the buffer plus 1 equals the maximum buffer size, returns false otherwise. */ public boolean wasFull() { return (numElements+1 == maxSize); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/NullEnumeration.java0000644000175000017500000000256211751454707027115 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import java.util.Enumeration; import java.util.NoSuchElementException; /** An always-empty Enumerator. @author Anders Kristensen @since version 1.0 */ public class NullEnumeration implements Enumeration { private static final NullEnumeration instance = new NullEnumeration(); private NullEnumeration() { } public static NullEnumeration getInstance() { return instance; } public boolean hasMoreElements() { return false; } public Object nextElement() { throw new NoSuchElementException(); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/CyclicBuffer.java0000644000175000017500000000743011751454707026333 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import org.apache.log4j.spi.LoggingEvent; /** CyclicBuffer is used by other appenders to hold {@link LoggingEvent LoggingEvents} for immediate or differed display.

This buffer gives read access to any element in the buffer not just the first or last element. @author Ceki Gülcü @since 0.9.0 */ public class CyclicBuffer { LoggingEvent[] ea; int first; int last; int numElems; int maxSize; /** Instantiate a new CyclicBuffer of at most maxSize events. The maxSize argument must a positive integer. @param maxSize The maximum number of elements in the buffer. */ public CyclicBuffer(int maxSize) throws IllegalArgumentException { if(maxSize < 1) { throw new IllegalArgumentException("The maxSize argument ("+maxSize+ ") is not a positive integer."); } this.maxSize = maxSize; ea = new LoggingEvent[maxSize]; first = 0; last = 0; numElems = 0; } /** Add an event as the last event in the buffer. */ public void add(LoggingEvent event) { ea[last] = event; if(++last == maxSize) last = 0; if(numElems < maxSize) numElems++; else if(++first == maxSize) first = 0; } /** Get the ith oldest event currently in the buffer. If i is outside the range 0 to the number of elements currently in the buffer, then null is returned. */ public LoggingEvent get(int i) { if(i < 0 || i >= numElems) return null; return ea[(first + i) % maxSize]; } public int getMaxSize() { return maxSize; } /** Get the oldest (first) element in the buffer. The oldest element is removed from the buffer. */ public LoggingEvent get() { LoggingEvent r = null; if(numElems > 0) { numElems--; r = ea[first]; ea[first] = null; if(++first == maxSize) first = 0; } return r; } /** Get the number of elements in the buffer. This number is guaranteed to be in the range 0 to maxSize (inclusive). */ public int length() { return numElems; } /** Resize the cyclic buffer to newSize. @throws IllegalArgumentException if newSize is negative. */ public void resize(int newSize) { if(newSize < 0) { throw new IllegalArgumentException("Negative array size ["+newSize+ "] not allowed."); } if(newSize == numElems) return; // nothing to do LoggingEvent[] temp = new LoggingEvent[newSize]; int loopLen = newSize < numElems ? newSize : numElems; for(int i = 0; i < loopLen; i++) { temp[i] = ea[first]; ea[first] = null; if(++first == numElems) first = 0; } ea = temp; first = 0; numElems = loopLen; maxSize = newSize; if (loopLen == newSize) { last = 0; } else { last = loopLen; } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/FileWatchdog.java0000644000175000017500000000557511751454707026343 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Contributors: Mathias Bogaert package org.apache.log4j.helpers; import java.io.File; /** Check every now and then that a certain file has not changed. If it has, then call the {@link #doOnChange} method. @author Ceki Gülcü @since version 0.9.1 */ public abstract class FileWatchdog extends Thread { /** The default delay between every file modification check, set to 60 seconds. */ static final public long DEFAULT_DELAY = 60000; /** The name of the file to observe for changes. */ protected String filename; /** The delay to observe between every check. By default set {@link #DEFAULT_DELAY}. */ protected long delay = DEFAULT_DELAY; File file; long lastModif = 0; boolean warnedAlready = false; boolean interrupted = false; protected FileWatchdog(String filename) { super("FileWatchdog"); this.filename = filename; file = new File(filename); setDaemon(true); checkAndConfigure(); } /** Set the delay to observe between each check of the file changes. */ public void setDelay(long delay) { this.delay = delay; } abstract protected void doOnChange(); protected void checkAndConfigure() { boolean fileExists; try { fileExists = file.exists(); } catch(SecurityException e) { LogLog.warn("Was not allowed to read check file existance, file:["+ filename+"]."); interrupted = true; // there is no point in continuing return; } if(fileExists) { long l = file.lastModified(); // this can also throw a SecurityException if(l > lastModif) { // however, if we reached this point this lastModif = l; // is very unlikely. doOnChange(); warnedAlready = false; } } else { if(!warnedAlready) { LogLog.debug("["+filename+"] does not exist."); warnedAlready = true; } } } public void run() { while(!interrupted) { try { Thread.sleep(delay); } catch(InterruptedException e) { // no interruption expected } checkAndConfigure(); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/OptionConverter.java0000644000175000017500000004032411751454707027132 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import java.io.InputStream; import java.io.InterruptedIOException; import java.net.URL; import java.util.Properties; import org.apache.log4j.Level; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.spi.Configurator; import org.apache.log4j.spi.LoggerRepository; // Contributors: Avy Sharell (sharell@online.fr) // Matthieu Verbert (mve@zurich.ibm.com) // Colin Sampaleanu /** A convenience class to convert property values to specific types. @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; /** OptionConverter is a static class. */ private OptionConverter() {} public static String[] concatanateArrays(String[] l, String[] r) { int len = l.length + r.length; String[] a = new String[len]; System.arraycopy(l, 0, a, 0, l.length); System.arraycopy(r, 0, a, l.length, r.length); 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++); if (c == '\\') { c = s.charAt(i++); if(c == 'n') c = '\n'; 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 = '\\'; } sbuf.append(c); } return sbuf.toString(); } /** Very similar to System.getProperty except that the {@link SecurityException} is hidden. @param key The key to search for. @param def The default value to return. @return the string value of the system property, or the default value if there is no property with that key. @since 1.1 */ public static String getSystemProperty(String key, String def) { try { return System.getProperty(key, def); } 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, Object defaultValue) { // Get the value of the property in string form String className = findAndSubst(key, props); if(className == null) { LogLog.error("Could not find value for key " + key); return defaultValue; } // Trim className to avoid trailing spaces that cause problems. return OptionConverter.instantiateByClassName(className.trim(), superClass, defaultValue); } /** If value is "true", then true is returned. If value is "false", then true is returned. Otherwise, default is returned.

Case of value is unimportant. */ public static boolean toBoolean(String value, boolean dEfault) { if(value == null) return dEfault; String trimmedVal = value.trim(); if("true".equalsIgnoreCase(trimmedVal)) return true; if("false".equalsIgnoreCase(trimmedVal)) return false; return dEfault; } public static int toInt(String value, int dEfault) { if(value != null) { String s = value.trim(); try { return Integer.valueOf(s).intValue(); } catch (NumberFormatException e) { LogLog.error("[" + s + "] is not in proper int form."); e.printStackTrace(); } } return dEfault; } /** Converts a standard or custom priority level to a Level object.

If value is of form "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.

As a special case, if the value parameter is equal to the string "NULL", then the value null will be returned.

If any error occurs while converting the value to a level, the defaultValue parameter, which may be null, is returned.

Case of value is insignificant for the level level, but is significant for the class name part, if present. @since 1.1 */ public static Level toLevel(String value, Level defaultValue) { if(value == null) return defaultValue; value = value.trim(); int hashIndex = value.indexOf('#'); if (hashIndex == -1) { if("NULL".equalsIgnoreCase(value)) { return null; } else { // no class name specified : use standard Level class return(Level) Level.toLevel(value, defaultValue); } } Level result = defaultValue; 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 + "]" + ":pri=[" + levelName + "]"); try { Class customLevel = Loader.loadClass(clazz); // get a ref to the specified class' static method // toLevel(String, org.apache.log4j.Level) Class[] paramTypes = new Class[] { String.class, org.apache.log4j.Level.class }; java.lang.reflect.Method toLevelMethod = customLevel.getMethod("toLevel", paramTypes); // now call the toLevel method, passing level string + default Object[] params = new Object[] {levelName, defaultValue}; Object o = toLevelMethod.invoke(null, params); result = (Level) o; } catch(ClassNotFoundException e) { LogLog.warn("custom level class [" + clazz + "] not found."); } catch(NoSuchMethodException e) { LogLog.warn("custom level class [" + clazz + "]" + " does not have a class function toLevel(String, Level)", e); } catch(java.lang.reflect.InvocationTargetException e) { if (e.getTargetException() instanceof InterruptedException || e.getTargetException() instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.warn("custom level class [" + clazz + "]" + " could not be instantiated", e); } catch(ClassCastException e) { LogLog.warn("class [" + clazz + "] is not a subclass of org.apache.log4j.Level", e); } catch(IllegalAccessException e) { LogLog.warn("class ["+clazz+ "] cannot be instantiated due to access restrictions", e); } catch(RuntimeException e) { LogLog.warn("class ["+clazz+"], level ["+levelName+ "] conversion failed.", e); } 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) { multiplier = 1024; s = s.substring(0, index); } else if((index = s.indexOf("MB")) != -1) { multiplier = 1024*1024; s = s.substring(0, index); } 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; } catch (NumberFormatException e) { LogLog.error("[" + s + "] is not in proper int form."); LogLog.error("[" + value + "] not in expected format.", e); } } return dEfault; } /** Find the value corresponding to key in props. Then perform variable substitution on the found value. */ public static String findAndSubst(String key, Properties props) { String value = props.getProperty(key); 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 className is a subclass of superClass. If that test fails or the object could not be instantiated, then defaultValue is returned. @param className The fully qualified class name of the object to instantiate. @param superClass The class to which the new object should belong. @param defaultValue The object to return in case of non-fulfillment */ public static Object instantiateByClassName(String className, Class superClass, Object defaultValue) { if(className != null) { try { Class classObj = Loader.loadClass(className); if(!superClass.isAssignableFrom(classObj)) { LogLog.error("A \""+className+"\" object is not assignable to a \""+ superClass.getName() + "\" variable."); LogLog.error("The class \""+ superClass.getName()+"\" was loaded by "); LogLog.error("["+superClass.getClassLoader()+"] whereas object of type "); LogLog.error("\"" +classObj.getName()+"\" was loaded by [" +classObj.getClassLoader()+"]."); return defaultValue; } return classObj.newInstance(); } catch (ClassNotFoundException e) { LogLog.error("Could not instantiate class [" + className + "].", e); } catch (IllegalAccessException e) { LogLog.error("Could not instantiate class [" + className + "].", e); } catch (InstantiationException e) { LogLog.error("Could not instantiate class [" + className + "].", e); } catch (RuntimeException e) { LogLog.error("Could not instantiate class [" + className + "].", e); } } return defaultValue; } /** Perform variable substitution in string val from the values of keys found in the system propeties.

The variable substitution delimeters are ${ and }.

For example, if the System properties contains "key=value", then the call

     String s = OptionConverter.substituteVars("Value of key is ${key}.");
     
will set the variable s to "Value of key is value.".

If no value could be found for the specified key, then the props parameter is searched, if the value could not be found there, then substitution defaults to the empty string.

For example, if system propeties contains no value for the key "inexistentKey", then the call

     String s = OptionConverter.subsVars("Value of inexistentKey is [${inexistentKey}]");
     
will set s to "Value of inexistentKey is []"

An {@link java.lang.IllegalArgumentException} is thrown if val contains a start delimeter "${" which is not balanced by a stop delimeter "}".

Author Avy Sharell

@param val The string on which variable substitution is performed. @throws IllegalArgumentException if val is malformed. */ public static String substVars(String val, Properties props) throws IllegalArgumentException { StringBuffer sbuf = new StringBuffer(); int i = 0; int j, k; while(true) { j=val.indexOf(DELIM_START, i); if(j == -1) { // no more variables if(i==0) { // this is a simple string return val; } else { // add the tail string which contails no variables and return the result. sbuf.append(val.substring(i, val.length())); return sbuf.toString(); } } else { sbuf.append(val.substring(i, j)); k = val.indexOf(DELIM_STOP, j); if(k == -1) { throw new IllegalArgumentException('"'+val+ "\" has no closing brace. Opening brace at position " + j + '.'); } else { j += DELIM_START_LEN; String key = val.substring(j, k); // first try in System properties String replacement = getSystemProperty(key, null); // then try props parameter if(replacement == null && props != null) { replacement = props.getProperty(key); } if(replacement != null) { // Do variable substitution on the replacement string // such that we can solve "Hello ${x2}" as "Hello p1" // the where the properties are // x1=p1 // x2=${x1} String recursiveReplacement = substVars(replacement, props); sbuf.append(recursiveReplacement); } i = k + DELIM_STOP_LEN; } } } } /** * Configure log4j given an {@link InputStream}. * *

* The InputStream will be interpreted by a new instance of a log4j configurator. *

*

* All configurations steps are taken on the hierarchy passed as a parameter. *

* * @param inputStream * The configuration input stream. * @param clazz * The class name, of the log4j configurator which will parse the inputStream. This must be a * subclass of {@link Configurator}, or null. If this value is null then a default configurator of * {@link PropertyConfigurator} is used. * @param hierarchy * The {@link org.apache.log4j.Hierarchy} to act on. * @since 1.2.17 */ static public void selectAndConfigure(InputStream inputStream, String clazz, LoggerRepository hierarchy) { Configurator configurator = null; if(clazz != null) { LogLog.debug("Preferred configurator class: " + clazz); configurator = (Configurator) instantiateByClassName(clazz, Configurator.class, null); if(configurator == null) { LogLog.error("Could not instantiate configurator ["+clazz+"]."); return; } } else { configurator = new PropertyConfigurator(); } configurator.doConfigure(inputStream, hierarchy); } /** Configure log4j given a URL.

The url must point to a file or resource which will be interpreted by a new instance of a log4j configurator.

All configurations steps are taken on the hierarchy passed as a parameter.

@param url The location of the configuration file or resource. @param clazz The classname, of the log4j configurator which will parse the file or resource at url. This must be a subclass of {@link Configurator}, or null. If this value is null then a default configurator of {@link PropertyConfigurator} is used, unless the filename pointed to by url ends in '.xml', in which case {@link org.apache.log4j.xml.DOMConfigurator} is used. @param hierarchy The {@link org.apache.log4j.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.class, null); if(configurator == null) { LogLog.error("Could not instantiate configurator ["+clazz+"]."); return; } } else { configurator = new PropertyConfigurator(); } configurator.doConfigure(url, hierarchy); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/MDCKeySetExtractor.java0000644000175000017500000000652111751454707027417 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.pattern.LogEvent; import java.lang.reflect.Method; import java.util.Set; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.ByteArrayInputStream; import java.io.ObjectInputStream; public final class MDCKeySetExtractor { private final Method getKeySetMethod; public static final MDCKeySetExtractor INSTANCE = new MDCKeySetExtractor(); private MDCKeySetExtractor() { // // log4j 1.2.15 and later will have method to get names // of all keys in MDC // Method getMethod = null; try { getMethod = LoggingEvent.class.getMethod( "getPropertyKeySet", null); } catch(Exception ex) { getMethod = null; } getKeySetMethod = getMethod; } public Set getPropertyKeySet(final LoggingEvent event) throws Exception { // // MDC keys are not visible prior to log4j 1.2.15 // Set keySet = null; if (getKeySetMethod != null) { keySet = (Set) getKeySetMethod.invoke(event, null); } else { // // for 1.2.14 and earlier could serialize and // extract MDC content ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); ObjectOutputStream os = new ObjectOutputStream(outBytes); os.writeObject(event); os.close(); byte[] raw = outBytes.toByteArray(); // // bytes 6 and 7 should be the length of the original classname // should be the same as our substitute class name final String subClassName = LogEvent.class.getName(); if (raw[6] == 0 || raw[7] == subClassName.length()) { // // manipulate stream to use our class name // for (int i = 0; i < subClassName.length(); i++) { raw[8 + i] = (byte) subClassName.charAt(i); } ByteArrayInputStream inBytes = new ByteArrayInputStream(raw); ObjectInputStream is = new ObjectInputStream(inBytes); Object cracked = is.readObject(); if (cracked instanceof LogEvent) { keySet = ((LogEvent) cracked).getPropertyKeySet(); } is.close(); } } return keySet; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/CountingQuietWriter.java0000644000175000017500000000311411751454707027761 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import java.io.Writer; import java.io.IOException; import org.apache.log4j.spi.ErrorHandler; import org.apache.log4j.spi.ErrorCode; /** Counts the number of bytes written. @author Heinz Richter, heinz.richter@frogdot.com @since 0.8.1 */ public class CountingQuietWriter extends QuietWriter { protected long count; public CountingQuietWriter(Writer writer, ErrorHandler eh) { super(writer, eh); } public void write(String string) { try { out.write(string); count += string.length(); } catch(IOException e) { errorHandler.error("Write failure.", e, ErrorCode.WRITE_FAILURE); } } public long getCount() { return count; } public void setCount(long count) { this.count = count; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/helpers/PatternConverter.java0000644000175000017500000000543711751454707027305 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; import org.apache.log4j.spi.LoggingEvent; /**

PatternConverter is an abtract class that provides the formatting functionality that derived classes need.

Conversion specifiers in a conversion patterns are parsed to individual PatternConverters. Each of which is responsible for converting a logging event in a converter specific manner. @author James P. Cakalic @author Ceki Gülcü @since 0.8.2 */ public abstract class PatternConverter { public PatternConverter next; int min = -1; int max = 0x7FFFFFFF; boolean leftAlign = false; protected PatternConverter() { } protected PatternConverter(FormattingInfo fi) { min = fi.min; max = fi.max; leftAlign = fi.leftAlign; } /** Derived pattern converters must override this method in order to convert conversion specifiers in the correct way. */ abstract protected String convert(LoggingEvent event); /** A template method for formatting in a converter specific way. */ public void format(StringBuffer sbuf, LoggingEvent e) { String s = convert(e); if(s == null) { if(0 < min) spacePad(sbuf, min); return; } int len = s.length(); if(len > max) sbuf.append(s.substring(len-max)); else if(len < min) { if(leftAlign) { sbuf.append(s); spacePad(sbuf, min-len); } else { spacePad(sbuf, min-len); sbuf.append(s); } } else sbuf.append(s); } static String[] SPACES = {" ", " ", " ", " ", //1,2,4,8 spaces " ", // 16 spaces " " }; // 32 spaces /** Fast space padding method. */ public void spacePad(StringBuffer sbuf, int length) { while(length >= 32) { sbuf.append(SPACES[5]); length -= 32; } for(int i = 4; i >= 0; i--) { if((length & (1<resource in different places. The search order is as follows:

  1. Search for resource using the thread context class loader under Java2. If that fails, search for resource using the class loader that loaded this class (Loader). Under JDK 1.1, only the the class loader that loaded this class (Loader) is used.

  2. Try one last time with ClassLoader.getSystemResource(resource), that is is using the system class loader in JDK 1.2 and virtual machine's built-in class loader in JDK 1.1.
*/ static public URL getResource(String resource) { ClassLoader classLoader = null; URL url = null; try { if(!java1 && !ignoreTCL) { classLoader = getTCL(); if(classLoader != null) { LogLog.debug("Trying to find ["+resource+"] using context classloader " +classLoader+"."); url = classLoader.getResource(resource); if(url != null) { return url; } } } // We could not find resource. Ler us now try with the // classloader that loaded this class. classLoader = Loader.class.getClassLoader(); if(classLoader != null) { LogLog.debug("Trying to find ["+resource+"] using "+classLoader +" class loader."); url = classLoader.getResource(resource); if(url != null) { return url; } } } catch(IllegalAccessException t) { LogLog.warn(TSTR, t); } catch(InvocationTargetException t) { if (t.getTargetException() instanceof InterruptedException || t.getTargetException() instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.warn(TSTR, t); } catch(Throwable t) { // // can't be InterruptedException or InterruptedIOException // since not declared, must be error or RuntimeError. LogLog.warn(TSTR, t); } // Last ditch attempt: get the resource from the class path. It // may be the case that clazz was loaded by the Extentsion class // loader which the parent of the system class loader. Hence the // code below. LogLog.debug("Trying to find ["+resource+ "] using ClassLoader.getSystemResource()."); return ClassLoader.getSystemResource(resource); } /** Are we running under JDK 1.x? */ public static boolean isJava1() { return java1; } /** * Get the Thread Context Loader which is a JDK 1.2 feature. If we * are running under JDK 1.1 or anything else goes wrong the method * returns null. * * */ private static ClassLoader getTCL() throws IllegalAccessException, InvocationTargetException { // Are we running on a JDK 1.2 or later system? Method method = null; try { method = Thread.class.getMethod("getContextClassLoader", null); } catch (NoSuchMethodException e) { // We are running on JDK 1.1 return null; } return (ClassLoader) method.invoke(Thread.currentThread(), null); } /** * If running under JDK 1.2 load the specified class using the * Thread contextClassLoader if that * fails try Class.forname. Under JDK 1.1 only Class.forName is * used. * */ static public Class loadClass (String clazz) throws ClassNotFoundException { // Just call Class.forName(clazz) if we are running under JDK 1.1 // or if we are instructed to ignore the TCL. if(java1 || ignoreTCL) { return Class.forName(clazz); } else { try { return getTCL().loadClass(clazz); } // we reached here because tcl was null or because of a // security exception, or because clazz could not be loaded... // In any case we now try one more time catch(InvocationTargetException e) { if (e.getTargetException() instanceof InterruptedException || e.getTargetException() instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } } catch(Throwable t) { } } return Class.forName(clazz); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/LogSF.java0000755000175000017500000015636411751454711023314 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.spi.LoggingEvent; import java.util.ResourceBundle; /** * This class provides parameterized logging services * using the SLF4J pattern syntax. *

* Message formatting is only performed when the * request exceeds the threshold level of the logger. * * @since 1.2.16 * */ public final class LogSF extends LogXF { /** * private constructor. * */ private LogSF() { } /** * Formats arguments using SLF4J-like formatter. * @param pattern pattern, may be malformed. * @param arguments arguments. * @return Message string */ private static String format(final String pattern, final Object[] arguments) { if (pattern != null) { String retval = ""; int count = 0; int prev = 0; int pos = pattern.indexOf("{"); while(pos >= 0) { if (pos == 0 || pattern.charAt(pos-1) != '\\') { retval += pattern.substring(prev, pos); if (pos + 1 < pattern.length() && pattern.charAt(pos+1) == '}') { if(arguments != null && count < arguments.length) { retval += arguments[count++]; } else { retval += "{}"; } prev = pos + 2; } else { retval += "{"; prev = pos + 1; } } else { retval += pattern.substring(prev, pos - 1) + "{"; prev = pos + 1; } pos = pattern.indexOf("{", prev); } return retval + pattern.substring(prev); } return null; } /** * Formats arguments using MessageFormat. * @param pattern pattern, may be malformed. * @param arg0 argument, may be null or mismatched. * @return Message string */ private static String format(final String pattern, final Object arg0) { if (pattern != null) { // // if there is an escaped brace, delegate to multi-param formatter if (pattern.indexOf("\\{") >= 0) { return format(pattern, new Object[] { arg0 }); } int pos = pattern.indexOf("{}"); if (pos >= 0) { return pattern.substring(0, pos) + arg0 + pattern.substring(pos+2); } } return pattern; } /** * Formats arguments using MessageFormat using a pattern from * a resource bundle. * @param resourceBundleName name of resource bundle, may be null. * @param key key for pattern in resource bundle, may be null. * @param arguments arguments, may be null or mismatched. * @return Message string or null */ private static String format( final String resourceBundleName, final String key, final Object[] arguments) { String pattern; if (resourceBundleName != null) { try { ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName); pattern = bundle.getString(key); } catch (Exception ex) { pattern = key; } } else { pattern = key; } return format(pattern, arguments); } /** * Fully Qualified Class Name of this class. */ private static final String FQCN = LogSF.class.getName(); /** * Equivalent of Logger.forcedLog. * * @param logger logger, may not be null. * @param level level, may not be null. * @param msg message, may be null. */ private static void forcedLog(final Logger logger, final Level level, final String msg) { logger.callAppenders(new LoggingEvent(FQCN, logger, level, msg, null)); } /** * Equivalent of Logger.forcedLog. * * @param logger logger, may not be null. * @param level level, may not be null. * @param msg message, may be null. * @param t throwable. */ private static void forcedLog(final Logger logger, final Level level, final String msg, final Throwable t) { logger.callAppenders(new LoggingEvent(FQCN, logger, level, msg, t)); } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be * formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final Object[] arguments) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, arguments)); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final Object[] arguments) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, arguments)); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final Object[] arguments) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, arguments)); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final Object[] arguments) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, arguments)); } } /** * Log a parameterized message at error level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void error(final Logger logger, final String pattern, final Object[] arguments) { if (logger.isEnabledFor(Level.ERROR)) { forcedLog(logger, Level.ERROR, format(pattern, arguments)); } } /** * Log a parameterized message at fatal level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void fatal(final Logger logger, final String pattern, final Object[] arguments) { if (logger.isEnabledFor(Level.FATAL)) { forcedLog(logger, Level.FATAL, format(pattern, arguments)); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param t throwable, may be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be * formatted and substituted. */ public static void trace(final Logger logger, final Throwable t, final String pattern, final Object[] arguments) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, arguments), t); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param t throwable, may be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void debug(final Logger logger, final Throwable t, final String pattern, final Object[] arguments) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, arguments), t); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param t throwable, may be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void info(final Logger logger, final Throwable t, final String pattern, final Object[] arguments) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, arguments), t); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param t throwable, may be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void warn(final Logger logger, final Throwable t, final String pattern, final Object[] arguments) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, arguments), t); } } /** * Log a parameterized message at error level. * @param logger logger, may not be null. * @param t throwable, may be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void error(final Logger logger, final Throwable t, final String pattern, final Object[] arguments) { if (logger.isEnabledFor(Level.ERROR)) { forcedLog(logger, Level.ERROR, format(pattern, arguments), t); } } /** * Log a parameterized message at fatal level. * @param logger logger, may not be null. * @param t throwable, may be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void fatal(final Logger logger, final Throwable t, final String pattern, final Object[] arguments) { if (logger.isEnabledFor(Level.FATAL)) { forcedLog(logger, Level.FATAL, format(pattern, arguments), t); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final boolean argument) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final char argument) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final byte argument) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final short argument) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final int argument) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final long argument) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final float argument) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final double argument) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final Object argument) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, argument)); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final Object arg0, final Object arg1) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, toArray(arg0, arg1))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final Object arg0, final Object arg1, final Object arg2) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, toArray(arg0, arg1, arg2))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. * @param arg3 a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final Object arg0, final Object arg1, final Object arg2, final Object arg3) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, toArray(arg0, arg1, arg2, arg3))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final boolean argument) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final char argument) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final byte argument) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final short argument) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final int argument) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final long argument) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final float argument) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final double argument) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final Object argument) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, argument)); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final Object arg0, final Object arg1) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, toArray(arg0, arg1))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final Object arg0, final Object arg1, final Object arg2) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, toArray(arg0, arg1, arg2))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. * @param arg3 a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final Object arg0, final Object arg1, final Object arg2, final Object arg3) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, toArray(arg0, arg1, arg2, arg3))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final boolean argument) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final char argument) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final byte argument) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final short argument) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final int argument) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final long argument) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final float argument) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final double argument) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final Object argument) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, argument)); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final Object arg0, final Object arg1) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, toArray(arg0, arg1))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final Object arg0, final Object arg1, final Object arg2) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, toArray(arg0, arg1, arg2))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. * @param arg3 a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final Object arg0, final Object arg1, final Object arg2, final Object arg3) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, toArray(arg0, arg1, arg2, arg3))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final boolean argument) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final char argument) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final byte argument) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final short argument) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final int argument) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final long argument) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final float argument) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final double argument) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final Object argument) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, argument)); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final Object arg0, final Object arg1) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, toArray(arg0, arg1))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final Object arg0, final Object arg1, final Object arg2) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, toArray(arg0, arg1, arg2))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. * @param arg3 a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final Object arg0, final Object arg1, final Object arg2, final Object arg3) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, toArray(arg0, arg1, arg2, arg3))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param parameters parameters to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final Object[] parameters) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, parameters)); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param t throwable, may be null. * @param pattern pattern, may be null. * @param parameters parameters to the log message. */ public static void log(final Logger logger, final Level level, final Throwable t, final String pattern, final Object[] parameters) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, parameters), t); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param param1 parameter to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final Object param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(param1))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param param1 parameter to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final boolean param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(valueOf(param1)))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param param1 parameter to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final byte param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(valueOf(param1)))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param param1 parameter to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final char param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(valueOf(param1)))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param param1 parameter to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final short param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(valueOf(param1)))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param param1 parameter to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final int param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(valueOf(param1)))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param param1 parameter to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final long param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(valueOf(param1)))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param param1 parameter to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final float param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(valueOf(param1)))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param param1 parameter to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final double param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(valueOf(param1)))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. */ public static void log(final Logger logger, final Level level, final String pattern, final Object arg0, final Object arg1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(arg0, arg1))); } } /** * Log a parameterized message at specifed level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. */ public static void log(final Logger logger, final Level level, final String pattern, final Object arg0, final Object arg1, final Object arg2) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(arg0, arg1, arg2))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param level level, may not be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. * @param arg3 a value to be formatted and substituted. */ public static void log(final Logger logger, final Level level, final String pattern, final Object arg0, final Object arg1, final Object arg2, final Object arg3) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(arg0, arg1, arg2, arg3))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param parameters parameters to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final Object[] parameters) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, parameters)); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param t throwable, may be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param parameters parameters to the log message. */ public static void logrb(final Logger logger, final Level level, final Throwable t, final String bundleName, final String key, final Object[] parameters) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, parameters), t); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final Object param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(param1))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final boolean param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(valueOf(param1)))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final char param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(valueOf(param1)))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final byte param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(valueOf(param1)))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final short param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(valueOf(param1)))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final int param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(valueOf(param1)))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final long param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(valueOf(param1)))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final float param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(valueOf(param1)))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final double param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(valueOf(param1)))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param0 Parameter to the log message. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final Object param0, final Object param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(param0, param1))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param0 Parameter to the log message. * @param param1 Parameter to the log message. * @param param2 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final Object param0, final Object param1, final Object param2) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(param0, param1, param2))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param0 Parameter to the log message. * @param param1 Parameter to the log message. * @param param2 Parameter to the log message. * @param param3 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final Object param0, final Object param1, final Object param2, final Object param3) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(param0, param1, param2, param3))); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/RollingFileAppender.java0000644000175000017500000002103011751454711026201 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import java.io.IOException; import java.io.Writer; import java.io.File; import java.io.InterruptedIOException; import org.apache.log4j.helpers.OptionConverter; 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. The log4j extras companion includes alternatives which should be considered for new deployments and which are discussed in the documentation for org.apache.log4j.rolling.RollingFileAppender. @author Heinz Richter @author Ceki Gülcü */ public class RollingFileAppender extends FileAppender { /** The default maximum file size is 10MB. */ protected long maxFileSize = 10*1024*1024; /** There is one backup file by default. */ protected int maxBackupIndex = 1; private long nextRollover = 0; /** The default constructor simply calls its {@link FileAppender#FileAppender parents constructor}. */ public RollingFileAppender() { super(); } /** Instantiate a RollingFileAppender and open the file designated by filename. The opened filename will become the ouput destination for this appender.

If the append parameter is true, the file will be appended to. Otherwise, the file desginated by filename will be truncated before being opened. */ public RollingFileAppender(Layout layout, String filename, boolean append) throws IOException { super(layout, filename, append); } /** Instantiate a FileAppender and open the file designated by filename. The opened filename will become the output destination for this appender.

The file will be appended to. */ public RollingFileAppender(Layout layout, String filename) throws IOException { super(layout, filename); } /** Returns the value of the MaxBackupIndex option. */ public int getMaxBackupIndex() { return maxBackupIndex; } /** Get the maximum size that the output file is allowed to reach before being rolled over to backup files. @since 1.1 */ public long getMaximumFileSize() { return maxFileSize; } /** Implements the usual roll over behaviour.

If MaxBackupIndex is positive, then files {File.1, ..., File.MaxBackupIndex -1} are renamed to {File.2, ..., File.MaxBackupIndex}. Moreover, File is renamed File.1 and closed. A new File is created to receive further log output.

If MaxBackupIndex is equal to zero, then the File is truncated with no backup files created. */ public // synchronization not necessary since doAppend is alreasy synched void rollOver() { File target; File file; if (qw != null) { long size = ((CountingQuietWriter) qw).getCount(); LogLog.debug("rolling over count=" + size); // if operation fails, do not roll again until // maxFileSize more bytes are written nextRollover = size + maxFileSize; } LogLog.debug("maxBackupIndex="+maxBackupIndex); boolean renameSucceeded = true; // 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); if (file.exists()) renameSucceeded = file.delete(); // Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2} for (int i = maxBackupIndex - 1; i >= 1 && renameSucceeded; i--) { file = new File(fileName + "." + i); if (file.exists()) { target = new File(fileName + '.' + (i + 1)); LogLog.debug("Renaming file " + file + " to " + target); renameSucceeded = file.renameTo(target); } } if(renameSucceeded) { // Rename fileName to fileName.1 target = new File(fileName + "." + 1); this.closeFile(); // keep windows happy. file = new File(fileName); LogLog.debug("Renaming file " + file + " to " + target); renameSucceeded = file.renameTo(target); // // if file rename failed, reopen file with append = true // if (!renameSucceeded) { try { this.setFile(fileName, true, bufferedIO, bufferSize); } catch(IOException e) { if (e instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.error("setFile("+fileName+", true) call failed.", e); } } } } // // if all renames were successful, then // if (renameSucceeded) { try { // This will also close the file. This is OK since multiple // close operations are safe. this.setFile(fileName, false, bufferedIO, bufferSize); nextRollover = 0; } catch(IOException e) { if (e instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.error("setFile("+fileName+", false) call failed.", e); } } } public synchronized void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize) throws IOException { super.setFile(fileName, append, this.bufferedIO, this.bufferSize); if(append) { File f = new File(fileName); ((CountingQuietWriter) qw).setCount(f.length()); } } /** Set the maximum number of backup files to keep around.

The MaxBackupIndex 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 backup files and the log file will be truncated when it reaches MaxFileSize. */ public void setMaxBackupIndex(int maxBackups) { this.maxBackupIndex = maxBackups; } /** Set the maximum size that the output file is allowed to reach before being rolled over to backup files.

This method is equivalent to {@link #setMaxFileSize} except that it is required for differentiating the setter taking a long argument from the setter taking a String argument by the JavaBeans {@link java.beans.Introspector Introspector}. @see #setMaxFileSize(String) */ public void setMaximumFileSize(long maxFileSize) { this.maxFileSize = maxFileSize; } /** Set the maximum size that the output file is allowed to reach before being rolled over to backup files.

In configuration files, the MaxFileSize 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 interpreted being expressed respectively in kilobytes, megabytes or gigabytes. For example, the value "10KB" will be interpreted as 10240. */ public void setMaxFileSize(String value) { maxFileSize = OptionConverter.toFileSize(value, maxFileSize + 1); } protected void setQWForFiles(Writer writer) { this.qw = new CountingQuietWriter(writer, errorHandler); } /** This method differentiates RollingFileAppender from its super class. @since 0.9.0 */ protected void subAppend(LoggingEvent event) { super.subAppend(event); if(fileName != null && qw != null) { long size = ((CountingQuietWriter) qw).getCount(); if (size >= maxFileSize && size >= nextRollover) { rollOver(); } } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/0000755000175000017500000000000012126647422022143 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/LogRecord.java0000644000175000017500000002626511751454705024704 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; /** * LogRecord. A LogRecord encapsulates the details of your desired log * request. * * @author Michael J. Sikorsky * @author Robert Shaw */ // Contributed by ThoughtWorks Inc. public abstract class LogRecord implements java.io.Serializable { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected static long _seqCount = 0; protected LogLevel _level; protected String _message; protected long _sequenceNumber; protected long _millis; protected String _category; protected String _thread; protected String _thrownStackTrace; protected Throwable _thrown; protected String _ndc; protected String _location; //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public LogRecord() { super(); _millis = System.currentTimeMillis(); _category = "Debug"; _message = ""; _level = LogLevel.INFO; _sequenceNumber = getNextId(); _thread = Thread.currentThread().toString(); _ndc = ""; _location = ""; } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** * Get the level of this LogRecord. * * @return The LogLevel of this record. * @see #setLevel(LogLevel) * @see LogLevel */ public LogLevel getLevel() { return (_level); } /** * Set the level of this LogRecord. * * @param level The LogLevel for this record. * @see #getLevel() * @see LogLevel */ public void setLevel(LogLevel level) { _level = level; } /** * Abstract method. Must be overridden to indicate what log level * to show in red. */ public abstract boolean isSevereLevel(); /** * @return true if getThrown().toString() is a non-empty string. */ public boolean hasThrown() { Throwable thrown = getThrown(); if (thrown == null) { return false; } String thrownString = thrown.toString(); return thrownString != null && thrownString.trim().length() != 0; } /** * @return true if isSevereLevel() or hasThrown() returns true. */ public boolean isFatal() { return isSevereLevel() || hasThrown(); } /** * Get the category asscociated with this LogRecord. For a more detailed * description of what a category is see setCategory(). * * @return The category of this record. * @see #setCategory(String) */ public String getCategory() { return (_category); } /** * Set the category associated with this LogRecord. A category represents * a hierarchical dot (".") separated namespace for messages. * The definition of a category is application specific, but a common convention * is as follows: * *

* When logging messages * for a particluar class you can use its class name: * com.thoughtworks.framework.servlet.ServletServiceBroker.

* Futhermore, to log a message for a particular method in a class * add the method name: * com.thoughtworks.framework.servlet.ServletServiceBroker.init(). *

* * @param category The category for this record. * @see #getCategory() */ public void setCategory(String category) { _category = category; } /** * Get the message asscociated with this LogRecord. * * @return The message of this record. * @see #setMessage(String) */ public String getMessage() { return (_message); } /** * Set the message associated with this LogRecord. * * @param message The message for this record. * @see #getMessage() */ public void setMessage(String message) { _message = message; } /** * Get the sequence number associated with this LogRecord. Sequence numbers * are generally assigned when a LogRecord is constructed. Sequence numbers * start at 0 and increase with each newly constructed LogRocord. * * @return The sequence number of this record. * @see #setSequenceNumber(long) */ public long getSequenceNumber() { return (_sequenceNumber); } /** * Set the sequence number assocsiated with this LogRecord. A sequence number * will automatically be assigned to evey newly constructed LogRecord, however, * this method can override the value. * * @param number The sequence number. * @see #getSequenceNumber() */ public void setSequenceNumber(long number) { _sequenceNumber = number; } /** * Get the event time of this record in milliseconds from 1970. * When a LogRecord is constructed the event time is set but may be * overridden by calling setMillis(); * * @return The event time of this record in milliseconds from 1970. * @see #setMillis(long) */ public long getMillis() { return _millis; } /** * Set the event time of this record. When a LogRecord is constructed * the event time is set but may be overridden by calling this method. * * @param millis The time in milliseconds from 1970. * @see #getMillis() */ public void setMillis(long millis) { _millis = millis; } /** * Get the thread description asscociated with this LogRecord. When a * LogRecord is constructed, the thread description is set by calling: * Thread.currentThread().toString(). You may supply a thread description * of your own by calling the setThreadDescription(String) method. * * @return The thread description of this record. * @see #setThreadDescription(String) */ public String getThreadDescription() { return (_thread); } /** * Set the thread description associated with this LogRecord. When a * LogRecord is constructed, the thread description is set by calling: * Thread.currentThread().toString(). You may supply a thread description * of your own by calling this method. * * @param threadDescription The description of the thread for this record. * @see #getThreadDescription() */ public void setThreadDescription(String threadDescription) { _thread = threadDescription; } /** * Get the stack trace in a String-based format for the associated Throwable * of this LogRecord. The stack trace in a String-based format is set * when the setThrown(Throwable) method is called. * *

* Why do we need this method considering that we * have the getThrown() and setThrown() methods? * A Throwable object may not be serializable, however, a String representation * of it is. Users of LogRecords should generally call this method over * getThrown() for the reasons of serialization. *

* * @return The Stack Trace for the asscoiated Throwable of this LogRecord. * @see #setThrown(Throwable) * @see #getThrown() */ public String getThrownStackTrace() { return (_thrownStackTrace); } /** * Set the ThrownStackTrace for the log record. * * @param trace A String to associate with this LogRecord * @see #getThrownStackTrace() */ public void setThrownStackTrace(String trace) { _thrownStackTrace = trace; } /** * Get the Throwable associated with this LogRecord. * * @return The LogLevel of this record. * @see #setThrown(Throwable) * @see #getThrownStackTrace() */ public Throwable getThrown() { return (_thrown); } /** * Set the Throwable associated with this LogRecord. When this method * is called, the stack trace in a String-based format is made * available via the getThrownStackTrace() method. * * @param thrown A Throwable to associate with this LogRecord. * @see #getThrown() * @see #getThrownStackTrace() */ public void setThrown(Throwable thrown) { if (thrown == null) { return; } _thrown = thrown; StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); thrown.printStackTrace(out); out.flush(); _thrownStackTrace = sw.toString(); try { out.close(); sw.close(); } catch (IOException e) { // Do nothing, this should not happen as it is StringWriter. } out = null; sw = null; } /** * Return a String representation of this LogRecord. */ public String toString() { StringBuffer buf = new StringBuffer(); buf.append("LogRecord: [" + _level + ", " + _message + "]"); return (buf.toString()); } /** * Get the NDC (nested diagnostic context) for this record. * * @return The string representing the NDC. */ public String getNDC() { return _ndc; } /** * Set the NDC (nested diagnostic context) for this record. * * @param ndc A string representing the NDC. */ public void setNDC(String ndc) { _ndc = ndc; } /** * Get the location in code where this LogRecord originated. * * @return The string containing the location information. */ public String getLocation() { return _location; } /** * Set the location in code where this LogRecord originated. * * @param location A string containing location information. */ public void setLocation(String location) { _location = location; } /** * Resets that sequence number to 0. * */ public static synchronized void resetSequenceNumber() { _seqCount = 0; } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- protected static synchronized long getNextId() { _seqCount++; return _seqCount; } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/Log4JLogRecord.java0000644000175000017500000000777411751454705025550 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5; import org.apache.log4j.spi.ThrowableInformation; /** * A Log4JLogRecord encapsulates * the details of your log4j LoggingEvent in a format usable * by the LogBrokerMonitor. * * @author Brent Sprecher */ // Contributed by ThoughtWorks Inc. public class Log4JLogRecord extends LogRecord { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- /** * Constructs an instance of a Log4JLogRecord. */ public Log4JLogRecord() { } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** * Determines which Priority levels will * be displayed in colored font when the LogMonitorAppender * renders this log message. By default, messages will be colored * red if they are of Priority ERROR or FATAL. * * @return true if the log level is ERROR or FATAL. */ public boolean isSevereLevel() { boolean isSevere = false; if (LogLevel.ERROR.equals(getLevel()) || LogLevel.FATAL.equals(getLevel())) { isSevere = true; } return isSevere; } /** * Set stack trace information associated with this Log4JLogRecord. * When this method is called, the stack trace in a * String-based format is made * available via the getThrownStackTrace() method. * * @param throwableInfo An org.apache.log4j.spi.ThrowableInformation to * associate with this Log4JLogRecord. * @see #getThrownStackTrace() */ public void setThrownStackTrace(ThrowableInformation throwableInfo) { String[] stackTraceArray = throwableInfo.getThrowableStrRep(); StringBuffer stackTrace = new StringBuffer(); String nextLine; for (int i = 0; i < stackTraceArray.length; i++) { nextLine = stackTraceArray[i] + "\n"; stackTrace.append(nextLine); } _thrownStackTrace = stackTrace.toString(); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/DefaultLF5Configurator.java0000644000175000017500000001070311751454705027270 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5; import java.io.IOException; import java.io.InputStream; import java.net.URL; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.spi.Configurator; import org.apache.log4j.spi.LoggerRepository; /** * The DefaultLF5Configurator provides a default * configuration for the LF5Appender. * * Note: The preferred method for configuring a LF5Appender * is to use the LF5Manager class. This class ensures * that configuration does not occur multiple times, and improves system * performance. Reconfiguring the monitor multiple times can result in * unexpected behavior. * * @author Brent Sprecher */ // Contributed by ThoughtWorks Inc. public class DefaultLF5Configurator implements Configurator { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- /** * This class should never be instantiated! It implements the * Configurator * interface, but does not provide the same functionality as full * configurator class. */ private DefaultLF5Configurator() { } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** * This method configures the LF5Appender using a * default configuration file. The default configuration file is * defaultconfig.properties. * @throws java.io.IOException */ public static void configure() throws IOException { String resource = "/org/apache/log4j/lf5/config/defaultconfig.properties"; URL configFileResource = DefaultLF5Configurator.class.getResource(resource); if (configFileResource != null) { PropertyConfigurator.configure(configFileResource); } else { throw new IOException("Error: Unable to open the resource" + resource); } } /** * This is a dummy method that will throw an * IllegalStateException if used. * * @since 1.2.17 */ public void doConfigure(InputStream inputStream, LoggerRepository repository) { throw new IllegalStateException("This class should NOT be instantiated!"); } /** * This is a dummy method that will throw an * IllegalStateException if used. */ public void doConfigure(URL configURL, LoggerRepository repository) { throw new IllegalStateException("This class should NOT be instantiated!"); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- }apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/LogLevelFormatException.java0000644000175000017500000000524411751454705027557 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5; /** * Thrown to indicate that the client has attempted to convert a string * to one the LogLevel types, but the string does not have the appropriate * format. * * @author Michael J. Sikorsky< * @author Robert Shaw */ // Contributed by ThoughtWorks Inc. public class LogLevelFormatException extends Exception { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public LogLevelFormatException(String message) { super(message); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/AppenderFinalizer.java0000644000175000017500000000601211751454705026412 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5; import org.apache.log4j.lf5.viewer.LogBrokerMonitor; /** * AppenderFinalizer has a single method that will finalize * resources associated with a LogBrokerMonitor in the event * that the LF5Appender class is destroyed, and the class loader * is garbage collected. * * @author Brent Sprecher */ // Contributed by ThoughtWorks Inc. public class AppenderFinalizer { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected LogBrokerMonitor _defaultMonitor = null; //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public AppenderFinalizer(LogBrokerMonitor defaultMonitor) { _defaultMonitor = defaultMonitor; } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- /** * @throws java.lang.Throwable */ protected void finalize() throws Throwable { System.out.println("Disposing of the default LogBrokerMonitor instance"); _defaultMonitor.dispose(); } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- }apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/StartLogFactor5.java0000644000175000017500000000567011751454705026004 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5; import org.apache.log4j.lf5.viewer.LogBrokerMonitor; /** * Starts an instance of the LogFactor5 console for off-line viewing. * * @author Brad Marlborough * @author Richard Hurst */ // Contributed by ThoughtWorks Inc. public class StartLogFactor5 { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** * Main - starts a an instance of the LogFactor5 console and configures * the console settings. */ public final static void main(String[] args) { LogBrokerMonitor monitor = new LogBrokerMonitor( LogLevel.getLog4JLevels()); monitor.setFrameSize(LF5Appender.getDefaultMonitorWidth(), LF5Appender.getDefaultMonitorHeight()); monitor.setFontSize(12); monitor.show(); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/util/0000755000175000017500000000000012126647422023120 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/util/Resource.java0000644000175000017500000001042711751454705025561 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.util; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; /** * Resource encapsulates access to Resources via the Classloader. * * @author Michael J. Sikorsky * @author Robert Shaw */ // Contributed by ThoughtWorks Inc. public class Resource { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected String _name; //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- /** * Default, no argument constructor. */ public Resource() { super(); } /** * Construct a Resource given a name. * * @see #setName(String) */ public Resource(String name) { _name = name; } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** * Set the name of the resource. *

* A resource is some data (images, audio, text, etc) that can be accessed * by class code in a way that is independent of the location of the code. *

*

* The name of a resource is a "/"-separated path name that identifies * the resource. *

* * @see #getName() */ public void setName(String name) { _name = name; } /** * Get the name of the resource. Set setName() for a description of * a resource. * * @see #setName */ public String getName() { return (_name); } /** * Get the InputStream for this Resource. Uses the classloader * from this Resource. * * @see #getInputStreamReader * @see ResourceUtils */ public InputStream getInputStream() { InputStream in = ResourceUtils.getResourceAsStream(this, this); return (in); } /** * Get the InputStreamReader for this Resource. Uses the classloader from * this Resource. * * @see #getInputStream * @see ResourceUtils */ public InputStreamReader getInputStreamReader() { InputStream in = ResourceUtils.getResourceAsStream(this, this); if (in == null) { return null; } InputStreamReader reader = new InputStreamReader(in); return reader; } /** * Get the URL of the Resource. Uses the classloader from this Resource. * * @see ResourceUtils */ public URL getURL() { return (ResourceUtils.getResourceAsURL(this, this)); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/util/AdapterLogRecord.java0000644000175000017500000000751611751454705027160 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.util; import org.apache.log4j.lf5.LogLevel; import org.apache.log4j.lf5.LogRecord; import java.io.PrintWriter; import java.io.StringWriter; /** *

A LogRecord to be used with the LogMonitorAdapter

* * @author Richard Hurst */ // Contributed by ThoughtWorks Inc. public class AdapterLogRecord extends LogRecord { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- private static LogLevel severeLevel = null; private static StringWriter sw = new StringWriter(); private static PrintWriter pw = new PrintWriter(sw); //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public AdapterLogRecord() { super(); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public void setCategory(String category) { super.setCategory(category); super.setLocation(getLocationInfo(category)); } public boolean isSevereLevel() { if (severeLevel == null) return false; return severeLevel.equals(getLevel()); } public static void setSevereLevel(LogLevel level) { severeLevel = level; } public static LogLevel getSevereLevel() { return severeLevel; } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- protected String getLocationInfo(String category) { String stackTrace = stackTraceToString(new Throwable()); String line = parseLine(stackTrace, category); return line; } protected String stackTraceToString(Throwable t) { String s = null; synchronized (sw) { t.printStackTrace(pw); s = sw.toString(); sw.getBuffer().setLength(0); } return s; } protected String parseLine(String trace, String category) { int index = trace.indexOf(category); if (index == -1) return null; trace = trace.substring(index); trace = trace.substring(0, trace.indexOf(")") + 1); return trace; } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/util/StreamUtils.java0000644000175000017500000001011211751454705026235 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Provides utility methods for input and output streams. * * @author Richard Wan */ // Contributed by ThoughtWorks Inc. public abstract class StreamUtils { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- /** * Default value is 2048. */ public static final int DEFAULT_BUFFER_SIZE = 2048; //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** * Copies information from the input stream to the output stream using * a default buffer size of 2048 bytes. * @throws java.io.IOException */ public static void copy(InputStream input, OutputStream output) throws IOException { copy(input, output, DEFAULT_BUFFER_SIZE); } /** * Copies information from the input stream to the output stream using * the specified buffer size * @throws java.io.IOException */ public static void copy(InputStream input, OutputStream output, int bufferSize) throws IOException { byte[] buf = new byte[bufferSize]; int bytesRead = input.read(buf); while (bytesRead != -1) { output.write(buf, 0, bytesRead); bytesRead = input.read(buf); } output.flush(); } /** * Copies information between specified streams and then closes * both of the streams. * @throws java.io.IOException */ public static void copyThenClose(InputStream input, OutputStream output) throws IOException { copy(input, output); input.close(); output.close(); } /** * @return a byte[] containing the information contained in the * specified InputStream. * @throws java.io.IOException */ public static byte[] getBytes(InputStream input) throws IOException { ByteArrayOutputStream result = new ByteArrayOutputStream(); copy(input, result); result.close(); return result.toByteArray(); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/util/LogFileParser.java0000644000175000017500000002153411751454705026471 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.util; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.SwingUtilities; import org.apache.log4j.lf5.Log4JLogRecord; import org.apache.log4j.lf5.LogLevel; import org.apache.log4j.lf5.LogLevelFormatException; import org.apache.log4j.lf5.LogRecord; import org.apache.log4j.lf5.viewer.LogBrokerMonitor; import org.apache.log4j.lf5.viewer.LogFactor5ErrorDialog; import org.apache.log4j.lf5.viewer.LogFactor5LoadingDialog; /** * Provides utility methods for input and output streams. * * @author Brad Marlborough * @author Richard Hurst */ // Contributed by ThoughtWorks Inc. public class LogFileParser implements Runnable { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- public static final String RECORD_DELIMITER = "[slf5s.start]"; public static final String ATTRIBUTE_DELIMITER = "[slf5s."; public static final String DATE_DELIMITER = ATTRIBUTE_DELIMITER + "DATE]"; public static final String THREAD_DELIMITER = ATTRIBUTE_DELIMITER + "THREAD]"; public static final String CATEGORY_DELIMITER = ATTRIBUTE_DELIMITER + "CATEGORY]"; public static final String LOCATION_DELIMITER = ATTRIBUTE_DELIMITER + "LOCATION]"; public static final String MESSAGE_DELIMITER = ATTRIBUTE_DELIMITER + "MESSAGE]"; public static final String PRIORITY_DELIMITER = ATTRIBUTE_DELIMITER + "PRIORITY]"; public static final String NDC_DELIMITER = ATTRIBUTE_DELIMITER + "NDC]"; //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- private static SimpleDateFormat _sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss,S"); private LogBrokerMonitor _monitor; LogFactor5LoadingDialog _loadDialog; private InputStream _in = null; //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public LogFileParser(File file) throws IOException, FileNotFoundException { this(new FileInputStream(file)); } public LogFileParser(InputStream stream) throws IOException { _in = stream; } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** * Starts a new thread to parse the log file and create a LogRecord. * See run(). * @param monitor LogBrokerMonitor */ public void parse(LogBrokerMonitor monitor) throws RuntimeException { _monitor = monitor; Thread t = new Thread(this); t.start(); } /** * Parses the file and creates new log records and adds the record * to the monitor. */ public void run() { int index = 0; int counter = 0; LogRecord temp; boolean isLogFile = false; _loadDialog = new LogFactor5LoadingDialog( _monitor.getBaseFrame(), "Loading file..."); try { String logRecords = loadLogFile(_in); while ((counter = logRecords.indexOf(RECORD_DELIMITER, index)) != -1) { temp = createLogRecord(logRecords.substring(index, counter)); isLogFile = true; if (temp != null) { _monitor.addMessage(temp); } index = counter + RECORD_DELIMITER.length(); } if (index < logRecords.length() && isLogFile) { temp = createLogRecord(logRecords.substring(index)); if (temp != null) { _monitor.addMessage(temp); } } if (isLogFile == false) { throw new RuntimeException("Invalid log file format"); } SwingUtilities.invokeLater(new Runnable() { public void run() { destroyDialog(); } }); } catch (RuntimeException e) { destroyDialog(); displayError("Error - Invalid log file format.\nPlease see documentation" + " on how to load log files."); } catch (IOException e) { destroyDialog(); displayError("Error - Unable to load log file!"); } _in = null; } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- protected void displayError(String message) { LogFactor5ErrorDialog error = new LogFactor5ErrorDialog( _monitor.getBaseFrame(), message); } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- private void destroyDialog() { _loadDialog.hide(); _loadDialog.dispose(); } /** * Loads a log file from a web server into the LogFactor5 GUI. */ private String loadLogFile(InputStream stream) throws IOException { BufferedInputStream br = new BufferedInputStream(stream); int count = 0; int size = br.available(); StringBuffer sb = null; if (size > 0) { sb = new StringBuffer(size); } else { sb = new StringBuffer(1024); } while ((count = br.read()) != -1) { sb.append((char) count); } br.close(); br = null; return sb.toString(); } private String parseAttribute(String name, String record) { int index = record.indexOf(name); if (index == -1) { return null; } return getAttribute(index, record); } private long parseDate(String record) { try { String s = parseAttribute(DATE_DELIMITER, record); if (s == null) { return 0; } Date d = _sdf.parse(s); return d.getTime(); } catch (ParseException e) { return 0; } } private LogLevel parsePriority(String record) { String temp = parseAttribute(PRIORITY_DELIMITER, record); if (temp != null) { try { return LogLevel.valueOf(temp); } catch (LogLevelFormatException e) { return LogLevel.DEBUG; } } return LogLevel.DEBUG; } private String parseThread(String record) { return parseAttribute(THREAD_DELIMITER, record); } private String parseCategory(String record) { return parseAttribute(CATEGORY_DELIMITER, record); } private String parseLocation(String record) { return parseAttribute(LOCATION_DELIMITER, record); } private String parseMessage(String record) { return parseAttribute(MESSAGE_DELIMITER, record); } private String parseNDC(String record) { return parseAttribute(NDC_DELIMITER, record); } private String parseThrowable(String record) { return getAttribute(record.length(), record); } private LogRecord createLogRecord(String record) { if (record == null || record.trim().length() == 0) { return null; } LogRecord lr = new Log4JLogRecord(); lr.setMillis(parseDate(record)); lr.setLevel(parsePriority(record)); lr.setCategory(parseCategory(record)); lr.setLocation(parseLocation(record)); lr.setThreadDescription(parseThread(record)); lr.setNDC(parseNDC(record)); lr.setMessage(parseMessage(record)); lr.setThrownStackTrace(parseThrowable(record)); return lr; } private String getAttribute(int index, String record) { int start = record.lastIndexOf(ATTRIBUTE_DELIMITER, index - 1); if (start == -1) { return record.substring(0, index); } start = record.indexOf("]", start); return record.substring(start + 1, index).trim(); } //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/util/ResourceUtils.java0000644000175000017500000001057311751454705026604 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.util; import java.io.InputStream; import java.net.URL; /** * ResourceUtils. Provide a set of convenience methods for working with * Resources. * * @see org.apache.log4j.lf5.util.Resource * * @author Michael J. Sikorsky * @author Robert Shaw */ // Contributed by ThoughtWorks Inc. public class ResourceUtils { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** * Get the InputStream for this resource. Note: to convert an InputStream * into an InputReader, use: new InputStreamReader(InputStream). * * @param object The object to grab the Classloader from. * This parameter is quite important from a * visibility of resources standpoint as the * hierarchy of Classloaders plays a role. * * @param resource The resource to load. * * @return If the Resource was found, the InputStream, otherwise null. * * @see Resource * @see #getResourceAsURL(Object,Resource) * @see InputStream */ public static InputStream getResourceAsStream(Object object, Resource resource) { ClassLoader loader = object.getClass().getClassLoader(); InputStream in = null; if (loader != null) { in = loader.getResourceAsStream(resource.getName()); } else { in = ClassLoader.getSystemResourceAsStream(resource.getName()); } return in; } /** * Get the URL for this resource. * * @param object The object to grab the Classloader from. * This parameter is quite important from a * visibility of resources standpoint as the * hierarchy of Classloaders plays a role. * * @param resource The resource to load. * * @return If the Resource was found, the URL, otherwise null. * * @see Resource * @see #getResourceAsStream(Object,Resource) */ public static URL getResourceAsURL(Object object, Resource resource) { ClassLoader loader = object.getClass().getClassLoader(); URL url = null; if (loader != null) { url = loader.getResource(resource.getName()); } else { url = ClassLoader.getSystemResource(resource.getName()); } return (url); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/util/LogMonitorAdapter.java0000644000175000017500000002166111751454705027366 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.util; import java.awt.Toolkit; import java.util.Arrays; import java.util.List; import org.apache.log4j.lf5.LogLevel; import org.apache.log4j.lf5.LogRecord; import org.apache.log4j.lf5.viewer.LogBrokerMonitor; /** *

LogMonitorAdapter facilitates the usage of the LogMonitor

* * @author Richard Hurst */ // Contributed by ThoughtWorks Inc. public class LogMonitorAdapter { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- public static final int LOG4J_LOG_LEVELS = 0; public static final int JDK14_LOG_LEVELS = 1; //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- private LogBrokerMonitor _logMonitor; private LogLevel _defaultLevel = null; //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- private LogMonitorAdapter(List userDefinedLevels) { super(); // set the default level to be the first entry in the list _defaultLevel = (LogLevel) userDefinedLevels.get(0); _logMonitor = new LogBrokerMonitor(userDefinedLevels); _logMonitor.setFrameSize(getDefaultMonitorWidth(), getDefaultMonitorHeight()); _logMonitor.setFontSize(12); _logMonitor.show(); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** *

Creates an instance of LogMonitorAdapter using the * log levels inticated by the parameter. Log4J and JDK1.4 both have default * LogLevels which are set but these levels can be overriden.

* * @param loglevels An integer representing either Log4J or JDK1.4 logging levels * @return LogMonitorAdapter */ public static LogMonitorAdapter newInstance(int loglevels) { LogMonitorAdapter adapter; if (loglevels == JDK14_LOG_LEVELS) { adapter = newInstance(LogLevel.getJdk14Levels()); adapter.setDefaultLevel(LogLevel.FINEST); adapter.setSevereLevel(LogLevel.SEVERE); } else { adapter = newInstance(LogLevel.getLog4JLevels()); adapter.setDefaultLevel(LogLevel.DEBUG); adapter.setSevereLevel(LogLevel.FATAL); } return adapter; } /** *

Creates an instance of LogMonitorAdapter using the specified LogLevels. * The first LogLevel in the array is used as the default LogLevel unless * changed using the setDefaultLevel method.

* * @param userDefined An array of user defined LogLevel objects. * @return LogMonitorAdapter */ public static LogMonitorAdapter newInstance(LogLevel[] userDefined) { if (userDefined == null) { return null; } return newInstance(Arrays.asList(userDefined)); } /** *

Creates an instance of LogMonitorAdapter using the specified LogLevels. * The first LogLevel in the List is used as the default LogLevel unless * changed using the setDefaultLevel method.

* * @param userDefinedLevels A list of user defined LogLevel objects. * @return LogMonitorAdapter */ public static LogMonitorAdapter newInstance(List userDefinedLevels) { return new LogMonitorAdapter(userDefinedLevels); } /** *

Adds a LogRecord to the LogMonitor.

* * @param record The LogRecord object to be logged in the logging monitor. */ public void addMessage(LogRecord record) { _logMonitor.addMessage(record); } /** *

Set the maximum number of records to be displayed in the monitor

* * @param maxNumberOfRecords */ public void setMaxNumberOfRecords(int maxNumberOfRecords) { _logMonitor.setMaxNumberOfLogRecords(maxNumberOfRecords); } /** *

Set the default log level to be used when logging messages without * specifying a LogLevel.

* * @param level */ public void setDefaultLevel(LogLevel level) { _defaultLevel = level; } /** *

Gets the default LogLevel for the Adapter.

* * @return LogLevel */ public LogLevel getDefaultLevel() { return _defaultLevel; } /** *

Sets the Severe LogLevel.

* * @param level */ public void setSevereLevel(LogLevel level) { AdapterLogRecord.setSevereLevel(level); } /** *

Gets the current Severe LogLevel

* * @return LogLevel */ public LogLevel getSevereLevel() { return AdapterLogRecord.getSevereLevel(); } /** *

Log a complete message to the Monitor.

* * @param category The category to be used * @param level The log level to apply to the message * @param message The message * @param t The throwable content of the message * @param NDC The NDC really only applies to Log4J and the parameter can * usually be ignored. */ public void log(String category, LogLevel level, String message, Throwable t, String NDC) { AdapterLogRecord record = new AdapterLogRecord(); record.setCategory(category); record.setMessage(message); record.setNDC(NDC); record.setThrown(t); if (level == null) { record.setLevel(getDefaultLevel()); } else { record.setLevel(level); } addMessage(record); } /** *

Log a message to the Monitor and use the default LogLevel.

* * @param category The category to be used * @param message The message */ public void log(String category, String message) { log(category, null, message); } /** *

Log a message to the Monitor.

* * @param category The category to be used * @param level The log level to apply to the message * @param message The message * @param NDC */ public void log(String category, LogLevel level, String message, String NDC) { log(category, level, message, null, NDC); } /** *

Log a message to the Monitor.

* * @param category The category to be used * @param level The log level to apply to the message * @param message The message * @param t The throwable content of the message */ public void log(String category, LogLevel level, String message, Throwable t) { log(category, level, message, t, null); } /** *

Log a message to the Monitor.

* * @param category The category to be used * @param level The log level to apply to the message * @param message The message */ public void log(String category, LogLevel level, String message) { log(category, level, message, null, null); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- /** * @return the screen width from Toolkit.getScreenSize() * if possible, otherwise returns 800 * @see java.awt.Toolkit */ protected static int getScreenWidth() { try { return Toolkit.getDefaultToolkit().getScreenSize().width; } catch (Throwable t) { return 800; } } /** * @return the screen height from Toolkit.getScreenSize() * if possible, otherwise returns 600 * @see java.awt.Toolkit */ protected static int getScreenHeight() { try { return Toolkit.getDefaultToolkit().getScreenSize().height; } catch (Throwable t) { return 600; } } protected static int getDefaultMonitorWidth() { return (3 * getScreenWidth()) / 4; } protected static int getDefaultMonitorHeight() { return (3 * getScreenHeight()) / 4; } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/util/DateFormatManager.java0000644000175000017500000001521711751454705027315 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.util; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** * Date format manager. * Utility class to help manage consistent date formatting and parsing. * It may be advantageous to have multiple DateFormatManagers per * application. For example, one for handling the output (formatting) of * dates, and another one for handling the input (parsing) of dates. * * @author Robert Shaw * @author Michael J. Sikorsky */ // Contributed by ThoughtWorks Inc. public class DateFormatManager { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- private TimeZone _timeZone = null; private Locale _locale = null; private String _pattern = null; private DateFormat _dateFormat = null; //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public DateFormatManager() { super(); configure(); } public DateFormatManager(TimeZone timeZone) { super(); _timeZone = timeZone; configure(); } public DateFormatManager(Locale locale) { super(); _locale = locale; configure(); } public DateFormatManager(String pattern) { super(); _pattern = pattern; configure(); } public DateFormatManager(TimeZone timeZone, Locale locale) { super(); _timeZone = timeZone; _locale = locale; configure(); } public DateFormatManager(TimeZone timeZone, String pattern) { super(); _timeZone = timeZone; _pattern = pattern; configure(); } public DateFormatManager(Locale locale, String pattern) { super(); _locale = locale; _pattern = pattern; configure(); } public DateFormatManager(TimeZone timeZone, Locale locale, String pattern) { super(); _timeZone = timeZone; _locale = locale; _pattern = pattern; configure(); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public synchronized TimeZone getTimeZone() { if (_timeZone == null) { return TimeZone.getDefault(); } else { return _timeZone; } } public synchronized void setTimeZone(TimeZone timeZone) { _timeZone = timeZone; configure(); } public synchronized Locale getLocale() { if (_locale == null) { return Locale.getDefault(); } else { return _locale; } } public synchronized void setLocale(Locale locale) { _locale = locale; configure(); } public synchronized String getPattern() { return _pattern; } /** * Set the pattern. i.e. "EEEEE, MMMMM d, yyyy hh:mm aaa" */ public synchronized void setPattern(String pattern) { _pattern = pattern; configure(); } /** * This method has been deprecated in favour of getPattern(). * @deprecated Use getPattern(). */ public synchronized String getOutputFormat() { return _pattern; } /** * This method has been deprecated in favour of setPattern(). * @deprecated Use setPattern(). */ public synchronized void setOutputFormat(String pattern) { _pattern = pattern; configure(); } public synchronized DateFormat getDateFormatInstance() { return _dateFormat; } public synchronized void setDateFormatInstance(DateFormat dateFormat) { _dateFormat = dateFormat; // No reconfiguration necessary! } public String format(Date date) { return getDateFormatInstance().format(date); } public String format(Date date, String pattern) { DateFormat formatter = null; formatter = getDateFormatInstance(); if (formatter instanceof SimpleDateFormat) { formatter = (SimpleDateFormat) (formatter.clone()); ((SimpleDateFormat) formatter).applyPattern(pattern); } return formatter.format(date); } /** * @throws java.text.ParseException */ public Date parse(String date) throws ParseException { return getDateFormatInstance().parse(date); } /** * @throws java.text.ParseException */ public Date parse(String date, String pattern) throws ParseException { DateFormat formatter = null; formatter = getDateFormatInstance(); if (formatter instanceof SimpleDateFormat) { formatter = (SimpleDateFormat) (formatter.clone()); ((SimpleDateFormat) formatter).applyPattern(pattern); } return formatter.parse(date); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- private synchronized void configure() { _dateFormat = SimpleDateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, getLocale()); _dateFormat.setTimeZone(getTimeZone()); if (_pattern != null) { ((SimpleDateFormat) _dateFormat).applyPattern(_pattern); } } //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/0000755000175000017500000000000012126647422023444 5ustar tonytony././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/TrackingAdjustmentListener.javaapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/TrackingAdjustmentListener.jav0000644000175000017500000000675711751454705031477 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer; import java.awt.Adjustable; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; /** * An AdjustmentListener which ensures that an Adjustable (e.g. a Scrollbar) * will "track" when the Adjustable expands. * For example, when a vertical scroll bar is at its bottom anchor, * the scrollbar will remain at the bottom. When the vertical scroll bar * is at any other location, then no tracking will happen. * An instance of this class should only listen to one Adjustable as * it retains state information about the Adjustable it listens to. * * @author Richard Wan */ // Contributed by ThoughtWorks Inc. public class TrackingAdjustmentListener implements AdjustmentListener { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected int _lastMaximum = -1; //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public void adjustmentValueChanged(AdjustmentEvent e) { Adjustable bar = e.getAdjustable(); int currentMaximum = bar.getMaximum(); if (bar.getMaximum() == _lastMaximum) { return; // nothing to do, the adjustable has not expanded } int bottom = bar.getValue() + bar.getVisibleAmount(); if (bottom + bar.getUnitIncrement() >= _lastMaximum) { bar.setValue(bar.getMaximum()); // use the most recent maximum } _lastMaximum = currentMaximum; } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/0000755000175000017500000000000012126647422027042 5ustar tonytony././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryNode.javaapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryNode.0000644000175000017500000001264211751454705031436 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer.categoryexplorer; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeNode; import java.util.Enumeration; /** * CategoryNode * * @author Michael J. Sikorsky * @author Robert Shaw */ // Contributed by ThoughtWorks Inc. public class CategoryNode extends DefaultMutableTreeNode { private static final long serialVersionUID = 5958994817693177319L; //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected boolean _selected = true; protected int _numberOfContainedRecords = 0; protected int _numberOfRecordsFromChildren = 0; protected boolean _hasFatalChildren = false; protected boolean _hasFatalRecords = false; //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- /** * */ public CategoryNode(String title) { setUserObject(title); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public String getTitle() { return (String) getUserObject(); } public void setSelected(boolean s) { if (s != _selected) { _selected = s; } } public boolean isSelected() { return _selected; } /** * @deprecated */ public void setAllDescendantsSelected() { Enumeration children = children(); while (children.hasMoreElements()) { CategoryNode node = (CategoryNode) children.nextElement(); node.setSelected(true); node.setAllDescendantsSelected(); } } /** * @deprecated */ public void setAllDescendantsDeSelected() { Enumeration children = children(); while (children.hasMoreElements()) { CategoryNode node = (CategoryNode) children.nextElement(); node.setSelected(false); node.setAllDescendantsDeSelected(); } } public String toString() { return (getTitle()); } public boolean equals(Object obj) { if (obj instanceof CategoryNode) { CategoryNode node = (CategoryNode) obj; String tit1 = getTitle().toLowerCase(); String tit2 = node.getTitle().toLowerCase(); if (tit1.equals(tit2)) { return (true); } } return (false); } public int hashCode() { return (getTitle().hashCode()); } public void addRecord() { _numberOfContainedRecords++; addRecordToParent(); } public int getNumberOfContainedRecords() { return _numberOfContainedRecords; } public void resetNumberOfContainedRecords() { _numberOfContainedRecords = 0; _numberOfRecordsFromChildren = 0; _hasFatalRecords = false; _hasFatalChildren = false; } public boolean hasFatalRecords() { return _hasFatalRecords; } public boolean hasFatalChildren() { return _hasFatalChildren; } public void setHasFatalRecords(boolean flag) { _hasFatalRecords = flag; } public void setHasFatalChildren(boolean flag) { _hasFatalChildren = flag; } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- protected int getTotalNumberOfRecords() { return getNumberOfRecordsFromChildren() + getNumberOfContainedRecords(); } /** * Passes up the addition from child to parent */ protected void addRecordFromChild() { _numberOfRecordsFromChildren++; addRecordToParent(); } protected int getNumberOfRecordsFromChildren() { return _numberOfRecordsFromChildren; } protected void addRecordToParent() { TreeNode parent = getParent(); if (parent == null) { return; } ((CategoryNode) parent).addRecordFromChild(); } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryExplorerLogRecordFilter.javaapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryExplo0000644000175000017500000000716111751454705031562 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer.categoryexplorer; import org.apache.log4j.lf5.LogRecord; import org.apache.log4j.lf5.LogRecordFilter; import java.util.Enumeration; /** * An implementation of LogRecordFilter based on a CategoryExplorerModel * * @author Richard Wan */ // Contributed by ThoughtWorks Inc. public class CategoryExplorerLogRecordFilter implements LogRecordFilter { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected CategoryExplorerModel _model; //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public CategoryExplorerLogRecordFilter(CategoryExplorerModel model) { _model = model; } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** * @return true if the CategoryExplorer model specified at construction * is accepting the category of the specified LogRecord. Has a side-effect * of adding the CategoryPath of the LogRecord to the explorer model * if the CategoryPath is new. */ public boolean passes(LogRecord record) { CategoryPath path = new CategoryPath(record.getCategory()); return _model.isCategoryPathActive(path); } /** * Resets the counters for the contained CategoryNodes to zero. */ public void reset() { resetAllNodes(); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- protected void resetAllNodes() { Enumeration nodes = _model.getRootCategoryNode().depthFirstEnumeration(); CategoryNode current; while (nodes.hasMoreElements()) { current = (CategoryNode) nodes.nextElement(); current.resetNumberOfContainedRecords(); _model.nodeChanged(current); } } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces //-------------------------------------------------------------------------- } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryNodeEditor.javaapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryNodeE0000644000175000017500000002275111751454705031467 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer.categoryexplorer; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Enumeration; import javax.swing.JCheckBox; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JTree; import javax.swing.tree.TreePath; /** * CategoryNodeEditor * * @author Michael J. Sikorsky * @author Robert Shaw */ // Contributed by ThoughtWorks Inc. public class CategoryNodeEditor extends CategoryAbstractCellEditor { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected CategoryNodeEditorRenderer _renderer; protected CategoryNode _lastEditedNode; protected JCheckBox _checkBox; protected CategoryExplorerModel _categoryModel; protected JTree _tree; //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public CategoryNodeEditor(CategoryExplorerModel model) { _renderer = new CategoryNodeEditorRenderer(); _checkBox = _renderer.getCheckBox(); _categoryModel = model; _checkBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { _categoryModel.update(_lastEditedNode, _checkBox.isSelected()); stopCellEditing(); } }); _renderer.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { if ((e.getModifiers() & MouseEvent.BUTTON3_MASK) != 0) { showPopup(_lastEditedNode, e.getX(), e.getY()); } stopCellEditing(); } }); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public Component getTreeCellEditorComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row) { _lastEditedNode = (CategoryNode) value; _tree = tree; return _renderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, true); // hasFocus ignored } public Object getCellEditorValue() { return _lastEditedNode.getUserObject(); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- protected JMenuItem createPropertiesMenuItem(final CategoryNode node) { JMenuItem result = new JMenuItem("Properties"); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showPropertiesDialog(node); } }); return result; } protected void showPropertiesDialog(CategoryNode node) { JOptionPane.showMessageDialog( _tree, getDisplayedProperties(node), "Category Properties: " + node.getTitle(), JOptionPane.PLAIN_MESSAGE ); } protected Object getDisplayedProperties(CategoryNode node) { ArrayList result = new ArrayList(); result.add("Category: " + node.getTitle()); if (node.hasFatalRecords()) { result.add("Contains at least one fatal LogRecord."); } if (node.hasFatalChildren()) { result.add("Contains descendants with a fatal LogRecord."); } result.add("LogRecords in this category alone: " + node.getNumberOfContainedRecords()); result.add("LogRecords in descendant categories: " + node.getNumberOfRecordsFromChildren()); result.add("LogRecords in this category including descendants: " + node.getTotalNumberOfRecords()); return result.toArray(); } protected void showPopup(CategoryNode node, int x, int y) { JPopupMenu popup = new JPopupMenu(); popup.setSize(150, 400); // // Configure the Popup // if (node.getParent() == null) { popup.add(createRemoveMenuItem()); popup.addSeparator(); } popup.add(createSelectDescendantsMenuItem(node)); popup.add(createUnselectDescendantsMenuItem(node)); popup.addSeparator(); popup.add(createExpandMenuItem(node)); popup.add(createCollapseMenuItem(node)); popup.addSeparator(); popup.add(createPropertiesMenuItem(node)); popup.show(_renderer, x, y); } protected JMenuItem createSelectDescendantsMenuItem(final CategoryNode node) { JMenuItem selectDescendants = new JMenuItem("Select All Descendant Categories"); selectDescendants.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { _categoryModel.setDescendantSelection(node, true); } } ); return selectDescendants; } protected JMenuItem createUnselectDescendantsMenuItem(final CategoryNode node) { JMenuItem unselectDescendants = new JMenuItem("Deselect All Descendant Categories"); unselectDescendants.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { _categoryModel.setDescendantSelection(node, false); } } ); return unselectDescendants; } protected JMenuItem createExpandMenuItem(final CategoryNode node) { JMenuItem result = new JMenuItem("Expand All Descendant Categories"); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { expandDescendants(node); } }); return result; } protected JMenuItem createCollapseMenuItem(final CategoryNode node) { JMenuItem result = new JMenuItem("Collapse All Descendant Categories"); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { collapseDescendants(node); } }); return result; } /** * This featured was moved from the LogBrokerMonitor class * to the CategoryNodeExplorer so that the Category tree * could be pruned from the Category Explorer popup menu. * This menu option only appears when a user right clicks on * the Category parent node. * * See removeUnusedNodes() */ protected JMenuItem createRemoveMenuItem() { JMenuItem result = new JMenuItem("Remove All Empty Categories"); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { while (removeUnusedNodes() > 0) ; } }); return result; } protected void expandDescendants(CategoryNode node) { Enumeration descendants = node.depthFirstEnumeration(); CategoryNode current; while (descendants.hasMoreElements()) { current = (CategoryNode) descendants.nextElement(); expand(current); } } protected void collapseDescendants(CategoryNode node) { Enumeration descendants = node.depthFirstEnumeration(); CategoryNode current; while (descendants.hasMoreElements()) { current = (CategoryNode) descendants.nextElement(); collapse(current); } } /** * Removes any inactive nodes from the Category tree. */ protected int removeUnusedNodes() { int count = 0; CategoryNode root = _categoryModel.getRootCategoryNode(); Enumeration enumeration = root.depthFirstEnumeration(); while (enumeration.hasMoreElements()) { CategoryNode node = (CategoryNode) enumeration.nextElement(); if (node.isLeaf() && node.getNumberOfContainedRecords() == 0 && node.getParent() != null) { _categoryModel.removeNodeFromParent(node); count++; } } return count; } protected void expand(CategoryNode node) { _tree.expandPath(getTreePath(node)); } protected TreePath getTreePath(CategoryNode node) { return new TreePath(node.getPath()); } protected void collapse(CategoryNode node) { _tree.collapsePath(getTreePath(node)); } //----------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryImmediateEditor.javaapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryImmed0000644000175000017500000001116211751454705031522 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer.categoryexplorer; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.util.EventObject; import javax.swing.Icon; import javax.swing.JTree; import javax.swing.tree.DefaultTreeCellEditor; import javax.swing.tree.TreePath; /** * CategoryImmediateEditor * * @author Michael J. Sikorsky * @author Robert Shaw */ // Contributed by ThoughtWorks Inc. public class CategoryImmediateEditor extends DefaultTreeCellEditor { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- private CategoryNodeRenderer renderer; protected Icon editingIcon = null; //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public CategoryImmediateEditor(JTree tree, CategoryNodeRenderer renderer, CategoryNodeEditor editor) { super(tree, renderer, editor); this.renderer = renderer; renderer.setIcon(null); renderer.setLeafIcon(null); renderer.setOpenIcon(null); renderer.setClosedIcon(null); super.editingIcon = null; } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public boolean shouldSelectCell(EventObject e) { boolean rv = false; // only mouse events if (e instanceof MouseEvent) { MouseEvent me = (MouseEvent) e; TreePath path = tree.getPathForLocation(me.getX(), me.getY()); CategoryNode node = (CategoryNode) path.getLastPathComponent(); rv = node.isLeaf() /*|| !inCheckBoxHitRegion(me)*/; } return rv; } public boolean inCheckBoxHitRegion(MouseEvent e) { TreePath path = tree.getPathForLocation(e.getX(), e.getY()); if (path == null) { return false; } CategoryNode node = (CategoryNode) path.getLastPathComponent(); boolean rv = false; if (true) { // offset and lastRow DefaultTreeCellEditor // protected members Rectangle bounds = tree.getRowBounds(lastRow); Dimension checkBoxOffset = renderer.getCheckBoxOffset(); bounds.translate(offset + checkBoxOffset.width, checkBoxOffset.height); rv = bounds.contains(e.getPoint()); } return true; } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- protected boolean canEditImmediately(EventObject e) { boolean rv = false; if (e instanceof MouseEvent) { MouseEvent me = (MouseEvent) e; rv = inCheckBoxHitRegion(me); } return rv; } protected void determineOffset(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) { // Very important: means that the tree won't jump around. offset = 0; } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryNodeRenderer.javaapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryNodeR0000644000175000017500000001172311751454705031501 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer.categoryexplorer; import javax.swing.*; import javax.swing.tree.DefaultTreeCellRenderer; import java.awt.*; import java.net.URL; /** * CategoryNodeRenderer * * @author Michael J. Sikorsky * @author Robert Shaw */ // Contributed by ThoughtWorks Inc. public class CategoryNodeRenderer extends DefaultTreeCellRenderer { private static final long serialVersionUID = -6046702673278595048L; //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- public static final Color FATAL_CHILDREN = new Color(189, 113, 0); //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected JCheckBox _checkBox = new JCheckBox(); protected JPanel _panel = new JPanel(); protected static ImageIcon _sat = null; // protected JLabel _label = new JLabel(); //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public CategoryNodeRenderer() { _panel.setBackground(UIManager.getColor("Tree.textBackground")); if (_sat == null) { // Load the satellite image. String resource = "/org/apache/log4j/lf5/viewer/images/channelexplorer_satellite.gif"; URL satURL = getClass().getResource(resource); _sat = new ImageIcon(satURL); } setOpaque(false); _checkBox.setOpaque(false); _panel.setOpaque(false); // The flowlayout set to LEFT is very important so that the editor // doesn't jump around. _panel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); _panel.add(_checkBox); _panel.add(this); setOpenIcon(_sat); setClosedIcon(_sat); setLeafIcon(_sat); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public Component getTreeCellRendererComponent( JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { CategoryNode node = (CategoryNode) value; //FileNode node = (FileNode)value; //String s = tree.convertValueToText(value, selected, // expanded, leaf, row, hasFocus); super.getTreeCellRendererComponent( tree, value, selected, expanded, leaf, row, hasFocus); if (row == 0) { // Root row -- no check box _checkBox.setVisible(false); } else { _checkBox.setVisible(true); _checkBox.setSelected(node.isSelected()); } String toolTip = buildToolTip(node); _panel.setToolTipText(toolTip); if (node.hasFatalChildren()) { this.setForeground(FATAL_CHILDREN); } if (node.hasFatalRecords()) { this.setForeground(Color.red); } return _panel; } public Dimension getCheckBoxOffset() { return new Dimension(0, 0); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- protected String buildToolTip(CategoryNode node) { StringBuffer result = new StringBuffer(); result.append(node.getTitle()).append(" contains a total of "); result.append(node.getTotalNumberOfRecords()); result.append(" LogRecords."); result.append(" Right-click for more info."); return result.toString(); } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryElement.javaapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryEleme0000644000175000017500000000544011751454705031520 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer.categoryexplorer; /** * CategoryElement represents a single element or part of a Category. * * @author Michael J. Sikorsky * @author Robert Shaw */ // Contributed by ThoughtWorks Inc. public class CategoryElement { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected String _categoryTitle; //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public CategoryElement() { super(); } public CategoryElement(String title) { _categoryTitle = title; } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public String getTitle() { return (_categoryTitle); } public void setTitle(String title) { _categoryTitle = title; } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryPath.javaapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryPath.0000644000175000017500000001124011751454705031436 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer.categoryexplorer; import java.util.LinkedList; import java.util.StringTokenizer; /** * CategoryPath is a collection of CategoryItems which represent a * path of categories. * * @author Michael J. Sikorsky * @author Robert Shaw */ // Contributed by ThoughtWorks Inc. public class CategoryPath { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected LinkedList _categoryElements = new LinkedList(); //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public CategoryPath() { super(); } /** * Construct a CategoryPath. If the category is null, it defaults to "Debug". */ public CategoryPath(String category) { String processedCategory = category; if (processedCategory == null) { processedCategory = "Debug"; } processedCategory = processedCategory.replace('/', '.'); processedCategory = processedCategory.replace('\\', '.'); StringTokenizer st = new StringTokenizer(processedCategory, "."); while (st.hasMoreTokens()) { String element = st.nextToken(); addCategoryElement(new CategoryElement(element)); } } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** * returns the number of CategoryElements. */ public int size() { int count = _categoryElements.size(); return (count); } public boolean isEmpty() { boolean empty = false; if (_categoryElements.size() == 0) { empty = true; } return (empty); } /** * Removes all categoryElements. */ public void removeAllCategoryElements() { _categoryElements.clear(); } /** * Adds the specified categoryElement to the end of the categoryElement set. */ public void addCategoryElement(CategoryElement categoryElement) { _categoryElements.addLast(categoryElement); } /** * Returns the CategoryElement at the specified index. */ public CategoryElement categoryElementAt(int index) { return ((CategoryElement) _categoryElements.get(index)); } public String toString() { StringBuffer out = new StringBuffer(100); out.append("\n"); out.append("===========================\n"); out.append("CategoryPath: \n"); out.append("---------------------------\n"); out.append("\nCategoryPath:\n\t"); if (this.size() > 0) { for (int i = 0; i < this.size(); i++) { out.append(this.categoryElementAt(i).toString()); out.append("\n\t"); } } else { out.append("<>"); } out.append("\n"); out.append("===========================\n"); return (out.toString()); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryNodeEditorRenderer.javaapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryNodeE0000644000175000017500000000602311751454705031461 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer.categoryexplorer; import java.awt.Component; import javax.swing.JCheckBox; import javax.swing.JTree; /** * CategoryNodeEditorRenderer * * @author Michael J. Sikorsky * @author Robert Shaw */ // Contributed by ThoughtWorks Inc. public class CategoryNodeEditorRenderer extends CategoryNodeRenderer { private static final long serialVersionUID = -6094804684259929574L; //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public Component getTreeCellRendererComponent( JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); return c; } public JCheckBox getCheckBox() { return _checkBox; } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryAbstractCellEditor.javaapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryAbstr0000644000175000017500000001256211751454705031547 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer.categoryexplorer; import java.awt.Component; import java.awt.event.MouseEvent; import java.util.EventObject; import javax.swing.JTable; import javax.swing.JTree; import javax.swing.event.CellEditorListener; import javax.swing.event.ChangeEvent; import javax.swing.event.EventListenerList; import javax.swing.table.TableCellEditor; import javax.swing.tree.TreeCellEditor; /** * CategoryAbstractCellEditor. Base class to handle the some common * details of cell editing. * * @author Michael J. Sikorsky * @author Robert Shaw */ // Contributed by ThoughtWorks Inc. public class CategoryAbstractCellEditor implements TableCellEditor, TreeCellEditor { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected EventListenerList _listenerList = new EventListenerList(); protected Object _value; protected ChangeEvent _changeEvent = null; protected int _clickCountToStart = 1; //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public Object getCellEditorValue() { return _value; } public void setCellEditorValue(Object value) { _value = value; } public void setClickCountToStart(int count) { _clickCountToStart = count; } public int getClickCountToStart() { return _clickCountToStart; } public boolean isCellEditable(EventObject anEvent) { if (anEvent instanceof MouseEvent) { if (((MouseEvent) anEvent).getClickCount() < _clickCountToStart) { return false; } } return true; } public boolean shouldSelectCell(EventObject anEvent) { if (this.isCellEditable(anEvent)) { if (anEvent == null || ((MouseEvent) anEvent).getClickCount() >= _clickCountToStart) { return true; } } return false; } public boolean stopCellEditing() { fireEditingStopped(); return true; } public void cancelCellEditing() { fireEditingCanceled(); } public void addCellEditorListener(CellEditorListener l) { _listenerList.add(CellEditorListener.class, l); } public void removeCellEditorListener(CellEditorListener l) { _listenerList.remove(CellEditorListener.class, l); } public Component getTreeCellEditorComponent( JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) { return null; } public Component getTableCellEditorComponent( JTable table, Object value, boolean isSelected, int row, int column) { return null; } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- protected void fireEditingStopped() { Object[] listeners = _listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == CellEditorListener.class) { if (_changeEvent == null) { _changeEvent = new ChangeEvent(this); } ((CellEditorListener) listeners[i + 1]).editingStopped(_changeEvent); } } } protected void fireEditingCanceled() { Object[] listeners = _listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == CellEditorListener.class) { if (_changeEvent == null) { _changeEvent = new ChangeEvent(this); } ((CellEditorListener) listeners[i + 1]).editingCanceled(_changeEvent); } } } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryExplorerModel.javaapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryExplo0000644000175000017500000002473511751454705031570 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer.categoryexplorer; import java.awt.AWTEventMulticaster; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Enumeration; import javax.swing.SwingUtilities; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import org.apache.log4j.lf5.LogRecord; /** * CategoryExplorerModel * * @author Michael J. Sikorsky * @author Robert Shaw * @author Brent Sprecher * @author Richard Hurst */ // Contributed by ThoughtWorks Inc. public class CategoryExplorerModel extends DefaultTreeModel { private static final long serialVersionUID = -3413887384316015901L; //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected boolean _renderFatal = true; protected ActionListener _listener = null; protected ActionEvent _event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "Nodes Selection changed"); //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public CategoryExplorerModel(CategoryNode node) { super(node); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public void addLogRecord(LogRecord lr) { CategoryPath path = new CategoryPath(lr.getCategory()); addCategory(path); // create category path if it is new CategoryNode node = getCategoryNode(path); node.addRecord(); // update category node if (_renderFatal && lr.isFatal()) { TreeNode[] nodes = getPathToRoot(node); int len = nodes.length; CategoryNode parent; // i = 0 gives root node // skip node and root, loop through "parents" in between for (int i = 1; i < len - 1; i++) { parent = (CategoryNode) nodes[i]; parent.setHasFatalChildren(true); nodeChanged(parent); } node.setHasFatalRecords(true); nodeChanged(node); } } public CategoryNode getRootCategoryNode() { return (CategoryNode) getRoot(); } public CategoryNode getCategoryNode(String category) { CategoryPath path = new CategoryPath(category); return (getCategoryNode(path)); } /** * returns null if no CategoryNode exists. */ public CategoryNode getCategoryNode(CategoryPath path) { CategoryNode root = (CategoryNode) getRoot(); CategoryNode parent = root; // Start condition. for (int i = 0; i < path.size(); i++) { CategoryElement element = path.categoryElementAt(i); // If the two nodes have matching titles they are considered equal. Enumeration children = parent.children(); boolean categoryAlreadyExists = false; while (children.hasMoreElements()) { CategoryNode node = (CategoryNode) children.nextElement(); String title = node.getTitle().toLowerCase(); String pathLC = element.getTitle().toLowerCase(); if (title.equals(pathLC)) { categoryAlreadyExists = true; // This is now the new parent node. parent = node; break; // out of the while, and back to the for(). } } if (categoryAlreadyExists == false) { return null; // Didn't find the Node. } } return (parent); } /** * @return true if all the nodes in the specified CategoryPath are * selected. */ public boolean isCategoryPathActive(CategoryPath path) { CategoryNode root = (CategoryNode) getRoot(); CategoryNode parent = root; // Start condition. boolean active = false; for (int i = 0; i < path.size(); i++) { CategoryElement element = path.categoryElementAt(i); // If the two nodes have matching titles they are considered equal. Enumeration children = parent.children(); boolean categoryAlreadyExists = false; active = false; while (children.hasMoreElements()) { CategoryNode node = (CategoryNode) children.nextElement(); String title = node.getTitle().toLowerCase(); String pathLC = element.getTitle().toLowerCase(); if (title.equals(pathLC)) { categoryAlreadyExists = true; // This is now the new parent node. parent = node; if (parent.isSelected()) { active = true; } break; // out of the while, and back to the for(). } } if (active == false || categoryAlreadyExists == false) { return false; } } return (active); } /** *

Method altered by Richard Hurst such that it returns the CategoryNode * corresponding to the CategoryPath

* * @param path category path. * @return CategoryNode */ public CategoryNode addCategory(CategoryPath path) { CategoryNode root = (CategoryNode) getRoot(); CategoryNode parent = root; // Start condition. for (int i = 0; i < path.size(); i++) { CategoryElement element = path.categoryElementAt(i); // If the two nodes have matching titles they are considered equal. Enumeration children = parent.children(); boolean categoryAlreadyExists = false; while (children.hasMoreElements()) { CategoryNode node = (CategoryNode) children.nextElement(); String title = node.getTitle().toLowerCase(); String pathLC = element.getTitle().toLowerCase(); if (title.equals(pathLC)) { categoryAlreadyExists = true; // This is now the new parent node. parent = node; break; } } if (categoryAlreadyExists == false) { // We need to add the node. CategoryNode newNode = new CategoryNode(element.getTitle()); //This method of adding a new node cause parent roots to be // collapsed. //parent.add( newNode ); //reload(parent); // This doesn't force the nodes to collapse. insertNodeInto(newNode, parent, parent.getChildCount()); refresh(newNode); // The newly added node is now the parent. parent = newNode; } } return parent; } public void update(CategoryNode node, boolean selected) { if (node.isSelected() == selected) { return; // nothing was changed, nothing to do } // select parents or deselect children if (selected) { setParentSelection(node, true); } else { setDescendantSelection(node, false); } } public void setDescendantSelection(CategoryNode node, boolean selected) { Enumeration descendants = node.depthFirstEnumeration(); CategoryNode current; while (descendants.hasMoreElements()) { current = (CategoryNode) descendants.nextElement(); // does the current node need to be changed? if (current.isSelected() != selected) { current.setSelected(selected); nodeChanged(current); } } notifyActionListeners(); } public void setParentSelection(CategoryNode node, boolean selected) { TreeNode[] nodes = getPathToRoot(node); int len = nodes.length; CategoryNode parent; // i = 0 gives root node, i=len-1 gives this node // skip the root node for (int i = 1; i < len; i++) { parent = (CategoryNode) nodes[i]; if (parent.isSelected() != selected) { parent.setSelected(selected); nodeChanged(parent); } } notifyActionListeners(); } public synchronized void addActionListener(ActionListener l) { _listener = AWTEventMulticaster.add(_listener, l); } public synchronized void removeActionListener(ActionListener l) { _listener = AWTEventMulticaster.remove(_listener, l); } public void resetAllNodeCounts() { Enumeration nodes = getRootCategoryNode().depthFirstEnumeration(); CategoryNode current; while (nodes.hasMoreElements()) { current = (CategoryNode) nodes.nextElement(); current.resetNumberOfContainedRecords(); nodeChanged(current); } } /** *

Returns the CategoryPath to the specified CategoryNode

* * @param node The target CategoryNode * @return CategoryPath */ public TreePath getTreePathToRoot(CategoryNode node) { if (node == null) { return null; } return (new TreePath(getPathToRoot(node))); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- protected void notifyActionListeners() { if (_listener != null) { _listener.actionPerformed(_event); } } /** * Fires a nodechanged event on the SwingThread. */ protected void refresh(final CategoryNode node) { SwingUtilities.invokeLater(new Runnable() { public void run() { nodeChanged(node); // remind the tree to render the new node } }); } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryExplorerTree.javaapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/CategoryExplo0000644000175000017500000001075611751454705031566 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer.categoryexplorer; import java.awt.event.MouseEvent; import javax.swing.JTree; import javax.swing.event.TreeModelEvent; import javax.swing.tree.TreePath; /** * CategoryExplorerTree * * @author Michael J. Sikorsky * @author Robert Shaw * @author Brent Sprecher * @author Brad Marlborough */ // Contributed by ThoughtWorks Inc. public class CategoryExplorerTree extends JTree { private static final long serialVersionUID = 8066257446951323576L; //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected CategoryExplorerModel _model; protected boolean _rootAlreadyExpanded = false; //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- /** * Construct a CategoryExplorerTree with a specific model. */ public CategoryExplorerTree(CategoryExplorerModel model) { super(model); _model = model; init(); } /** * Construct a CategoryExplorerTree and create a default CategoryExplorerModel. */ public CategoryExplorerTree() { super(); CategoryNode rootNode = new CategoryNode("Categories"); _model = new CategoryExplorerModel(rootNode); setModel(_model); init(); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public CategoryExplorerModel getExplorerModel() { return (_model); } public String getToolTipText(MouseEvent e) { try { return super.getToolTipText(e); } catch (Exception ex) { return ""; } } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- protected void init() { // Put visible lines on the JTree. putClientProperty("JTree.lineStyle", "Angled"); // Configure the Tree with the appropriate Renderers and Editors. CategoryNodeRenderer renderer = new CategoryNodeRenderer(); setEditable(true); setCellRenderer(renderer); CategoryNodeEditor editor = new CategoryNodeEditor(_model); setCellEditor(new CategoryImmediateEditor(this, new CategoryNodeRenderer(), editor)); setShowsRootHandles(true); setToolTipText(""); ensureRootExpansion(); } protected void expandRootNode() { if (_rootAlreadyExpanded) { return; } _rootAlreadyExpanded = true; TreePath path = new TreePath(_model.getRootCategoryNode().getPath()); expandPath(path); } protected void ensureRootExpansion() { _model.addTreeModelListener(new TreeModelAdapter() { public void treeNodesInserted(TreeModelEvent e) { expandRootNode(); } }); } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/TreeModelAdapter.javaapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/categoryexplorer/TreeModelAdap0000644000175000017500000000545511751454705031447 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer.categoryexplorer; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; /** * Default implementation of TreeModelListener which does nothing. * * @author Richard Wan */ // Contributed by ThoughtWorks Inc. public class TreeModelAdapter implements TreeModelListener { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public void treeNodesChanged(TreeModelEvent e) { } public void treeNodesInserted(TreeModelEvent e) { } public void treeNodesRemoved(TreeModelEvent e) { } public void treeStructureChanged(TreeModelEvent e) { } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/LogFactor5LoadingDialog.java0000644000175000017500000000601311751454705030675 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridBagLayout; import javax.swing.JFrame; import javax.swing.JPanel; /** * LogFactor5LoadingDialog * * @author Richard Hurst * @author Brad Marlborough */ // Contributed by ThoughtWorks Inc. public class LogFactor5LoadingDialog extends LogFactor5Dialog { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public LogFactor5LoadingDialog(JFrame jframe, String message) { super(jframe, "LogFactor5", false); JPanel bottom = new JPanel(); bottom.setLayout(new FlowLayout()); JPanel main = new JPanel(); main.setLayout(new GridBagLayout()); wrapStringOnPanel(message, main); getContentPane().add(main, BorderLayout.CENTER); getContentPane().add(bottom, BorderLayout.SOUTH); show(); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces //-------------------------------------------------------------------------- }apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/LogTable.java0000644000175000017500000002031611751454705026005 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Vector; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import org.apache.log4j.lf5.util.DateFormatManager; /** * LogTable. * * @author Michael J. Sikorsky * @author Robert Shaw * @author Brad Marlborough * @author Brent Sprecher */ // Contributed by ThoughtWorks Inc. public class LogTable extends JTable { private static final long serialVersionUID = 4867085140195148458L; //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected int _rowHeight = 30; protected JTextArea _detailTextArea; // For the columns: protected int _numCols = 9; protected TableColumn[] _tableColumns = new TableColumn[_numCols]; protected int[] _colWidths = {40, 40, 40, 70, 70, 360, 440, 200, 60}; protected LogTableColumn[] _colNames = LogTableColumn.getLogTableColumnArray(); protected int _colDate = 0; protected int _colThread = 1; protected int _colMessageNum = 2; protected int _colLevel = 3; protected int _colNDC = 4; protected int _colCategory = 5; protected int _colMessage = 6; protected int _colLocation = 7; protected int _colThrown = 8; protected DateFormatManager _dateFormatManager = null; //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public LogTable(JTextArea detailTextArea) { super(); init(); _detailTextArea = detailTextArea; setModel(new FilteredLogTableModel()); Enumeration columns = getColumnModel().getColumns(); int i = 0; while (columns.hasMoreElements()) { TableColumn col = (TableColumn) columns.nextElement(); col.setCellRenderer(new LogTableRowRenderer()); col.setPreferredWidth(_colWidths[i]); _tableColumns[i] = col; i++; } ListSelectionModel rowSM = getSelectionModel(); rowSM.addListSelectionListener(new LogTableListSelectionListener(this)); //setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** * Get the DateFormatManager for formatting dates. */ public DateFormatManager getDateFormatManager() { return _dateFormatManager; } /** * Set the date format manager for formatting dates. */ public void setDateFormatManager(DateFormatManager dfm) { _dateFormatManager = dfm; } public synchronized void clearLogRecords() { //For JDK1.3 //((DefaultTableModel)getModel()).setRowCount(0); // For JDK1.2.x getFilteredLogTableModel().clear(); } public FilteredLogTableModel getFilteredLogTableModel() { return (FilteredLogTableModel) getModel(); } // default view if a view is not set and saved public void setDetailedView() { //TODO: Defineable Views. TableColumnModel model = getColumnModel(); // Remove all the columns: for (int f = 0; f < _numCols; f++) { model.removeColumn(_tableColumns[f]); } // Add them back in the correct order: for (int i = 0; i < _numCols; i++) { model.addColumn(_tableColumns[i]); } //SWING BUG: sizeColumnsToFit(-1); } public void setView(List columns) { TableColumnModel model = getColumnModel(); // Remove all the columns: for (int f = 0; f < _numCols; f++) { model.removeColumn(_tableColumns[f]); } Iterator selectedColumns = columns.iterator(); Vector columnNameAndNumber = getColumnNameAndNumber(); while (selectedColumns.hasNext()) { // add the column to the view model.addColumn(_tableColumns[columnNameAndNumber.indexOf(selectedColumns.next())]); } //SWING BUG: sizeColumnsToFit(-1); } public void setFont(Font font) { super.setFont(font); Graphics g = this.getGraphics(); if (g != null) { FontMetrics fm = g.getFontMetrics(font); int height = fm.getHeight(); _rowHeight = height + height / 3; setRowHeight(_rowHeight); } } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- protected void init() { setRowHeight(_rowHeight); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); } // assign a column number to a column name protected Vector getColumnNameAndNumber() { Vector columnNameAndNumber = new Vector(); for (int i = 0; i < _colNames.length; i++) { columnNameAndNumber.add(i, _colNames[i]); } return columnNameAndNumber; } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- class LogTableListSelectionListener implements ListSelectionListener { protected JTable _table; public LogTableListSelectionListener(JTable table) { _table = table; } public void valueChanged(ListSelectionEvent e) { //Ignore extra messages. if (e.getValueIsAdjusting()) { return; } ListSelectionModel lsm = (ListSelectionModel) e.getSource(); if (lsm.isSelectionEmpty()) { //no rows are selected } else { StringBuffer buf = new StringBuffer(); int selectedRow = lsm.getMinSelectionIndex(); for (int i = 0; i < _numCols - 1; i++) { String value = ""; Object obj = _table.getModel().getValueAt(selectedRow, i); if (obj != null) { value = obj.toString(); } buf.append(_colNames[i] + ":"); buf.append("\t"); if (i == _colThread || i == _colMessage || i == _colLevel) { buf.append("\t"); // pad out the date. } if (i == _colDate || i == _colNDC) { buf.append("\t\t"); // pad out the date. } // if( i == _colSequence) // { // buf.append("\t\t\t"); // pad out the Sequnce. // } buf.append(value); buf.append("\n"); } buf.append(_colNames[_numCols - 1] + ":\n"); Object obj = _table.getModel().getValueAt(selectedRow, _numCols - 1); if (obj != null) { buf.append(obj.toString()); } _detailTextArea.setText(buf.toString()); } } } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/LogTableColumnFormatException.javaapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/LogTableColumnFormatException.0000644000175000017500000000534511751454705031356 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer; /** * Thrown to indicate that the client has attempted to convert a string * to one the LogLevel types, but the string does not have the appropriate * format. * * @author Michael J. Sikorsky */ // Contributed by ThoughtWorks Inc. public class LogTableColumnFormatException extends Exception { private static final long serialVersionUID = 6529165785030431653L; //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public LogTableColumnFormatException(String message) { super(message); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/LogBrokerMonitor.java0000644000175000017500000013623311751454705027560 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JColorChooser; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.JToolBar; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import org.apache.log4j.lf5.LogLevel; import org.apache.log4j.lf5.LogRecord; import org.apache.log4j.lf5.LogRecordFilter; import org.apache.log4j.lf5.util.DateFormatManager; import org.apache.log4j.lf5.util.LogFileParser; import org.apache.log4j.lf5.viewer.categoryexplorer.CategoryExplorerTree; import org.apache.log4j.lf5.viewer.categoryexplorer.CategoryPath; import org.apache.log4j.lf5.viewer.configure.ConfigurationManager; import org.apache.log4j.lf5.viewer.configure.MRUFileManager; /** * LogBrokerMonitor *. * @author Michael J. Sikorsky * @author Robert Shaw * @author Brad Marlborough * @author Richard Wan * @author Brent Sprecher * @author Richard Hurst */ // Contributed by ThoughtWorks Inc. public class LogBrokerMonitor { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- public static final String DETAILED_VIEW = "Detailed"; // public static final String STANDARD_VIEW = "Standard"; // public static final String COMPACT_VIEW = "Compact"; //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected JFrame _logMonitorFrame; protected int _logMonitorFrameWidth = 550; protected int _logMonitorFrameHeight = 500; protected LogTable _table; protected CategoryExplorerTree _categoryExplorerTree; protected String _searchText; protected String _NDCTextFilter = ""; protected LogLevel _leastSevereDisplayedLogLevel = LogLevel.DEBUG; protected JScrollPane _logTableScrollPane; protected JLabel _statusLabel; protected Object _lock = new Object(); protected JComboBox _fontSizeCombo; protected int _fontSize = 10; protected String _fontName = "Dialog"; protected String _currentView = DETAILED_VIEW; protected boolean _loadSystemFonts = false; protected boolean _trackTableScrollPane = true; protected Dimension _lastTableViewportSize; protected boolean _callSystemExitOnClose = false; protected List _displayedLogBrokerProperties = new Vector(); protected Map _logLevelMenuItems = new HashMap(); protected Map _logTableColumnMenuItems = new HashMap(); protected List _levels = null; protected List _columns = null; protected boolean _isDisposed = false; protected ConfigurationManager _configurationManager = null; protected MRUFileManager _mruFileManager = null; protected File _fileLocation = null; //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- /** * Construct a LogBrokerMonitor. */ public LogBrokerMonitor(List logLevels) { _levels = logLevels; _columns = LogTableColumn.getLogTableColumns(); // This allows us to use the LogBroker in command line tools and // have the option for it to shutdown. String callSystemExitOnClose = System.getProperty("monitor.exit"); if (callSystemExitOnClose == null) { callSystemExitOnClose = "false"; } callSystemExitOnClose = callSystemExitOnClose.trim().toLowerCase(); if (callSystemExitOnClose.equals("true")) { _callSystemExitOnClose = true; } initComponents(); _logMonitorFrame.addWindowListener( new LogBrokerMonitorWindowAdaptor(this)); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** * Show the frame for the LogBrokerMonitor. Dispatched to the * swing thread. */ public void show(final int delay) { if (_logMonitorFrame.isVisible()) { return; } // This request is very low priority, let other threads execute first. SwingUtilities.invokeLater(new Runnable() { public void run() { Thread.yield(); pause(delay); _logMonitorFrame.setVisible(true); } }); } public void show() { show(0); } /** * Dispose of the frame for the LogBrokerMonitor. */ public void dispose() { _logMonitorFrame.dispose(); _isDisposed = true; if (_callSystemExitOnClose == true) { System.exit(0); } } /** * Hide the frame for the LogBrokerMonitor. */ public void hide() { _logMonitorFrame.setVisible(false); } /** * Get the DateFormatManager for formatting dates. */ public DateFormatManager getDateFormatManager() { return _table.getDateFormatManager(); } /** * Set the date format manager for formatting dates. */ public void setDateFormatManager(DateFormatManager dfm) { _table.setDateFormatManager(dfm); } /** * Get the value of whether or not System.exit() will be called * when the LogBrokerMonitor is closed. */ public boolean getCallSystemExitOnClose() { return _callSystemExitOnClose; } /** * Set the value of whether or not System.exit() will be called * when the LogBrokerMonitor is closed. */ public void setCallSystemExitOnClose(boolean callSystemExitOnClose) { _callSystemExitOnClose = callSystemExitOnClose; } /** * Add a log record message to be displayed in the LogTable. * This method is thread-safe as it posts requests to the SwingThread * rather than processing directly. */ public void addMessage(final LogRecord lr) { if (_isDisposed == true) { // If the frame has been disposed of, do not log any more // messages. return; } SwingUtilities.invokeLater(new Runnable() { public void run() { _categoryExplorerTree.getExplorerModel().addLogRecord(lr); _table.getFilteredLogTableModel().addLogRecord(lr); // update table updateStatusLabel(); // show updated counts } }); } public void setMaxNumberOfLogRecords(int maxNumberOfLogRecords) { _table.getFilteredLogTableModel().setMaxNumberOfLogRecords(maxNumberOfLogRecords); } public JFrame getBaseFrame() { return _logMonitorFrame; } public void setTitle(String title) { _logMonitorFrame.setTitle(title + " - LogFactor5"); } public void setFrameSize(int width, int height) { Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); if (0 < width && width < screen.width) { _logMonitorFrameWidth = width; } if (0 < height && height < screen.height) { _logMonitorFrameHeight = height; } updateFrameSize(); } public void setFontSize(int fontSize) { changeFontSizeCombo(_fontSizeCombo, fontSize); // setFontSizeSilently(actualFontSize); - changeFontSizeCombo fires event // refreshDetailTextArea(); } public void addDisplayedProperty(Object messageLine) { _displayedLogBrokerProperties.add(messageLine); } public Map getLogLevelMenuItems() { return _logLevelMenuItems; } public Map getLogTableColumnMenuItems() { return _logTableColumnMenuItems; } public JCheckBoxMenuItem getTableColumnMenuItem(LogTableColumn column) { return getLogTableColumnMenuItem(column); } public CategoryExplorerTree getCategoryExplorerTree() { return _categoryExplorerTree; } // Added in version 1.2 - gets the value of the NDC text filter // This value is set back to null each time the Monitor is initialized. public String getNDCTextFilter() { return _NDCTextFilter; } // Added in version 1.2 - sets the NDC Filter based on // a String passed in by the user. This value is persisted // in the XML Configuration file. public void setNDCLogRecordFilter(String textFilter) { _table.getFilteredLogTableModel(). setLogRecordFilter(createNDCLogRecordFilter(textFilter)); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- protected void setSearchText(String text) { _searchText = text; } // Added in version 1.2 - Sets the text filter for the NDC protected void setNDCTextFilter(String text) { // if no value is set, set it to a blank string // otherwise use the value provided if (text == null) { _NDCTextFilter = ""; } else { _NDCTextFilter = text; } } // Added in version 1.2 - Uses a different filter that sorts // based on an NDC string passed in by the user. If the string // is null or is an empty string, we do nothing. protected void sortByNDC() { String text = _NDCTextFilter; if (text == null || text.length() == 0) { return; } // Use new NDC filter _table.getFilteredLogTableModel(). setLogRecordFilter(createNDCLogRecordFilter(text)); } protected void findSearchText() { String text = _searchText; if (text == null || text.length() == 0) { return; } int startRow = getFirstSelectedRow(); int foundRow = findRecord( startRow, text, _table.getFilteredLogTableModel().getFilteredRecords() ); selectRow(foundRow); } protected int getFirstSelectedRow() { return _table.getSelectionModel().getMinSelectionIndex(); } protected void selectRow(int foundRow) { if (foundRow == -1) { String message = _searchText + " not found."; JOptionPane.showMessageDialog( _logMonitorFrame, message, "Text not found", JOptionPane.INFORMATION_MESSAGE ); return; } LF5SwingUtils.selectRow(foundRow, _table, _logTableScrollPane); } protected int findRecord( int startRow, String searchText, List records ) { if (startRow < 0) { startRow = 0; // start at first element if no rows are selected } else { startRow++; // start after the first selected row } int len = records.size(); for (int i = startRow; i < len; i++) { if (matches((LogRecord) records.get(i), searchText)) { return i; // found a record } } // wrap around to beginning if when we reach the end with no match len = startRow; for (int i = 0; i < len; i++) { if (matches((LogRecord) records.get(i), searchText)) { return i; // found a record } } // nothing found return -1; } /** * Check to see if the any records contain the search string. * Searching now supports NDC messages and date. */ protected boolean matches(LogRecord record, String text) { String message = record.getMessage(); String NDC = record.getNDC(); if (message == null && NDC == null || text == null) { return false; } if (message.toLowerCase().indexOf(text.toLowerCase()) == -1 && NDC.toLowerCase().indexOf(text.toLowerCase()) == -1) { return false; } return true; } /** * When the fontsize of a JTextArea is changed, the word-wrapped lines * may become garbled. This method clears and resets the text of the * text area. */ protected void refresh(JTextArea textArea) { String text = textArea.getText(); textArea.setText(""); textArea.setText(text); } protected void refreshDetailTextArea() { refresh(_table._detailTextArea); } protected void clearDetailTextArea() { _table._detailTextArea.setText(""); } /** * Changes the font selection in the combo box and returns the * size actually selected. * @return -1 if unable to select an appropriate font */ protected int changeFontSizeCombo(JComboBox box, int requestedSize) { int len = box.getItemCount(); int currentValue; Object currentObject; Object selectedObject = box.getItemAt(0); int selectedValue = Integer.parseInt(String.valueOf(selectedObject)); for (int i = 0; i < len; i++) { currentObject = box.getItemAt(i); currentValue = Integer.parseInt(String.valueOf(currentObject)); if (selectedValue < currentValue && currentValue <= requestedSize) { selectedValue = currentValue; selectedObject = currentObject; } } box.setSelectedItem(selectedObject); return selectedValue; } /** * Does not update gui or cause any events to be fired. */ protected void setFontSizeSilently(int fontSize) { _fontSize = fontSize; setFontSize(_table._detailTextArea, fontSize); selectRow(0); setFontSize(_table, fontSize); } protected void setFontSize(Component component, int fontSize) { Font oldFont = component.getFont(); Font newFont = new Font(oldFont.getFontName(), oldFont.getStyle(), fontSize); component.setFont(newFont); } protected void updateFrameSize() { _logMonitorFrame.setSize(_logMonitorFrameWidth, _logMonitorFrameHeight); centerFrame(_logMonitorFrame); } protected void pause(int millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { } } protected void initComponents() { // // Configure the Frame. // _logMonitorFrame = new JFrame("LogFactor5"); _logMonitorFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); String resource = "/org/apache/log4j/lf5/viewer/images/lf5_small_icon.gif"; URL lf5IconURL = getClass().getResource(resource); if (lf5IconURL != null) { _logMonitorFrame.setIconImage(new ImageIcon(lf5IconURL).getImage()); } updateFrameSize(); // // Configure the LogTable. // JTextArea detailTA = createDetailTextArea(); JScrollPane detailTAScrollPane = new JScrollPane(detailTA); _table = new LogTable(detailTA); setView(_currentView, _table); _table.setFont(new Font(_fontName, Font.PLAIN, _fontSize)); _logTableScrollPane = new JScrollPane(_table); if (_trackTableScrollPane) { _logTableScrollPane.getVerticalScrollBar().addAdjustmentListener( new TrackingAdjustmentListener() ); } // Configure the SplitPane between the LogTable & DetailTextArea // JSplitPane tableViewerSplitPane = new JSplitPane(); tableViewerSplitPane.setOneTouchExpandable(true); tableViewerSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); tableViewerSplitPane.setLeftComponent(_logTableScrollPane); tableViewerSplitPane.setRightComponent(detailTAScrollPane); // Make sure to do this last.. //tableViewerSplitPane.setDividerLocation(1.0); Doesn't work //the same under 1.2.x & 1.3 // "350" is a magic number that provides the correct default // behaviour under 1.2.x & 1.3. For example, bumping this // number to 400, causes the pane to be completely open in 1.2.x // and closed in 1.3 tableViewerSplitPane.setDividerLocation(350); // // Configure the CategoryExplorer // _categoryExplorerTree = new CategoryExplorerTree(); _table.getFilteredLogTableModel().setLogRecordFilter(createLogRecordFilter()); JScrollPane categoryExplorerTreeScrollPane = new JScrollPane(_categoryExplorerTree); categoryExplorerTreeScrollPane.setPreferredSize(new Dimension(130, 400)); // Load most recently used file list _mruFileManager = new MRUFileManager(); // // Configure the SplitPane between the CategoryExplorer & (LogTable/Detail) // JSplitPane splitPane = new JSplitPane(); splitPane.setOneTouchExpandable(true); splitPane.setRightComponent(tableViewerSplitPane); splitPane.setLeftComponent(categoryExplorerTreeScrollPane); // Do this last. splitPane.setDividerLocation(130); // // Add the MenuBar, StatusArea, CategoryExplorer|LogTable to the // LogMonitorFrame. // _logMonitorFrame.getRootPane().setJMenuBar(createMenuBar()); _logMonitorFrame.getContentPane().add(splitPane, BorderLayout.CENTER); _logMonitorFrame.getContentPane().add(createToolBar(), BorderLayout.NORTH); _logMonitorFrame.getContentPane().add(createStatusArea(), BorderLayout.SOUTH); makeLogTableListenToCategoryExplorer(); addTableModelProperties(); // // Configure ConfigurationManager // _configurationManager = new ConfigurationManager(this, _table); } protected LogRecordFilter createLogRecordFilter() { LogRecordFilter result = new LogRecordFilter() { public boolean passes(LogRecord record) { CategoryPath path = new CategoryPath(record.getCategory()); return getMenuItem(record.getLevel()).isSelected() && _categoryExplorerTree.getExplorerModel().isCategoryPathActive(path); } }; return result; } // Added in version 1.2 - Creates a new filter that sorts records based on // an NDC string passed in by the user. protected LogRecordFilter createNDCLogRecordFilter(String text) { _NDCTextFilter = text; LogRecordFilter result = new LogRecordFilter() { public boolean passes(LogRecord record) { String NDC = record.getNDC(); CategoryPath path = new CategoryPath(record.getCategory()); if (NDC == null || _NDCTextFilter == null) { return false; } else if (NDC.toLowerCase().indexOf(_NDCTextFilter.toLowerCase()) == -1) { return false; } else { return getMenuItem(record.getLevel()).isSelected() && _categoryExplorerTree.getExplorerModel().isCategoryPathActive(path); } } }; return result; } protected void updateStatusLabel() { _statusLabel.setText(getRecordsDisplayedMessage()); } protected String getRecordsDisplayedMessage() { FilteredLogTableModel model = _table.getFilteredLogTableModel(); return getStatusText(model.getRowCount(), model.getTotalRowCount()); } protected void addTableModelProperties() { final FilteredLogTableModel model = _table.getFilteredLogTableModel(); addDisplayedProperty(new Object() { public String toString() { return getRecordsDisplayedMessage(); } }); addDisplayedProperty(new Object() { public String toString() { return "Maximum number of displayed LogRecords: " + model._maxNumberOfLogRecords; } }); } protected String getStatusText(int displayedRows, int totalRows) { StringBuffer result = new StringBuffer(); result.append("Displaying: "); result.append(displayedRows); result.append(" records out of a total of: "); result.append(totalRows); result.append(" records."); return result.toString(); } protected void makeLogTableListenToCategoryExplorer() { ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { _table.getFilteredLogTableModel().refresh(); updateStatusLabel(); } }; _categoryExplorerTree.getExplorerModel().addActionListener(listener); } protected JPanel createStatusArea() { JPanel statusArea = new JPanel(); JLabel status = new JLabel("No log records to display."); _statusLabel = status; status.setHorizontalAlignment(JLabel.LEFT); statusArea.setBorder(BorderFactory.createEtchedBorder()); statusArea.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); statusArea.add(status); return (statusArea); } protected JTextArea createDetailTextArea() { JTextArea detailTA = new JTextArea(); detailTA.setFont(new Font("Monospaced", Font.PLAIN, 14)); detailTA.setTabSize(3); detailTA.setLineWrap(true); detailTA.setWrapStyleWord(false); return (detailTA); } protected JMenuBar createMenuBar() { JMenuBar menuBar = new JMenuBar(); menuBar.add(createFileMenu()); menuBar.add(createEditMenu()); menuBar.add(createLogLevelMenu()); menuBar.add(createViewMenu()); menuBar.add(createConfigureMenu()); menuBar.add(createHelpMenu()); return (menuBar); } protected JMenu createLogLevelMenu() { JMenu result = new JMenu("Log Level"); result.setMnemonic('l'); Iterator levels = getLogLevels(); while (levels.hasNext()) { result.add(getMenuItem((LogLevel) levels.next())); } result.addSeparator(); result.add(createAllLogLevelsMenuItem()); result.add(createNoLogLevelsMenuItem()); result.addSeparator(); result.add(createLogLevelColorMenu()); result.add(createResetLogLevelColorMenuItem()); return result; } protected JMenuItem createAllLogLevelsMenuItem() { JMenuItem result = new JMenuItem("Show all LogLevels"); result.setMnemonic('s'); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllLogLevels(true); _table.getFilteredLogTableModel().refresh(); updateStatusLabel(); } }); return result; } protected JMenuItem createNoLogLevelsMenuItem() { JMenuItem result = new JMenuItem("Hide all LogLevels"); result.setMnemonic('h'); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllLogLevels(false); _table.getFilteredLogTableModel().refresh(); updateStatusLabel(); } }); return result; } protected JMenu createLogLevelColorMenu() { JMenu colorMenu = new JMenu("Configure LogLevel Colors"); colorMenu.setMnemonic('c'); Iterator levels = getLogLevels(); while (levels.hasNext()) { colorMenu.add(createSubMenuItem((LogLevel) levels.next())); } return colorMenu; } protected JMenuItem createResetLogLevelColorMenuItem() { JMenuItem result = new JMenuItem("Reset LogLevel Colors"); result.setMnemonic('r'); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // reset the level colors in the map LogLevel.resetLogLevelColorMap(); // refresh the table _table.getFilteredLogTableModel().refresh(); } }); return result; } protected void selectAllLogLevels(boolean selected) { Iterator levels = getLogLevels(); while (levels.hasNext()) { getMenuItem((LogLevel) levels.next()).setSelected(selected); } } protected JCheckBoxMenuItem getMenuItem(LogLevel level) { JCheckBoxMenuItem result = (JCheckBoxMenuItem) (_logLevelMenuItems.get(level)); if (result == null) { result = createMenuItem(level); _logLevelMenuItems.put(level, result); } return result; } protected JMenuItem createSubMenuItem(LogLevel level) { final JMenuItem result = new JMenuItem(level.toString()); final LogLevel logLevel = level; result.setMnemonic(level.toString().charAt(0)); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showLogLevelColorChangeDialog(result, logLevel); } }); return result; } protected void showLogLevelColorChangeDialog(JMenuItem result, LogLevel level) { JMenuItem menuItem = result; Color newColor = JColorChooser.showDialog( _logMonitorFrame, "Choose LogLevel Color", result.getForeground()); if (newColor != null) { // set the color for the record level.setLogLevelColorMap(level, newColor); _table.getFilteredLogTableModel().refresh(); } } protected JCheckBoxMenuItem createMenuItem(LogLevel level) { JCheckBoxMenuItem result = new JCheckBoxMenuItem(level.toString()); result.setSelected(true); result.setMnemonic(level.toString().charAt(0)); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { _table.getFilteredLogTableModel().refresh(); updateStatusLabel(); } }); return result; } // view menu protected JMenu createViewMenu() { JMenu result = new JMenu("View"); result.setMnemonic('v'); Iterator columns = getLogTableColumns(); while (columns.hasNext()) { result.add(getLogTableColumnMenuItem((LogTableColumn) columns.next())); } result.addSeparator(); result.add(createAllLogTableColumnsMenuItem()); result.add(createNoLogTableColumnsMenuItem()); return result; } protected JCheckBoxMenuItem getLogTableColumnMenuItem(LogTableColumn column) { JCheckBoxMenuItem result = (JCheckBoxMenuItem) (_logTableColumnMenuItems.get(column)); if (result == null) { result = createLogTableColumnMenuItem(column); _logTableColumnMenuItems.put(column, result); } return result; } protected JCheckBoxMenuItem createLogTableColumnMenuItem(LogTableColumn column) { JCheckBoxMenuItem result = new JCheckBoxMenuItem(column.toString()); result.setSelected(true); result.setMnemonic(column.toString().charAt(0)); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // update list of columns and reset the view List selectedColumns = updateView(); _table.setView(selectedColumns); } }); return result; } protected List updateView() { ArrayList updatedList = new ArrayList(); Iterator columnIterator = _columns.iterator(); while (columnIterator.hasNext()) { LogTableColumn column = (LogTableColumn) columnIterator.next(); JCheckBoxMenuItem result = getLogTableColumnMenuItem(column); // check and see if the checkbox is checked if (result.isSelected()) { updatedList.add(column); } } return updatedList; } protected JMenuItem createAllLogTableColumnsMenuItem() { JMenuItem result = new JMenuItem("Show all Columns"); result.setMnemonic('s'); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllLogTableColumns(true); // update list of columns and reset the view List selectedColumns = updateView(); _table.setView(selectedColumns); } }); return result; } protected JMenuItem createNoLogTableColumnsMenuItem() { JMenuItem result = new JMenuItem("Hide all Columns"); result.setMnemonic('h'); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllLogTableColumns(false); // update list of columns and reset the view List selectedColumns = updateView(); _table.setView(selectedColumns); } }); return result; } protected void selectAllLogTableColumns(boolean selected) { Iterator columns = getLogTableColumns(); while (columns.hasNext()) { getLogTableColumnMenuItem((LogTableColumn) columns.next()).setSelected(selected); } } protected JMenu createFileMenu() { JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('f'); JMenuItem exitMI; fileMenu.add(createOpenMI()); fileMenu.add(createOpenURLMI()); fileMenu.addSeparator(); fileMenu.add(createCloseMI()); createMRUFileListMI(fileMenu); fileMenu.addSeparator(); fileMenu.add(createExitMI()); return fileMenu; } /** * Menu item added to allow log files to be opened with * the LF5 GUI. */ protected JMenuItem createOpenMI() { JMenuItem result = new JMenuItem("Open..."); result.setMnemonic('o'); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { requestOpen(); } }); return result; } /** * Menu item added to allow log files loaded from a URL * to be opened by the LF5 GUI. */ protected JMenuItem createOpenURLMI() { JMenuItem result = new JMenuItem("Open URL..."); result.setMnemonic('u'); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { requestOpenURL(); } }); return result; } protected JMenuItem createCloseMI() { JMenuItem result = new JMenuItem("Close"); result.setMnemonic('c'); result.setAccelerator(KeyStroke.getKeyStroke("control Q")); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { requestClose(); } }); return result; } /** * Creates a Most Recently Used file list to be * displayed in the File menu */ protected void createMRUFileListMI(JMenu menu) { String[] files = _mruFileManager.getMRUFileList(); if (files != null) { menu.addSeparator(); for (int i = 0; i < files.length; i++) { JMenuItem result = new JMenuItem((i + 1) + " " + files[i]); result.setMnemonic(i + 1); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { requestOpenMRU(e); } }); menu.add(result); } } } protected JMenuItem createExitMI() { JMenuItem result = new JMenuItem("Exit"); result.setMnemonic('x'); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { requestExit(); } }); return result; } protected JMenu createConfigureMenu() { JMenu configureMenu = new JMenu("Configure"); configureMenu.setMnemonic('c'); configureMenu.add(createConfigureSave()); configureMenu.add(createConfigureReset()); configureMenu.add(createConfigureMaxRecords()); return configureMenu; } protected JMenuItem createConfigureSave() { JMenuItem result = new JMenuItem("Save"); result.setMnemonic('s'); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveConfiguration(); } }); return result; } protected JMenuItem createConfigureReset() { JMenuItem result = new JMenuItem("Reset"); result.setMnemonic('r'); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { resetConfiguration(); } }); return result; } protected JMenuItem createConfigureMaxRecords() { JMenuItem result = new JMenuItem("Set Max Number of Records"); result.setMnemonic('m'); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setMaxRecordConfiguration(); } }); return result; } protected void saveConfiguration() { _configurationManager.save(); } protected void resetConfiguration() { _configurationManager.reset(); } protected void setMaxRecordConfiguration() { LogFactor5InputDialog inputDialog = new LogFactor5InputDialog( getBaseFrame(), "Set Max Number of Records", "", 10); String temp = inputDialog.getText(); if (temp != null) { try { setMaxNumberOfLogRecords(Integer.parseInt(temp)); } catch (NumberFormatException e) { LogFactor5ErrorDialog error = new LogFactor5ErrorDialog( getBaseFrame(), "'" + temp + "' is an invalid parameter.\nPlease try again."); setMaxRecordConfiguration(); } } } protected JMenu createHelpMenu() { JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('h'); helpMenu.add(createHelpProperties()); return helpMenu; } protected JMenuItem createHelpProperties() { final String title = "LogFactor5 Properties"; final JMenuItem result = new JMenuItem(title); result.setMnemonic('l'); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showPropertiesDialog(title); } }); return result; } protected void showPropertiesDialog(String title) { JOptionPane.showMessageDialog( _logMonitorFrame, _displayedLogBrokerProperties.toArray(), title, JOptionPane.PLAIN_MESSAGE ); } protected JMenu createEditMenu() { JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic('e'); editMenu.add(createEditFindMI()); editMenu.add(createEditFindNextMI()); editMenu.addSeparator(); editMenu.add(createEditSortNDCMI()); editMenu.add(createEditRestoreAllNDCMI()); return editMenu; } protected JMenuItem createEditFindNextMI() { JMenuItem editFindNextMI = new JMenuItem("Find Next"); editFindNextMI.setMnemonic('n'); editFindNextMI.setAccelerator(KeyStroke.getKeyStroke("F3")); editFindNextMI.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { findSearchText(); } }); return editFindNextMI; } protected JMenuItem createEditFindMI() { JMenuItem editFindMI = new JMenuItem("Find"); editFindMI.setMnemonic('f'); editFindMI.setAccelerator(KeyStroke.getKeyStroke("control F")); editFindMI.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { String inputValue = JOptionPane.showInputDialog( _logMonitorFrame, "Find text: ", "Search Record Messages", JOptionPane.QUESTION_MESSAGE ); setSearchText(inputValue); findSearchText(); } } ); return editFindMI; } // Added version 1.2 - Allows users to Sort Log Records by an // NDC text filter. A new LogRecordFilter was created to // sort the records. protected JMenuItem createEditSortNDCMI() { JMenuItem editSortNDCMI = new JMenuItem("Sort by NDC"); editSortNDCMI.setMnemonic('s'); editSortNDCMI.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { String inputValue = JOptionPane.showInputDialog( _logMonitorFrame, "Sort by this NDC: ", "Sort Log Records by NDC", JOptionPane.QUESTION_MESSAGE ); setNDCTextFilter(inputValue); sortByNDC(); _table.getFilteredLogTableModel().refresh(); updateStatusLabel(); } } ); return editSortNDCMI; } // Added in version 1.2 - Resets the LogRecordFilter back to default // filter. protected JMenuItem createEditRestoreAllNDCMI() { JMenuItem editRestoreAllNDCMI = new JMenuItem("Restore all NDCs"); editRestoreAllNDCMI.setMnemonic('r'); editRestoreAllNDCMI.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { _table.getFilteredLogTableModel().setLogRecordFilter(createLogRecordFilter()); // reset the text filter setNDCTextFilter(""); _table.getFilteredLogTableModel().refresh(); updateStatusLabel(); } } ); return editRestoreAllNDCMI; } protected JToolBar createToolBar() { JToolBar tb = new JToolBar(); tb.putClientProperty("JToolBar.isRollover", Boolean.TRUE); JComboBox fontCombo = new JComboBox(); JComboBox fontSizeCombo = new JComboBox(); _fontSizeCombo = fontSizeCombo; ClassLoader cl = this.getClass().getClassLoader(); if(cl == null) { cl = ClassLoader.getSystemClassLoader(); } URL newIconURL = cl.getResource("org/apache/log4j/lf5/viewer/" + "images/channelexplorer_new.gif"); ImageIcon newIcon = null; if (newIconURL != null) { newIcon = new ImageIcon(newIconURL); } JButton newButton = new JButton("Clear Log Table"); if (newIcon != null) { newButton.setIcon(newIcon); } newButton.setToolTipText("Clear Log Table."); //newButton.setBorder(BorderFactory.createEtchedBorder()); newButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { _table.clearLogRecords(); _categoryExplorerTree.getExplorerModel().resetAllNodeCounts(); updateStatusLabel(); clearDetailTextArea(); LogRecord.resetSequenceNumber(); } } ); Toolkit tk = Toolkit.getDefaultToolkit(); // This will actually grab all the fonts String[] fonts; if (_loadSystemFonts) { fonts = GraphicsEnvironment. getLocalGraphicsEnvironment().getAvailableFontFamilyNames(); } else { fonts = tk.getFontList(); } for (int j = 0; j < fonts.length; j++) { fontCombo.addItem(fonts[j]); } fontCombo.setSelectedItem(_fontName); fontCombo.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { JComboBox box = (JComboBox) e.getSource(); String font = (String) box.getSelectedItem(); _table.setFont(new Font(font, Font.PLAIN, _fontSize)); _fontName = font; } } ); fontSizeCombo.addItem("8"); fontSizeCombo.addItem("9"); fontSizeCombo.addItem("10"); fontSizeCombo.addItem("12"); fontSizeCombo.addItem("14"); fontSizeCombo.addItem("16"); fontSizeCombo.addItem("18"); fontSizeCombo.addItem("24"); fontSizeCombo.setSelectedItem(String.valueOf(_fontSize)); fontSizeCombo.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { JComboBox box = (JComboBox) e.getSource(); String size = (String) box.getSelectedItem(); int s = Integer.valueOf(size).intValue(); setFontSizeSilently(s); refreshDetailTextArea(); _fontSize = s; } } ); tb.add(new JLabel(" Font: ")); tb.add(fontCombo); tb.add(fontSizeCombo); tb.addSeparator(); tb.addSeparator(); tb.add(newButton); newButton.setAlignmentY(0.5f); newButton.setAlignmentX(0.5f); fontCombo.setMaximumSize(fontCombo.getPreferredSize()); fontSizeCombo.setMaximumSize( fontSizeCombo.getPreferredSize()); return (tb); } // protected void setView(String viewString, LogTable table) { // if (STANDARD_VIEW.equals(viewString)) { // table.setStandardView(); // } else if (COMPACT_VIEW.equals(viewString)) { // table.setCompactView(); // } else if (DETAILED_VIEW.equals(viewString)) { // table.setDetailedView(); // } else { // String message = viewString + "does not match a supported view."; // throw new IllegalArgumentException(message); // } // _currentView = viewString; // } protected void setView(String viewString, LogTable table) { if (DETAILED_VIEW.equals(viewString)) { table.setDetailedView(); } else { String message = viewString + "does not match a supported view."; throw new IllegalArgumentException(message); } _currentView = viewString; } protected JComboBox createLogLevelCombo() { JComboBox result = new JComboBox(); Iterator levels = getLogLevels(); while (levels.hasNext()) { result.addItem(levels.next()); } result.setSelectedItem(_leastSevereDisplayedLogLevel); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JComboBox box = (JComboBox) e.getSource(); LogLevel level = (LogLevel) box.getSelectedItem(); setLeastSevereDisplayedLogLevel(level); } }); result.setMaximumSize(result.getPreferredSize()); return result; } protected void setLeastSevereDisplayedLogLevel(LogLevel level) { if (level == null || _leastSevereDisplayedLogLevel == level) { return; // nothing to do } _leastSevereDisplayedLogLevel = level; _table.getFilteredLogTableModel().refresh(); updateStatusLabel(); } /** * Ensures that the Table's ScrollPane Viewport will "track" with updates * to the Table. When the vertical scroll bar is at its bottom anchor * and tracking is enabled then viewport will stay at the bottom most * point of the component. The purpose of this feature is to allow * a developer to watch the table as messages arrive and not have to * scroll after each new message arrives. When the vertical scroll bar * is at any other location, then no tracking will happen. * @deprecated tracking is now done automatically. */ protected void trackTableScrollPane() { // do nothing } protected void centerFrame(JFrame frame) { Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); Dimension comp = frame.getSize(); frame.setLocation(((screen.width - comp.width) / 2), ((screen.height - comp.height) / 2)); } /** * Uses a JFileChooser to select a file to opened with the * LF5 GUI. */ protected void requestOpen() { JFileChooser chooser; if (_fileLocation == null) { chooser = new JFileChooser(); } else { chooser = new JFileChooser(_fileLocation); } int returnVal = chooser.showOpenDialog(_logMonitorFrame); if (returnVal == JFileChooser.APPROVE_OPTION) { File f = chooser.getSelectedFile(); if (loadLogFile(f)) { _fileLocation = chooser.getSelectedFile(); _mruFileManager.set(f); updateMRUList(); } } } /** * Uses a Dialog box to accept a URL to a file to be opened * with the LF5 GUI. */ protected void requestOpenURL() { LogFactor5InputDialog inputDialog = new LogFactor5InputDialog( getBaseFrame(), "Open URL", "URL:"); String temp = inputDialog.getText(); if (temp != null) { if (temp.indexOf("://") == -1) { temp = "http://" + temp; } try { URL url = new URL(temp); if (loadLogFile(url)) { _mruFileManager.set(url); updateMRUList(); } } catch (MalformedURLException e) { LogFactor5ErrorDialog error = new LogFactor5ErrorDialog( getBaseFrame(), "Error reading URL."); } } } /** * Removes old file list and creates a new file list * with the updated MRU list. */ protected void updateMRUList() { JMenu menu = _logMonitorFrame.getJMenuBar().getMenu(0); menu.removeAll(); menu.add(createOpenMI()); menu.add(createOpenURLMI()); menu.addSeparator(); menu.add(createCloseMI()); createMRUFileListMI(menu); menu.addSeparator(); menu.add(createExitMI()); } protected void requestClose() { setCallSystemExitOnClose(false); closeAfterConfirm(); } /** * Opens a file in the MRU list. */ protected void requestOpenMRU(ActionEvent e) { String file = e.getActionCommand(); StringTokenizer st = new StringTokenizer(file); String num = st.nextToken().trim(); file = st.nextToken("\n"); try { int index = Integer.parseInt(num) - 1; InputStream in = _mruFileManager.getInputStream(index); LogFileParser lfp = new LogFileParser(in); lfp.parse(this); _mruFileManager.moveToTop(index); updateMRUList(); } catch (Exception me) { LogFactor5ErrorDialog error = new LogFactor5ErrorDialog( getBaseFrame(), "Unable to load file " + file); } } protected void requestExit() { _mruFileManager.save(); setCallSystemExitOnClose(true); closeAfterConfirm(); } protected void closeAfterConfirm() { StringBuffer message = new StringBuffer(); if (_callSystemExitOnClose == false) { message.append("Are you sure you want to close the logging "); message.append("console?\n"); message.append("(Note: This will not shut down the Virtual Machine,\n"); message.append("or the Swing event thread.)"); } else { message.append("Are you sure you want to exit?\n"); message.append("This will shut down the Virtual Machine.\n"); } String title = "Are you sure you want to dispose of the Logging Console?"; if (_callSystemExitOnClose == true) { title = "Are you sure you want to exit?"; } int value = JOptionPane.showConfirmDialog( _logMonitorFrame, message.toString(), title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null ); if (value == JOptionPane.OK_OPTION) { dispose(); } } protected Iterator getLogLevels() { return _levels.iterator(); } protected Iterator getLogTableColumns() { return _columns.iterator(); } /** * Loads and parses a log file. */ protected boolean loadLogFile(File file) { boolean ok = false; try { LogFileParser lfp = new LogFileParser(file); lfp.parse(this); ok = true; } catch (IOException e) { LogFactor5ErrorDialog error = new LogFactor5ErrorDialog( getBaseFrame(), "Error reading " + file.getName()); } return ok; } /** * Loads a parses a log file running on a server. */ protected boolean loadLogFile(URL url) { boolean ok = false; try { LogFileParser lfp = new LogFileParser(url.openStream()); lfp.parse(this); ok = true; } catch (IOException e) { LogFactor5ErrorDialog error = new LogFactor5ErrorDialog( getBaseFrame(), "Error reading URL:" + url.getFile()); } return ok; } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- class LogBrokerMonitorWindowAdaptor extends WindowAdapter { protected LogBrokerMonitor _monitor; public LogBrokerMonitorWindowAdaptor(LogBrokerMonitor monitor) { _monitor = monitor; } public void windowClosing(WindowEvent ev) { _monitor.requestClose(); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/LogFactor5ErrorDialog.java0000644000175000017500000000643711751454705030423 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; /** * LogFactor5ErrorDialog * * @author Richard Hurst * @author Brad Marlborough */ // Contributed by ThoughtWorks Inc. public class LogFactor5ErrorDialog extends LogFactor5Dialog { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public LogFactor5ErrorDialog(JFrame jframe, String message) { super(jframe, "Error", true); JButton ok = new JButton("Ok"); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hide(); } }); JPanel bottom = new JPanel(); bottom.setLayout(new FlowLayout()); bottom.add(ok); JPanel main = new JPanel(); main.setLayout(new GridBagLayout()); wrapStringOnPanel(message, main); getContentPane().add(main, BorderLayout.CENTER); getContentPane().add(bottom, BorderLayout.SOUTH); show(); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces //-------------------------------------------------------------------------- }apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/LogTableRowRenderer.java0000644000175000017500000000710011751454705030160 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer; import java.awt.Color; import java.awt.Component; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import org.apache.log4j.lf5.LogLevel; import org.apache.log4j.lf5.LogRecord; /** * LogTableRowRenderer * * @author Michael J. Sikorsky * @author Robert Shaw * @author Brad Marlborough */ // Contributed by ThoughtWorks Inc. public class LogTableRowRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = -3951639953706443213L; //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected boolean _highlightFatal = true; protected Color _color = new Color(230, 230, 230); //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { if ((row % 2) == 0) { setBackground(_color); } else { setBackground(Color.white); } FilteredLogTableModel model = (FilteredLogTableModel) table.getModel(); LogRecord record = model.getFilteredRecord(row); setForeground(getLogLevelColor(record.getLevel())); return (super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col)); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- protected Color getLogLevelColor(LogLevel level) { return (Color) LogLevel.getLogLevelColorMap().get(level); } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/FilteredLogTableModel.java0000644000175000017500000001675711751454705030463 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer; import org.apache.log4j.lf5.LogRecord; import org.apache.log4j.lf5.LogRecordFilter; import org.apache.log4j.lf5.PassingLogRecordFilter; import javax.swing.table.AbstractTableModel; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; /** * A TableModel for LogRecords which includes filtering support. * * @author Richard Wan * @author Brent Sprecher */ // Contributed by ThoughtWorks Inc. public class FilteredLogTableModel extends AbstractTableModel { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected LogRecordFilter _filter = new PassingLogRecordFilter(); protected List _allRecords = new ArrayList(); protected List _filteredRecords; protected int _maxNumberOfLogRecords = 5000; protected String[] _colNames = {"Date", "Thread", "Message #", "Level", "NDC", "Category", "Message", "Location", "Thrown"}; //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public FilteredLogTableModel() { super(); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public void setLogRecordFilter(LogRecordFilter filter) { _filter = filter; } public LogRecordFilter getLogRecordFilter() { return _filter; } public String getColumnName(int i) { return _colNames[i]; } public int getColumnCount() { return _colNames.length; } public int getRowCount() { return getFilteredRecords().size(); } public int getTotalRowCount() { return _allRecords.size(); } public Object getValueAt(int row, int col) { LogRecord record = getFilteredRecord(row); return getColumn(col, record); } public void setMaxNumberOfLogRecords(int maxNumRecords) { if (maxNumRecords > 0) { _maxNumberOfLogRecords = maxNumRecords; } } public synchronized boolean addLogRecord(LogRecord record) { _allRecords.add(record); if (_filter.passes(record) == false) { return false; } getFilteredRecords().add(record); fireTableRowsInserted(getRowCount(), getRowCount()); trimRecords(); return true; } /** * Forces the LogTableModel to requery its filters to determine * which records to display. */ public synchronized void refresh() { _filteredRecords = createFilteredRecordsList(); fireTableDataChanged(); } public synchronized void fastRefresh() { _filteredRecords.remove(0); fireTableRowsDeleted(0, 0); } /** * Clears all records from the LogTableModel */ public synchronized void clear() { _allRecords.clear(); _filteredRecords.clear(); fireTableDataChanged(); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- protected List getFilteredRecords() { if (_filteredRecords == null) { refresh(); } return _filteredRecords; } protected List createFilteredRecordsList() { List result = new ArrayList(); Iterator records = _allRecords.iterator(); LogRecord current; while (records.hasNext()) { current = (LogRecord) records.next(); if (_filter.passes(current)) { result.add(current); } } return result; } protected LogRecord getFilteredRecord(int row) { List records = getFilteredRecords(); int size = records.size(); if (row < size) { return (LogRecord) records.get(row); } // a minor problem has happened. JTable has asked for // a row outside the bounds, because the size of // _filteredRecords has changed while it was looping. // return the last row. return (LogRecord) records.get(size - 1); } protected Object getColumn(int col, LogRecord lr) { if (lr == null) { return "NULL Column"; } String date = new Date(lr.getMillis()).toString(); switch (col) { case 0: return date + " (" + lr.getMillis() + ")"; case 1: return lr.getThreadDescription(); case 2: return new Long(lr.getSequenceNumber()); case 3: return lr.getLevel(); case 4: return lr.getNDC(); case 5: return lr.getCategory(); case 6: return lr.getMessage(); case 7: return lr.getLocation(); case 8: return lr.getThrownStackTrace(); default: String message = "The column number " + col + "must be between 0 and 8"; throw new IllegalArgumentException(message); } } // We don't want the amount of rows to grow without bound, // leading to a out-of-memory-exception. Especially not good // in a production environment :) // This method & clearLogRecords() are synchronized so we don't // delete rows that don't exist. protected void trimRecords() { if (needsTrimming()) { trimOldestRecords(); } } protected boolean needsTrimming() { return (_allRecords.size() > _maxNumberOfLogRecords); } protected void trimOldestRecords() { synchronized (_allRecords) { int trim = numberOfRecordsToTrim(); if (trim > 1) { List oldRecords = _allRecords.subList(0, trim); oldRecords.clear(); refresh(); } else { _allRecords.remove(0); fastRefresh(); } } } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- private int numberOfRecordsToTrim() { return _allRecords.size() - _maxNumberOfLogRecords; } //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/LF5SwingUtils.java0000644000175000017500000001217711751454705026741 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer; import java.awt.Adjustable; import javax.swing.JComponent; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.table.TableModel; /** * Provides methods to accomplish common yet non-trivial tasks * with Swing. Obvious implementations of these methods have been * tried and failed. * * @author Richard Wan */ // Contributed by ThoughtWorks Inc. public class LF5SwingUtils { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** * Selects a the specified row in the specified JTable and scrolls * the specified JScrollpane to the newly selected row. More importantly, * the call to repaint() delayed long enough to have the table * properly paint the newly selected row which may be offscre * @param table should belong to the specified JScrollPane */ public static void selectRow(int row, JTable table, JScrollPane pane) { if (table == null || pane == null) { return; } if (contains(row, table.getModel()) == false) { return; } moveAdjustable(row * table.getRowHeight(), pane.getVerticalScrollBar()); selectRow(row, table.getSelectionModel()); // repaint must be done later because moveAdjustable // posts requests to the swing thread which must execute before // the repaint logic gets executed. repaintLater(table); } /** * Makes the specified Adjustable track if the view area expands and * the specified Adjustable is located near the of the view. */ public static void makeScrollBarTrack(Adjustable scrollBar) { if (scrollBar == null) { return; } scrollBar.addAdjustmentListener(new TrackingAdjustmentListener()); } /** * Makes the vertical scroll bar of the specified JScrollPane * track if the view expands (e.g. if rows are added to an underlying * table). */ public static void makeVerticalScrollBarTrack(JScrollPane pane) { if (pane == null) { return; } makeScrollBarTrack(pane.getVerticalScrollBar()); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- protected static boolean contains(int row, TableModel model) { if (model == null) { return false; } if (row < 0) { return false; } if (row >= model.getRowCount()) { return false; } return true; } protected static void selectRow(int row, ListSelectionModel model) { if (model == null) { return; } model.setSelectionInterval(row, row); } protected static void moveAdjustable(int location, Adjustable scrollBar) { if (scrollBar == null) { return; } scrollBar.setValue(location); } /** * Work around for JTable/viewport bug. * @link http://developer.java.sun.com/developer/bugParade/bugs/4205145.html */ protected static void repaintLater(final JComponent component) { SwingUtilities.invokeLater(new Runnable() { public void run() { component.repaint(); } }); } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/LogTableModel.java0000644000175000017500000000535411751454705026773 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer; import javax.swing.table.DefaultTableModel; /** * LogTableModel * * @author Michael J. Sikorsky * @author Robert Shaw */ // Contributed by ThoughtWorks Inc. public class LogTableModel extends DefaultTableModel { private static final long serialVersionUID = 3593300685868700894L; //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public LogTableModel(Object[] colNames, int numRows) { super(colNames, numRows); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public boolean isCellEditable(int row, int column) { return (false); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/configure/0000755000175000017500000000000012126647422025425 5ustar tonytony././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/configure/ConfigurationManager.javaapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/configure/ConfigurationManager0000644000175000017500000004101511751454704031455 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer.configure; import java.awt.Color; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.JCheckBoxMenuItem; import javax.swing.tree.TreePath; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.log4j.lf5.LogLevel; import org.apache.log4j.lf5.LogLevelFormatException; import org.apache.log4j.lf5.viewer.LogBrokerMonitor; import org.apache.log4j.lf5.viewer.LogTable; import org.apache.log4j.lf5.viewer.LogTableColumn; import org.apache.log4j.lf5.viewer.LogTableColumnFormatException; import org.apache.log4j.lf5.viewer.categoryexplorer.CategoryExplorerModel; import org.apache.log4j.lf5.viewer.categoryexplorer.CategoryExplorerTree; import org.apache.log4j.lf5.viewer.categoryexplorer.CategoryNode; import org.apache.log4j.lf5.viewer.categoryexplorer.CategoryPath; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** *

ConfigurationManager handles the storage and retrival of the state of * the CategoryExplorer * * @author Richard Hurst * @author Brad Marlborough */ // Contributed by ThoughtWorks Inc. public class ConfigurationManager extends Object { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- private static final String CONFIG_FILE_NAME = "lf5_configuration.xml"; private static final String NAME = "name"; private static final String PATH = "path"; private static final String SELECTED = "selected"; private static final String EXPANDED = "expanded"; private static final String CATEGORY = "category"; private static final String FIRST_CATEGORY_NAME = "Categories"; private static final String LEVEL = "level"; private static final String COLORLEVEL = "colorlevel"; private static final String RED = "red"; private static final String GREEN = "green"; private static final String BLUE = "blue"; private static final String COLUMN = "column"; private static final String NDCTEXTFILTER = "searchtext"; //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- private LogBrokerMonitor _monitor = null; private LogTable _table = null; //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public ConfigurationManager(LogBrokerMonitor monitor, LogTable table) { super(); _monitor = monitor; _table = table; load(); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public void save() { CategoryExplorerModel model = _monitor.getCategoryExplorerTree().getExplorerModel(); CategoryNode root = model.getRootCategoryNode(); StringBuffer xml = new StringBuffer(2048); openXMLDocument(xml); openConfigurationXML(xml); processLogRecordFilter(_monitor.getNDCTextFilter(), xml); processLogLevels(_monitor.getLogLevelMenuItems(), xml); processLogLevelColors(_monitor.getLogLevelMenuItems(), LogLevel.getLogLevelColorMap(), xml); processLogTableColumns(LogTableColumn.getLogTableColumns(), xml); processConfigurationNode(root, xml); closeConfigurationXML(xml); store(xml.toString()); } public void reset() { deleteConfigurationFile(); collapseTree(); selectAllNodes(); } public static String treePathToString(TreePath path) { // count begins at one so as to not include the 'Categories' - root category StringBuffer sb = new StringBuffer(); CategoryNode n = null; Object[] objects = path.getPath(); for (int i = 1; i < objects.length; i++) { n = (CategoryNode) objects[i]; if (i > 1) { sb.append("."); } sb.append(n.getTitle()); } return sb.toString(); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- protected void load() { File file = new File(getFilename()); if (file.exists()) { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory. newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(file); processRecordFilter(doc); processCategories(doc); processLogLevels(doc); processLogLevelColors(doc); processLogTableColumns(doc); } catch (Exception e) { // ignore all error and just continue as if there was no // configuration xml file but do report a message System.err.println("Unable process configuration file at " + getFilename() + ". Error Message=" + e.getMessage()); } } } // Added in version 1.2 - reads in the NDC text filter from the // xml configuration file. If the value of the filter is not null // or an empty string ("") then the manager will set the LogBrokerMonitor's // LogRecordFilter to use the NDC LogRecordFilter. Otherwise, the // LogBrokerMonitor will use the default LogRecordFilter. protected void processRecordFilter(Document doc) { NodeList nodeList = doc.getElementsByTagName(NDCTEXTFILTER); // there is only one value stored Node n = nodeList.item(0); // add check for backwards compatibility as this feature was added in // version 1.2 if (n == null) { return; } NamedNodeMap map = n.getAttributes(); String text = getValue(map, NAME); if (text == null || text.equals("")) { return; } _monitor.setNDCLogRecordFilter(text); } protected void processCategories(Document doc) { CategoryExplorerTree tree = _monitor.getCategoryExplorerTree(); CategoryExplorerModel model = tree.getExplorerModel(); NodeList nodeList = doc.getElementsByTagName(CATEGORY); // determine where the starting node is NamedNodeMap map = nodeList.item(0).getAttributes(); int j = (getValue(map, NAME).equalsIgnoreCase(FIRST_CATEGORY_NAME)) ? 1 : 0; // iterate backwards throught the nodeList so that expansion of the // list can occur for (int i = nodeList.getLength() - 1; i >= j; i--) { Node n = nodeList.item(i); map = n.getAttributes(); CategoryNode chnode = model.addCategory(new CategoryPath(getValue(map, PATH))); chnode.setSelected((getValue(map, SELECTED).equalsIgnoreCase("true")) ? true : false); if (getValue(map, EXPANDED).equalsIgnoreCase("true")) ; tree.expandPath(model.getTreePathToRoot(chnode)); } } protected void processLogLevels(Document doc) { NodeList nodeList = doc.getElementsByTagName(LEVEL); Map menuItems = _monitor.getLogLevelMenuItems(); for (int i = 0; i < nodeList.getLength(); i++) { Node n = nodeList.item(i); NamedNodeMap map = n.getAttributes(); String name = getValue(map, NAME); try { JCheckBoxMenuItem item = (JCheckBoxMenuItem) menuItems.get(LogLevel.valueOf(name)); item.setSelected(getValue(map, SELECTED).equalsIgnoreCase("true")); } catch (LogLevelFormatException e) { // ignore it will be on by default. } } } protected void processLogLevelColors(Document doc) { NodeList nodeList = doc.getElementsByTagName(COLORLEVEL); LogLevel.getLogLevelColorMap(); for (int i = 0; i < nodeList.getLength(); i++) { Node n = nodeList.item(i); // check for backwards compatibility since this feature was added // in version 1.3 if (n == null) { return; } NamedNodeMap map = n.getAttributes(); String name = getValue(map, NAME); try { LogLevel level = LogLevel.valueOf(name); int red = Integer.parseInt(getValue(map, RED)); int green = Integer.parseInt(getValue(map, GREEN)); int blue = Integer.parseInt(getValue(map, BLUE)); Color c = new Color(red, green, blue); if (level != null) { level.setLogLevelColorMap(level, c); } } catch (LogLevelFormatException e) { // ignore it will be on by default. } } } protected void processLogTableColumns(Document doc) { NodeList nodeList = doc.getElementsByTagName(COLUMN); Map menuItems = _monitor.getLogTableColumnMenuItems(); List selectedColumns = new ArrayList(); for (int i = 0; i < nodeList.getLength(); i++) { Node n = nodeList.item(i); // check for backwards compatibility since this feature was added // in version 1.3 if (n == null) { return; } NamedNodeMap map = n.getAttributes(); String name = getValue(map, NAME); try { LogTableColumn column = LogTableColumn.valueOf(name); JCheckBoxMenuItem item = (JCheckBoxMenuItem) menuItems.get(column); item.setSelected(getValue(map, SELECTED).equalsIgnoreCase("true")); if (item.isSelected()) { selectedColumns.add(column); } } catch (LogTableColumnFormatException e) { // ignore it will be on by default. } if (selectedColumns.isEmpty()) { _table.setDetailedView(); } else { _table.setView(selectedColumns); } } } protected String getValue(NamedNodeMap map, String attr) { Node n = map.getNamedItem(attr); return n.getNodeValue(); } protected void collapseTree() { // collapse everything except the first category CategoryExplorerTree tree = _monitor.getCategoryExplorerTree(); for (int i = tree.getRowCount() - 1; i > 0; i--) { tree.collapseRow(i); } } protected void selectAllNodes() { CategoryExplorerModel model = _monitor.getCategoryExplorerTree().getExplorerModel(); CategoryNode root = model.getRootCategoryNode(); Enumeration all = root.breadthFirstEnumeration(); CategoryNode n = null; while (all.hasMoreElements()) { n = (CategoryNode) all.nextElement(); n.setSelected(true); } } protected void store(String s) { try { PrintWriter writer = new PrintWriter(new FileWriter(getFilename())); writer.print(s); writer.close(); } catch (IOException e) { // do something with this error. e.printStackTrace(); } } protected void deleteConfigurationFile() { try { File f = new File(getFilename()); if (f.exists()) { f.delete(); } } catch (SecurityException e) { System.err.println("Cannot delete " + getFilename() + " because a security violation occured."); } } protected String getFilename() { String home = System.getProperty("user.home"); String sep = System.getProperty("file.separator"); return home + sep + "lf5" + sep + CONFIG_FILE_NAME; } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- private void processConfigurationNode(CategoryNode node, StringBuffer xml) { CategoryExplorerModel model = _monitor.getCategoryExplorerTree().getExplorerModel(); Enumeration all = node.breadthFirstEnumeration(); CategoryNode n = null; while (all.hasMoreElements()) { n = (CategoryNode) all.nextElement(); exportXMLElement(n, model.getTreePathToRoot(n), xml); } } private void processLogLevels(Map logLevelMenuItems, StringBuffer xml) { xml.append("\t\r\n"); Iterator it = logLevelMenuItems.keySet().iterator(); while (it.hasNext()) { LogLevel level = (LogLevel) it.next(); JCheckBoxMenuItem item = (JCheckBoxMenuItem) logLevelMenuItems.get(level); exportLogLevelXMLElement(level.getLabel(), item.isSelected(), xml); } xml.append("\t\r\n"); } private void processLogLevelColors(Map logLevelMenuItems, Map logLevelColors, StringBuffer xml) { xml.append("\t\r\n"); // iterate through the list of log levels being used (log4j, jdk1.4, custom levels) Iterator it = logLevelMenuItems.keySet().iterator(); while (it.hasNext()) { LogLevel level = (LogLevel) it.next(); // for each level, get the associated color from the log level color map Color color = (Color) logLevelColors.get(level); exportLogLevelColorXMLElement(level.getLabel(), color, xml); } xml.append("\t\r\n"); } private void processLogTableColumns(List logTableColumnMenuItems, StringBuffer xml) { xml.append("\t\r\n"); Iterator it = logTableColumnMenuItems.iterator(); while (it.hasNext()) { LogTableColumn column = (LogTableColumn) it.next(); JCheckBoxMenuItem item = _monitor.getTableColumnMenuItem(column); exportLogTableColumnXMLElement(column.getLabel(), item.isSelected(), xml); } xml.append("\t\r\n"); } // Added in version 1.2 - stores the NDC text filter in the xml file // for future use. private void processLogRecordFilter(String text, StringBuffer xml) { xml.append("\t<").append(NDCTEXTFILTER).append(" "); xml.append(NAME).append("=\"").append(text).append("\""); xml.append("/>\r\n"); } private void openXMLDocument(StringBuffer xml) { xml.append("\r\n"); } private void openConfigurationXML(StringBuffer xml) { xml.append("\r\n"); } private void closeConfigurationXML(StringBuffer xml) { xml.append("\r\n"); } private void exportXMLElement(CategoryNode node, TreePath path, StringBuffer xml) { CategoryExplorerTree tree = _monitor.getCategoryExplorerTree(); xml.append("\t<").append(CATEGORY).append(" "); xml.append(NAME).append("=\"").append(node.getTitle()).append("\" "); xml.append(PATH).append("=\"").append(treePathToString(path)).append("\" "); xml.append(EXPANDED).append("=\"").append(tree.isExpanded(path)).append("\" "); xml.append(SELECTED).append("=\"").append(node.isSelected()).append("\"/>\r\n"); } private void exportLogLevelXMLElement(String label, boolean selected, StringBuffer xml) { xml.append("\t\t<").append(LEVEL).append(" ").append(NAME); xml.append("=\"").append(label).append("\" "); xml.append(SELECTED).append("=\"").append(selected); xml.append("\"/>\r\n"); } private void exportLogLevelColorXMLElement(String label, Color color, StringBuffer xml) { xml.append("\t\t<").append(COLORLEVEL).append(" ").append(NAME); xml.append("=\"").append(label).append("\" "); xml.append(RED).append("=\"").append(color.getRed()).append("\" "); xml.append(GREEN).append("=\"").append(color.getGreen()).append("\" "); xml.append(BLUE).append("=\"").append(color.getBlue()); xml.append("\"/>\r\n"); } private void exportLogTableColumnXMLElement(String label, boolean selected, StringBuffer xml) { xml.append("\t\t<").append(COLUMN).append(" ").append(NAME); xml.append("=\"").append(label).append("\" "); xml.append(SELECTED).append("=\"").append(selected); xml.append("\"/>\r\n"); } //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/configure/MRUFileManager.java0000644000175000017500000001766411751454704031046 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer.configure; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.URL; import java.util.Iterator; import java.util.LinkedList; /** *

MRUFileManager handles the storage and retrival the most * recently opened log files. * * @author Brad Marlborough * @author Richard Hurst */ // Contributed by ThoughtWorks Inc. public class MRUFileManager { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- private static final String CONFIG_FILE_NAME = "mru_file_manager"; private static final int DEFAULT_MAX_SIZE = 3; //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- private int _maxSize = 0; private LinkedList _mruFileList; //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- public MRUFileManager() { load(); setMaxSize(DEFAULT_MAX_SIZE); } public MRUFileManager(int maxSize) { load(); setMaxSize(maxSize); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** * Saves a list of MRU files out to a file. */ public void save() { File file = new File(getFilename()); try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file)); oos.writeObject(_mruFileList); oos.flush(); oos.close(); } catch (Exception e) { // do nothing e.printStackTrace(); } } /** * Gets the size of the MRU file list. */ public int size() { return _mruFileList.size(); } /** * Returns a particular file name stored in a MRU file * list based on an index value. */ public Object getFile(int index) { if (index < size()) { return _mruFileList.get(index); } return null; } /** * Returns a input stream to the resource at the specified index */ public InputStream getInputStream(int index) throws IOException, FileNotFoundException { if (index < size()) { Object o = getFile(index); if (o instanceof File) { return getInputStream((File) o); } else { return getInputStream((URL) o); } } return null; } /** * Adds a file name to the MRU file list. */ public void set(File file) { setMRU(file); } /** * Adds a url to the MRU file list. */ public void set(URL url) { setMRU(url); } /** * Gets the list of files stored in the MRU file list. */ public String[] getMRUFileList() { if (size() == 0) { return null; } String[] ss = new String[size()]; for (int i = 0; i < size(); i++) { Object o = getFile(i); if (o instanceof File) { ss[i] = ((File) o).getAbsolutePath(); } else // must be a url { ss[i] = o.toString(); } } return ss; } /** * Moves the the index to the top of the MRU List * * @param index The index to be first in the mru list */ public void moveToTop(int index) { _mruFileList.add(0, _mruFileList.remove(index)); } /** * Creates the directory where the MRU file list will be written. * The "lf5" directory is created in the Documents and Settings * directory on Windows 2000 machines and where ever the user.home * variable points on all other platforms. */ public static void createConfigurationDirectory() { String home = System.getProperty("user.home"); String sep = System.getProperty("file.separator"); File f = new File(home + sep + "lf5"); if (!f.exists()) { try { f.mkdir(); } catch (SecurityException e) { e.printStackTrace(); } } } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- /** * Gets an input stream for the corresponding file. * * @param file The file to create the input stream from. * @return InputStream */ protected InputStream getInputStream(File file) throws IOException, FileNotFoundException { BufferedInputStream reader = new BufferedInputStream(new FileInputStream(file)); return reader; } /** * Gets an input stream for the corresponding URL. * * @param url The url to create the input stream from. * @return InputStream */ protected InputStream getInputStream(URL url) throws IOException { return url.openStream(); } /** * Adds an object to the mru. */ protected void setMRU(Object o) { int index = _mruFileList.indexOf(o); if (index == -1) { _mruFileList.add(0, o); setMaxSize(_maxSize); } else { moveToTop(index); } } /** * Loads the MRU file list in from a file and stores it in a LinkedList. * If no file exists, a new LinkedList is created. */ protected void load() { createConfigurationDirectory(); File file = new File(getFilename()); if (file.exists()) { try { ObjectInputStream ois = new ObjectInputStream( new FileInputStream(file)); _mruFileList = (LinkedList) ois.readObject(); ois.close(); // check that only files and url are in linked list Iterator it = _mruFileList.iterator(); while (it.hasNext()) { Object o = it.next(); if (!(o instanceof File) && !(o instanceof URL)) { it.remove(); } } } catch (Exception e) { _mruFileList = new LinkedList(); } } else { _mruFileList = new LinkedList(); } } protected String getFilename() { String home = System.getProperty("user.home"); String sep = System.getProperty("file.separator"); return home + sep + "lf5" + sep + CONFIG_FILE_NAME; } /** * Ensures that the MRU list will have a MaxSize. */ protected void setMaxSize(int maxSize) { if (maxSize < _mruFileList.size()) { for (int i = 0; i < _mruFileList.size() - maxSize; i++) { _mruFileList.removeLast(); } } _maxSize = maxSize; } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces //-------------------------------------------------------------------------- }apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/LogFactor5Dialog.java0000644000175000017500000001251211751454705027400 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Label; import java.awt.Toolkit; import java.awt.Window; import javax.swing.JDialog; import javax.swing.JFrame; /** * LogFactor5Dialog * * @author Richard Hurst * @author Brad Marlborough */ // Contributed by ThoughtWorks Inc. public abstract class LogFactor5Dialog extends JDialog { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- protected static final Font DISPLAY_FONT = new Font("Arial", Font.BOLD, 12); //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- protected LogFactor5Dialog(JFrame jframe, String message, boolean modal) { super(jframe, message, modal); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public void show() { pack(); minimumSizeDialog(this, 200, 100); centerWindow(this); super.show(); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- protected void centerWindow(Window win) { Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize(); // If larger than screen, reduce window width or height if (screenDim.width < win.getSize().width) { win.setSize(screenDim.width, win.getSize().height); } if (screenDim.height < win.getSize().height) { win.setSize(win.getSize().width, screenDim.height); } // Center Frame, Dialogue or Window on screen int x = (screenDim.width - win.getSize().width) / 2; int y = (screenDim.height - win.getSize().height) / 2; win.setLocation(x, y); } protected void wrapStringOnPanel(String message, Container container) { GridBagConstraints c = getDefaultConstraints(); c.gridwidth = GridBagConstraints.REMAINDER; // Insets() args are top, left, bottom, right c.insets = new Insets(0, 0, 0, 0); GridBagLayout gbLayout = (GridBagLayout) container.getLayout(); while (message.length() > 0) { int newLineIndex = message.indexOf('\n'); String line; if (newLineIndex >= 0) { line = message.substring(0, newLineIndex); message = message.substring(newLineIndex + 1); } else { line = message; message = ""; } Label label = new Label(line); label.setFont(DISPLAY_FONT); gbLayout.setConstraints(label, c); container.add(label); } } protected GridBagConstraints getDefaultConstraints() { GridBagConstraints constraints = new GridBagConstraints(); constraints.weightx = 1.0; constraints.weighty = 1.0; constraints.gridheight = 1; // One row high // Insets() args are top, left, bottom, right constraints.insets = new Insets(4, 4, 4, 4); // fill of NONE means do not change size constraints.fill = GridBagConstraints.NONE; // WEST means align left constraints.anchor = GridBagConstraints.WEST; return constraints; } protected void minimumSizeDialog(Component component, int minWidth, int minHeight) { // set the min width if (component.getSize().width < minWidth) component.setSize(minWidth, component.getSize().height); // set the min height if (component.getSize().height < minHeight) component.setSize(component.getSize().width, minHeight); } //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces //-------------------------------------------------------------------------- }apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/LogTableColumn.java0000644000175000017500000001251711751454705027167 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * LogTableColumn * * @author Michael J. Sikorsky * @author Brad Marlborough */ // Contributed by ThoughtWorks Inc. public class LogTableColumn implements java.io.Serializable { private static final long serialVersionUID = -4275827753626456547L; // log4j table columns. public final static LogTableColumn DATE = new LogTableColumn("Date"); public final static LogTableColumn THREAD = new LogTableColumn("Thread"); public final static LogTableColumn MESSAGE_NUM = new LogTableColumn("Message #"); public final static LogTableColumn LEVEL = new LogTableColumn("Level"); public final static LogTableColumn NDC = new LogTableColumn("NDC"); public final static LogTableColumn CATEGORY = new LogTableColumn("Category"); public final static LogTableColumn MESSAGE = new LogTableColumn("Message"); public final static LogTableColumn LOCATION = new LogTableColumn("Location"); public final static LogTableColumn THROWN = new LogTableColumn("Thrown"); //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected String _label; //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- private static LogTableColumn[] _log4JColumns; private static Map _logTableColumnMap; //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- static { _log4JColumns = new LogTableColumn[]{DATE, THREAD, MESSAGE_NUM, LEVEL, NDC, CATEGORY, MESSAGE, LOCATION, THROWN}; _logTableColumnMap = new HashMap(); for (int i = 0; i < _log4JColumns.length; i++) { _logTableColumnMap.put(_log4JColumns[i].getLabel(), _log4JColumns[i]); } } public LogTableColumn(String label) { _label = label; } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** * Return the Label of the LogLevel. */ public String getLabel() { return _label; } /** * Convert a column label into a LogTableColumn object. * * @param column The label of a level to be converted into a LogTableColumn. * @return LogTableColumn The LogTableColumn with a label equal to column. * @throws LogTableColumnFormatException Is thrown when the column can not be * converted into a LogTableColumn. */ public static LogTableColumn valueOf(String column) throws LogTableColumnFormatException { LogTableColumn tableColumn = null; if (column != null) { column = column.trim(); tableColumn = (LogTableColumn) _logTableColumnMap.get(column); } if (tableColumn == null) { StringBuffer buf = new StringBuffer(); buf.append("Error while trying to parse (" + column + ") into"); buf.append(" a LogTableColumn."); throw new LogTableColumnFormatException(buf.toString()); } return tableColumn; } public boolean equals(Object o) { boolean equals = false; if (o instanceof LogTableColumn) { if (this.getLabel() == ((LogTableColumn) o).getLabel()) { equals = true; } } return equals; } public int hashCode() { return _label.hashCode(); } public String toString() { return _label; } /** * @return A List of LogTableColumn/code> objects that map * to log4j Column objects. */ public static List getLogTableColumns() { return Arrays.asList(_log4JColumns); } public static LogTableColumn[] getLogTableColumnArray() { return _log4JColumns; } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/viewer/LogFactor5InputDialog.java0000644000175000017500000001146711751454705030430 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5.viewer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; /** * LogFactor5InputDialog * * Creates a popup input dialog box so that users can enter * a URL to open a log file from. * * @author Richard Hurst * @author Brad Marlborough */ // Contributed by ThoughtWorks Inc. public class LogFactor5InputDialog extends LogFactor5Dialog { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- public static final int SIZE = 30; //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- private JTextField _textField; //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- /** * Configures an input dialog box using a defualt size for the text field. * param jframe the frame where the dialog will be loaded from. * param title the title of the dialog box. * param label the label to be put in the dialog box. */ public LogFactor5InputDialog(JFrame jframe, String title, String label) { this(jframe, title, label, SIZE); } /** * Configures an input dialog box. * param jframe the frame where the dialog will be loaded from. * param title the title of the dialog box. * param label the label to be put in the dialog box. * param size the size of the text field. */ public LogFactor5InputDialog(JFrame jframe, String title, String label, int size) { super(jframe, title, true); JPanel bottom = new JPanel(); bottom.setLayout(new FlowLayout()); JPanel main = new JPanel(); main.setLayout(new FlowLayout()); main.add(new JLabel(label)); _textField = new JTextField(size); main.add(_textField); addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { hide(); } } }); JButton ok = new JButton("Ok"); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hide(); } }); JButton cancel = new JButton("Cancel"); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hide(); // set the text field to blank just in case // a file was selected before the Cancel // button was pressed. _textField.setText(""); } }); bottom.add(ok); bottom.add(cancel); getContentPane().add(main, BorderLayout.CENTER); getContentPane().add(bottom, BorderLayout.SOUTH); pack(); centerWindow(this); show(); } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- public String getText() { String s = _textField.getText(); if (s != null && s.trim().length() == 0) { return null; } return s; } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces //-------------------------------------------------------------------------- }apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/LogLevel.java0000644000175000017500000002117511751454705024530 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5; import java.awt.Color; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * The LogLevel class defines a set of standard logging levels. * * The logging Level objects are ordered and are specified by ordered * integers. Enabling logging at a given level also enables logging at all * higher levels. * * @author Michael J. Sikorsky * @author Robert Shaw * @author Brent Sprecher * @author Richard Hurst * @author Brad Marlborough */ // Contributed by ThoughtWorks Inc. public class LogLevel implements java.io.Serializable { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- // log4j log levels. public final static LogLevel FATAL = new LogLevel("FATAL", 0); public final static LogLevel ERROR = new LogLevel("ERROR", 1); public final static LogLevel WARN = new LogLevel("WARN", 2); public final static LogLevel INFO = new LogLevel("INFO", 3); public final static LogLevel DEBUG = new LogLevel("DEBUG", 4); // jdk1.4 log levels NOTE: also includes INFO public final static LogLevel SEVERE = new LogLevel("SEVERE", 1); public final static LogLevel WARNING = new LogLevel("WARNING", 2); public final static LogLevel CONFIG = new LogLevel("CONFIG", 4); public final static LogLevel FINE = new LogLevel("FINE", 5); public final static LogLevel FINER = new LogLevel("FINER", 6); public final static LogLevel FINEST = new LogLevel("FINEST", 7); //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected String _label; protected int _precedence; //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- private static LogLevel[] _log4JLevels; private static LogLevel[] _jdk14Levels; private static LogLevel[] _allDefaultLevels; private static Map _logLevelMap; private static Map _logLevelColorMap; private static Map _registeredLogLevelMap = new HashMap(); //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- static { _log4JLevels = new LogLevel[]{FATAL, ERROR, WARN, INFO, DEBUG}; _jdk14Levels = new LogLevel[]{SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST}; _allDefaultLevels = new LogLevel[]{FATAL, ERROR, WARN, INFO, DEBUG, SEVERE, WARNING, CONFIG, FINE, FINER, FINEST}; _logLevelMap = new HashMap(); for (int i = 0; i < _allDefaultLevels.length; i++) { _logLevelMap.put(_allDefaultLevels[i].getLabel(), _allDefaultLevels[i]); } // prepopulate map with levels and text color of black _logLevelColorMap = new HashMap(); for (int i = 0; i < _allDefaultLevels.length; i++) { _logLevelColorMap.put(_allDefaultLevels[i], Color.black); } } public LogLevel(String label, int precedence) { _label = label; _precedence = precedence; } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** * Return the Label of the LogLevel. */ public String getLabel() { return _label; } /** * Returns true if the level supplied is encompassed by this level. * For example, LogLevel.SEVERE encompasses no other LogLevels and * LogLevel.FINE encompasses all other LogLevels. By definition, * a LogLevel encompasses itself. */ public boolean encompasses(LogLevel level) { if (level.getPrecedence() <= getPrecedence()) { return true; } return false; } /** * Convert a log level label into a LogLevel object. * * @param level The label of a level to be converted into a LogLevel. * @return LogLevel The LogLevel with a label equal to level. * @throws LogLevelFormatException Is thrown when the level can not be * converted into a LogLevel. */ public static LogLevel valueOf(String level) throws LogLevelFormatException { LogLevel logLevel = null; if (level != null) { level = level.trim().toUpperCase(); logLevel = (LogLevel) _logLevelMap.get(level); } // Didn't match, Check for registered LogLevels if (logLevel == null && _registeredLogLevelMap.size() > 0) { logLevel = (LogLevel) _registeredLogLevelMap.get(level); } if (logLevel == null) { StringBuffer buf = new StringBuffer(); buf.append("Error while trying to parse (" + level + ") into"); buf.append(" a LogLevel."); throw new LogLevelFormatException(buf.toString()); } return logLevel; } /** * Registers a used defined LogLevel. * * @param logLevel The log level to be registered. Cannot be a default LogLevel * @return LogLevel The replaced log level. */ public static LogLevel register(LogLevel logLevel) { if (logLevel == null) return null; // ensure that this is not a default log level if (_logLevelMap.get(logLevel.getLabel()) == null) { return (LogLevel) _registeredLogLevelMap.put(logLevel.getLabel(), logLevel); } return null; } public static void register(LogLevel[] logLevels) { if (logLevels != null) { for (int i = 0; i < logLevels.length; i++) { register(logLevels[i]); } } } public static void register(List logLevels) { if (logLevels != null) { Iterator it = logLevels.iterator(); while (it.hasNext()) { register((LogLevel) it.next()); } } } public boolean equals(Object o) { boolean equals = false; if (o instanceof LogLevel) { if (this.getPrecedence() == ((LogLevel) o).getPrecedence()) { equals = true; } } return equals; } public int hashCode() { return _label.hashCode(); } public String toString() { return _label; } // set a text color for a specific log level public void setLogLevelColorMap(LogLevel level, Color color) { // remove the old entry _logLevelColorMap.remove(level); // add the new color entry if (color == null) { color = Color.black; } _logLevelColorMap.put(level, color); } public static void resetLogLevelColorMap() { // empty the map _logLevelColorMap.clear(); // repopulate map and reset text color black for (int i = 0; i < _allDefaultLevels.length; i++) { _logLevelColorMap.put(_allDefaultLevels[i], Color.black); } } /** * @return A List of LogLevel objects that map * to log4j Priority objects. */ public static List getLog4JLevels() { return Arrays.asList(_log4JLevels); } public static List getJdk14Levels() { return Arrays.asList(_jdk14Levels); } public static List getAllDefaultLevels() { return Arrays.asList(_allDefaultLevels); } public static Map getLogLevelColorMap() { return _logLevelColorMap; } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- protected int getPrecedence() { return _precedence; } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/LogRecordFilter.java0000644000175000017500000000313411751454705026040 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5; /** * An interface for classes which filters LogRecords. Implementations * represent a rule or condition which LogRecords may pass or fail. * @see LogRecord * * @author Richard Wan */ // Contributed by ThoughtWorks Inc. public interface LogRecordFilter { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** * @return true if the specified LogRecord satisfies whatever condition * implementing class tests for. */ public boolean passes(LogRecord record); } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/PassingLogRecordFilter.java0000644000175000017500000000521511751454705027367 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5; /** * An implementation of LogRecordFilter which always returns true. * * @author Richard Wan */ // Contributed by ThoughtWorks Inc. public class PassingLogRecordFilter implements LogRecordFilter { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** * @return true; */ public boolean passes(LogRecord record) { return true; } /** * Does nothing. */ public void reset() { // do nothing } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/lf5/LF5Appender.java0000644000175000017500000002133311751454705025060 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.lf5; import java.awt.Toolkit; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.lf5.viewer.LogBrokerMonitor; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggingEvent; /** * LF5Appender logs events to a swing based logging * console. The swing console supports turning categories on and off, * multiple detail level views, as well as full text searching and many * other capabilties. * * @author Brent Sprecher */ // Contributed by ThoughtWorks Inc. public class LF5Appender extends AppenderSkeleton { //-------------------------------------------------------------------------- // Constants: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Protected Variables: //-------------------------------------------------------------------------- protected LogBrokerMonitor _logMonitor; protected static LogBrokerMonitor _defaultLogMonitor; protected static AppenderFinalizer _finalizer; //-------------------------------------------------------------------------- // Private Variables: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Constructors: //-------------------------------------------------------------------------- /** * Constructs a LF5Appender using the default instance of * the LogBrokerMonitor. This constructor should always * be preferred over the * LF5Appender(LogBrokerMonitor monitor) * constructor, unless you need to spawn additional log monitoring * windows. */ public LF5Appender() { this(getDefaultInstance()); } /** * Constructs a LF5Appender using an instance of * a LogBrokerMonitor supplied by the user. This * constructor should only be used when you need to spawn * additional log monitoring windows. * * @param monitor An instance of a LogBrokerMonitor * created by the user. */ public LF5Appender(LogBrokerMonitor monitor) { if (monitor != null) { _logMonitor = monitor; } } //-------------------------------------------------------------------------- // Public Methods: //-------------------------------------------------------------------------- /** * Appends a LoggingEvent record to the * LF5Appender. * @param event The LoggingEvent * to be appended. */ public void append(LoggingEvent event) { // Retrieve the information from the log4j LoggingEvent. String category = event.getLoggerName(); String logMessage = event.getRenderedMessage(); String nestedDiagnosticContext = event.getNDC(); String threadDescription = event.getThreadName(); String level = event.getLevel().toString(); long time = event.timeStamp; LocationInfo locationInfo = event.getLocationInformation(); // Add the logging event information to a LogRecord Log4JLogRecord record = new Log4JLogRecord(); record.setCategory(category); record.setMessage(logMessage); record.setLocation(locationInfo.fullInfo); record.setMillis(time); record.setThreadDescription(threadDescription); if (nestedDiagnosticContext != null) { record.setNDC(nestedDiagnosticContext); } else { record.setNDC(""); } if (event.getThrowableInformation() != null) { record.setThrownStackTrace(event.getThrowableInformation()); } try { record.setLevel(LogLevel.valueOf(level)); } catch (LogLevelFormatException e) { // If the priority level doesn't match one of the predefined // log levels, then set the level to warning. record.setLevel(LogLevel.WARN); } if (_logMonitor != null) { _logMonitor.addMessage(record); } } /** * This method is an empty implementation of the close() method inherited * from the org.apache.log4j.Appender interface. */ public void close() { } /** * Returns a value that indicates whether this appender requires a * Layout. This method always returns false. * No layout is required for the LF5Appender. */ public boolean requiresLayout() { return false; } /** * This method is used to set the property that controls whether * the LogBrokerMonitor is hidden or closed when a user * exits * the monitor. By default, the LogBrokerMonitor will hide * itself when the log window is exited, and the swing thread will * continue to run in the background. If this property is * set to true, the LogBrokerMonitor will call System.exit(0) * and will shut down swing thread and the virtual machine. * * @param callSystemExitOnClose A boolean value indicating whether * to call System.exit(0) when closing the log window. */ public void setCallSystemExitOnClose(boolean callSystemExitOnClose) { _logMonitor.setCallSystemExitOnClose(callSystemExitOnClose); } /** * The equals method compares two LF5Appenders and determines whether * they are equal. Two Appenders will be considered equal * if, and only if, they both contain references to the same * LogBrokerMonitor. * * @param compareTo A boolean value indicating whether * the two LF5Appenders are equal. */ public boolean equals(LF5Appender compareTo) { // If both reference the same LogBrokerMonitor, they are equal. return _logMonitor == compareTo.getLogBrokerMonitor(); } public LogBrokerMonitor getLogBrokerMonitor() { return _logMonitor; } public static void main(String[] args) { new LF5Appender(); } public void setMaxNumberOfRecords(int maxNumberOfRecords) { _defaultLogMonitor.setMaxNumberOfLogRecords(maxNumberOfRecords); } //-------------------------------------------------------------------------- // Protected Methods: //-------------------------------------------------------------------------- /** * @return The default instance of the LogBrokerMonitor. */ protected static synchronized LogBrokerMonitor getDefaultInstance() { if (_defaultLogMonitor == null) { try { _defaultLogMonitor = new LogBrokerMonitor(LogLevel.getLog4JLevels()); _finalizer = new AppenderFinalizer(_defaultLogMonitor); _defaultLogMonitor.setFrameSize(getDefaultMonitorWidth(), getDefaultMonitorHeight()); _defaultLogMonitor.setFontSize(12); _defaultLogMonitor.show(); } catch (SecurityException e) { _defaultLogMonitor = null; } } return _defaultLogMonitor; } /** * @return the screen width from Toolkit.getScreenSize() * if possible, otherwise returns 800 * @see java.awt.Toolkit */ protected static int getScreenWidth() { try { return Toolkit.getDefaultToolkit().getScreenSize().width; } catch (Throwable t) { return 800; } } /** * @return the screen height from Toolkit.getScreenSize() * if possible, otherwise returns 600 * @see java.awt.Toolkit */ protected static int getScreenHeight() { try { return Toolkit.getDefaultToolkit().getScreenSize().height; } catch (Throwable t) { return 600; } } protected static int getDefaultMonitorWidth() { return (3 * getScreenWidth()) / 4; } protected static int getDefaultMonitorHeight() { return (3 * getScreenHeight()) / 4; } //-------------------------------------------------------------------------- // Private Methods: //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Nested Top-Level Classes or Interfaces: //-------------------------------------------------------------------------- } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/ConsoleAppender.java0000644000175000017500000001330411751454711025402 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import java.io.IOException; import java.io.OutputStream; import org.apache.log4j.helpers.LogLog; /** * ConsoleAppender appends log events to System.out or * System.err using a layout specified by the user. The * default target is System.out. * * @author Ceki Gülcü * @author Curt Arnold * @since 1.1 */ public class ConsoleAppender extends WriterAppender { public static final String SYSTEM_OUT = "System.out"; public static final String SYSTEM_ERR = "System.err"; protected String target = SYSTEM_OUT; /** * Determines if the appender honors reassignments of System.out * or System.err made after configuration. */ private boolean follow = false; /** * Constructs an unconfigured appender. */ public ConsoleAppender() { } /** * Creates a configured appender. * * @param layout layout, may not be null. */ public ConsoleAppender(Layout layout) { this(layout, SYSTEM_OUT); } /** * Creates a configured appender. * @param layout layout, may not be null. * @param target target, either "System.err" or "System.out". */ public ConsoleAppender(Layout layout, String target) { setLayout(layout); setTarget(target); activateOptions(); } /** * Sets the value of the Target 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 Target property. The * default value of the option is "System.out". * * See also {@link #setTarget}. * */ public String getTarget() { return target; } /** * Sets whether the appender honors reassignments of System.out * or System.err made after configuration. * @param newValue if true, appender will use value of System.out or * System.err in force at the time when logging events are appended. * @since 1.2.13 */ public final void setFollow(final boolean newValue) { follow = newValue; } /** * Gets whether the appender honors reassignments of System.out * or System.err made after configuration. * @return true if appender will use value of System.out or * System.err in force at the time when logging events are appended. * @since 1.2.13 */ public final boolean getFollow() { return follow; } void targetWarn(String val) { LogLog.warn("["+val+"] should be System.out or System.err."); LogLog.warn("Using previously set target, System.out by default."); } /** * Prepares the appender for use. */ public void activateOptions() { if (follow) { if (target.equals(SYSTEM_ERR)) { setWriter(createWriter(new SystemErrStream())); } else { setWriter(createWriter(new SystemOutStream())); } } else { if (target.equals(SYSTEM_ERR)) { setWriter(createWriter(System.err)); } else { setWriter(createWriter(System.out)); } } super.activateOptions(); } /** * {@inheritDoc} */ protected final void closeWriter() { if (follow) { super.closeWriter(); } } /** * An implementation of OutputStream that redirects to the * current System.err. * */ private static class SystemErrStream extends OutputStream { public SystemErrStream() { } public void close() { } public void flush() { System.err.flush(); } public void write(final byte[] b) throws IOException { System.err.write(b); } public void write(final byte[] b, final int off, final int len) throws IOException { System.err.write(b, off, len); } public void write(final int b) throws IOException { System.err.write(b); } } /** * An implementation of OutputStream that redirects to the * current System.out. * */ private static class SystemOutStream extends OutputStream { public SystemOutStream() { } public void close() { } public void flush() { System.out.flush(); } public void write(final byte[] b) throws IOException { System.out.write(b); } public void write(final byte[] b, final int off, final int len) throws IOException { System.out.write(b, off, len); } public void write(final int b) throws IOException { System.out.write(b); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/WriterAppender.java0000644000175000017500000002352211751454711025257 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import java.io.IOException; import java.io.InterruptedIOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.helpers.QuietWriter; import org.apache.log4j.spi.ErrorHandler; import org.apache.log4j.spi.LoggingEvent; // Contibutors: Jens Uwe Pipka // Ben Sandee /** WriterAppender appends log events to a {@link java.io.Writer} or an {@link java.io.OutputStream} depending on the user's choice. @author Ceki Gülcü @since 1.1 */ public class WriterAppender extends AppenderSkeleton { /** Immediate flush means that the underlying writer or output stream will be flushed at the end of each append operation unless shouldFlush() is overridden. Immediate flush is slower but ensures that each append request is actually written. If immediateFlush is set to false, then there is a good chance that the last few logs events are not actually written to persistent media if and when the application crashes.

The immediateFlush variable is set to true by default. */ protected boolean immediateFlush = true; /** The encoding to use when writing.

The encoding variable is set to null by default which results in the utilization of the system's default encoding. */ protected String encoding; /** This is the {@link QuietWriter quietWriter} where we will write to. */ protected QuietWriter qw; /** This default constructor does nothing. */ public WriterAppender() { } /** Instantiate a WriterAppender and set the output destination to a new {@link OutputStreamWriter} initialized with os as its {@link OutputStream}. */ public WriterAppender(Layout layout, OutputStream os) { this(layout, new OutputStreamWriter(os)); } /** Instantiate a WriterAppender and set the output destination to writer.

The writer must have been previously opened by the user. */ public WriterAppender(Layout layout, Writer writer) { this.layout = layout; this.setWriter(writer); } /** If the ImmediateFlush option is set to true, the appender will flush at the end of each write. This is the default behavior. If the option is set to false, then the underlying stream can defer writing to physical medium to a later time.

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 involved in skipping flushing. Indeed, when flushing is skipped, then it is likely that the last few log events will not be recorded on disk when the application exits. This is a high price to pay even for a 20% performance gain. */ public void setImmediateFlush(boolean value) { immediateFlush = value; } /** Returns value of the ImmediateFlush option. */ public boolean getImmediateFlush() { return immediateFlush; } /** Does nothing. */ public void activateOptions() { } /** This method is called by the {@link AppenderSkeleton#doAppend} method.

If the output stream exists and is writable then write a log statement to the output stream. Otherwise, write a single warning message to System.err.

The format of the output will depend on this appender's layout. */ public void append(LoggingEvent event) { // Reminder: the nesting of calls is: // // doAppend() // - check threshold // - filter // - append(); // - checkEntryConditions(); // - subAppend(); if(!checkEntryConditions()) { return; } subAppend(event); } /** This method determines if there is a sense in attempting to append.

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 false is returned. */ protected boolean checkEntryConditions() { if(this.closed) { LogLog.warn("Not allowed to write to a closed appender."); return false; } if(this.qw == null) { 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; } return true; } /** Close this appender instance. The underlying stream or writer is also closed.

Closed appenders cannot be reused. @see #setWriter @since 0.8.4 */ public synchronized void close() { if(this.closed) return; this.closed = true; writeFooter(); reset(); } /** * Close the underlying {@link java.io.Writer}. * */ protected void closeWriter() { if(qw != null) { try { qw.close(); } catch(IOException e) { if (e instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } // There is do need to invoke an error handler at this late // stage. LogLog.error("Could not close " + qw, e); } } } /** Returns an OutputStreamWriter when passed an OutputStream. The encoding used will depend on the value of the encoding 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 OutputStreamWriter createWriter(OutputStream os) { OutputStreamWriter retval = null; String enc = getEncoding(); if(enc != null) { try { retval = new OutputStreamWriter(os, enc); } catch(IOException e) { if (e instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.warn("Error initializing output writer."); LogLog.warn("Unsupported encoding?"); } } if(retval == null) { retval = new OutputStreamWriter(os); } return retval; } public String getEncoding() { return encoding; } public void setEncoding(String value) { encoding = value; } /** Set the {@link ErrorHandler} for this WriterAppender and also the underlying {@link QuietWriter} if any. */ public synchronized void setErrorHandler(ErrorHandler eh) { if(eh == null) { LogLog.warn("You have tried to set a null error-handler."); } else { this.errorHandler = eh; if(this.qw != null) { this.qw.setErrorHandler(eh); } } } /**

Sets the Writer where the log output will go. The specified Writer must be opened by the user and be writable.

The java.io.Writer will be closed when the appender instance is closed.

WARNING: Logging to an unopened Writer will fail.

@param writer An already opened Writer. */ public synchronized void setWriter(Writer writer) { reset(); this.qw = new QuietWriter(writer, errorHandler); //this.tp = new TracerPrintWriter(qw); writeHeader(); } /** Actual writing occurs here.

Most subclasses of WriterAppender will need to override this method. @since 0.9.0 */ protected void subAppend(LoggingEvent event) { this.qw.write(this.layout.format(event)); if(layout.ignoresThrowable()) { String[] s = event.getThrowableStrRep(); if (s != null) { int len = s.length; for(int i = 0; i < len; i++) { this.qw.write(s[i]); this.qw.write(Layout.LINE_SEP); } } } if(shouldFlush(event)) { this.qw.flush(); } } /** The WriterAppender requires a layout. Hence, this method returns true. */ public boolean requiresLayout() { return true; } /** Clear internal references to the writer and other variables. Subclasses can override this method for an alternate closing behavior. */ protected void reset() { closeWriter(); this.qw = null; //this.tp = null; } /** Write a footer as produced by the embedded layout's {@link Layout#getFooter} method. */ protected void writeFooter() { if(layout != null) { String f = layout.getFooter(); if(f != null && this.qw != null) { this.qw.write(f); this.qw.flush(); } } } /** Write a header as produced by the embedded layout's {@link Layout#getHeader} method. */ protected void writeHeader() { if(layout != null) { String h = layout.getHeader(); if(h != null && this.qw != null) this.qw.write(h); } } /** * Determines whether the writer should be flushed after * this event is written. * * @since 1.2.16 */ protected boolean shouldFlush(final LoggingEvent event) { return immediateFlush; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/PropertyConfigurator.java0000644000175000017500000010470311751454711026534 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Contibutors: "Luke Blanshard" // "Mark DONSZELMANN" // Anders Kristensen package org.apache.log4j; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.net.URLConnection; import java.util.Enumeration; import java.util.Hashtable; import java.util.Properties; import java.util.StringTokenizer; import java.util.Vector; import java.util.Iterator; import java.util.Map; import org.apache.log4j.config.PropertySetter; import org.apache.log4j.helpers.FileWatchdog; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.helpers.OptionConverter; import org.apache.log4j.or.RendererMap; import org.apache.log4j.spi.Configurator; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggerFactory; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.OptionHandler; import org.apache.log4j.spi.RendererSupport; import org.apache.log4j.spi.ThrowableRenderer; import org.apache.log4j.spi.ThrowableRendererSupport; import org.apache.log4j.spi.ErrorHandler; /** Allows the configuration of log4j from an external file. See {@link #doConfigure(String, LoggerRepository)} for the expected format.

It is sometimes useful to see how log4j is reading configuration files. You can enable log4j internal logging by defining the log4j.debug variable.

As of log4j version 0.8.5, at class initialization time class, the file log4j.properties will be searched from the search path used to load classes. If the file can be found, then it will be fed to the {@link PropertyConfigurator#configure(java.net.URL)} method.

The PropertyConfigurator does not handle the advanced configuration features supported by the {@link org.apache.log4j.xml.DOMConfigurator DOMConfigurator} such as support custom {@link org.apache.log4j.spi.ErrorHandler ErrorHandlers}, nested appenders such as the {@link org.apache.log4j.AsyncAppender AsyncAppender}, etc.

All option values admit variable substitution. The syntax of variable substitution is similar to that of Unix shells. The string between an opening "${" and closing "}" is interpreted as a key. The value of the substituted variable can be defined as a system property or in the configuration file itself. The value of the key is first searched in the system properties, and if not found there, it is then searched in the configuration file being parsed. The corresponding value replaces the ${variableName} sequence. For example, if java.home system property is set to /home/xyz, then every occurrence of the sequence ${java.home} will be interpreted as /home/xyz. @author Ceki Gülcü @author Anders Kristensen @since 0.8.1 */ public class PropertyConfigurator implements Configurator { /** Used internally to keep track of configured appenders. */ protected Hashtable registry = new Hashtable(11); private LoggerRepository repository; 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 RENDERER_PREFIX = "log4j.renderer."; static final String THRESHOLD_PREFIX = "log4j.threshold"; private static final String THROWABLE_RENDERER_PREFIX = "log4j.throwableRenderer"; private static final String LOGGER_REF = "logger-ref"; private static final String ROOT_REF = "root-ref"; private static final String APPENDER_REF_TAG = "appender-ref"; /** Key for specifying the {@link org.apache.log4j.spi.LoggerFactory LoggerFactory}. Currently set to "log4j.loggerFactory". */ public static final String LOGGER_FACTORY_KEY = "log4j.loggerFactory"; /** * If property set to true, then hierarchy will be reset before configuration. */ private static final String RESET_KEY = "log4j.reset"; static final private String INTERNAL_ROOT_NAME = "root"; /** Read configuration from a file. The existing configuration is not cleared nor reset. If you require a different behavior, then call {@link LogManager#resetConfiguration resetConfiguration} method before calling doConfigure.

The configuration file consists of statements in the format key=value. The syntax of different configuration elements are discussed below.

Repository-wide threshold

The repository-wide threshold filters logging requests by level regardless of logger. The syntax is:

    log4j.threshold=[level]
    

The level value can consist of the string values OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL or a custom level value. A custom level value can be specified in the form level#classname. By default the repository-wide threshold is set to the lowest possible value, namely the level ALL.

Appender configuration

Appender configuration syntax is:

    # For appender named appenderName, set its class.
    # Note: The appender name can contain dots.
    log4j.appender.appenderName=fully.qualified.name.of.appender.class

    # Set appender specific options.
    log4j.appender.appenderName.option1=value1
    ...
    log4j.appender.appenderName.optionN=valueN
    
For each named appender you can configure its {@link Layout}. The syntax for configuring an appender's layout is:
    log4j.appender.appenderName.layout=fully.qualified.name.of.layout.class
    log4j.appender.appenderName.layout.option1=value1
    ....
    log4j.appender.appenderName.layout.optionN=valueN
    
The syntax for adding {@link Filter}s to an appender is:
    log4j.appender.appenderName.filter.ID=fully.qualified.name.of.filter.class
    log4j.appender.appenderName.filter.ID.option1=value1
    ...
    log4j.appender.appenderName.filter.ID.optionN=valueN
    
The first line defines the class name of the filter identified by ID; subsequent lines with the same ID specify filter option - value paris. Multiple filters are added to the appender in the lexicographic order of IDs. The syntax for adding an {@link ErrorHandler} to an appender is:
    log4j.appender.appenderName.errorhandler=fully.qualified.name.of.filter.class
    log4j.appender.appenderName.errorhandler.root-ref={true|false}
    log4j.appender.appenderName.errorhandler.logger-ref=loggerName
    log4j.appender.appenderName.errorhandler.appender-ref=appenderName
    log4j.appender.appenderName.errorhandler.option1=value1
    ...
    log4j.appender.appenderName.errorhandler.optionN=valueN
    

Configuring loggers

The syntax for configuring the root logger is:

      log4j.rootLogger=[level], appenderName, appenderName, ...
    

This syntax means that an optional level can be supplied followed by appender names separated by commas.

The level value can consist of the string values OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL or a custom level value. A custom level value can be specified in the form level#classname.

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.

The root logger can be assigned multiple appenders.

Each appenderName (separated by commas) will be added to the root logger. The named appender is defined using the appender syntax defined above.

For non-root categories the syntax is almost the same:

    log4j.logger.logger_name=[level|INHERITED|NULL], appenderName, appenderName, ...
    

The meaning of the optional level value is discussed above in relation to the root logger. In addition however, the value INHERITED can be specified meaning that the named logger should inherit its level from the logger hierarchy.

If no level value is supplied, then the level of the named logger remains untouched.

By default categories inherit their level from the 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. NULL is a synonym for INHERITED.

Similar to the root logger syntax, each appenderName (separated by commas) will be attached to the named logger.

See the appender additivity rule in the user manual for the meaning of the additivity flag.

ObjectRenderers

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} for the object type would like to customize.

The syntax is:

    log4j.renderer.fully.qualified.name.of.rendered.class=fully.qualified.name.of.rendering.class
    
As in,
    log4j.renderer.my.Fruit=my.FruitRenderer
    

ThrowableRenderer

You can customize the way an instance of Throwable is converted to String before being logged. This is done by specifying an {@link org.apache.log4j.spi.ThrowableRenderer ThrowableRenderer}.

The syntax is:

   log4j.throwableRenderer=fully.qualified.name.of.rendering.class
   log4j.throwableRenderer.paramName=paramValue
   
As in,
   log4j.throwableRenderer=org.apache.log4j.EnhancedThrowableRenderer
   

Logger Factories

The usage of custom logger factories is discouraged and no longer documented.

Resetting Hierarchy

The hierarchy will be reset before configuration when log4j.reset=true is present in the properties file.

Example

An example configuration is given below. Other configuration file examples are given in the examples folder.


    # 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
    # %r %-5p %c{2} %M.%L %x - %m\n. 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,
    # followed by the two rightmost components of the logger name,
    # 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.
    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.
    log4j.appender.A2=org.apache.log4j.RollingFileAppender
    log4j.appender.A2.MaxFileSize=10MB
    log4j.appender.A2.MaxBackupIndex=1
    log4j.appender.A2.layout=org.apache.log4j.TTCCLayout
    log4j.appender.A2.layout.ContextPrinting=enabled
    log4j.appender.A2.layout.DateFormat=ISO8601

    # Root logger set to DEBUG using the A2 appender defined above.
    log4j.rootLogger=DEBUG, A2

    # Logger definitions:
    # The SECURITY logger inherits is level from root. However, it's output
    # will go to A1 appender defined above. It's additivity is non-cumulative.
    log4j.logger.SECURITY=INHERIT, A1
    log4j.additivity.SECURITY=false

    # Only warnings or above will be logged for the logger "SECURITY.access".
    # 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.
    log4j.logger.class.of.the.day=INHERIT
    

Refer to the setOption method in each Appender and Layout for class specific options.

Use the # or ! characters at the beginning of a line for comments.

@param configFileName The name of the configuration file where the configuration information is stored. */ public void doConfigure(String configFileName, LoggerRepository hierarchy) { Properties props = new Properties(); FileInputStream istream = null; try { istream = new FileInputStream(configFileName); props.load(istream); istream.close(); } catch (Exception e) { if (e instanceof InterruptedIOException || e instanceof InterruptedException) { Thread.currentThread().interrupt(); } LogLog.error("Could not read configuration file ["+configFileName+"].", e); LogLog.error("Ignoring configuration file [" + configFileName+"]."); return; } finally { if(istream != null) { try { istream.close(); } catch(InterruptedIOException ignore) { Thread.currentThread().interrupt(); } catch(Throwable ignore) { } } } // If we reach here, then the config file is alright. doConfigure(props, hierarchy); } /** */ static public void configure(String configFilename) { new PropertyConfigurator().doConfigure(configFilename, LogManager.getLoggerRepository()); } /** Read configuration options from url configURL. @since 0.8.2 */ public static void configure(java.net.URL configURL) { new PropertyConfigurator().doConfigure(configURL, LogManager.getLoggerRepository()); } /** Reads configuration options from an InputStream. @since 1.2.17 */ public static void configure(InputStream inputStream) { new PropertyConfigurator().doConfigure(inputStream, LogManager.getLoggerRepository()); } /** Read configuration options from properties. See {@link #doConfigure(String, LoggerRepository)} for the expected format. */ static public void configure(Properties 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. @param configFilename A file in key=value format. */ static public void configureAndWatch(String configFilename) { configureAndWatch(configFilename, FileWatchdog.DEFAULT_DELAY); } /** Read the configuration file configFilename if it exists. Moreover, a thread will be created that will periodically check if configFilename has been created or modified. The period is determined by the delay argument. If a change or file creation is detected, then configFilename is read to configure log4j. @param configFilename A file in key=value format. @param delay The delay in milliseconds to wait between each check. */ static public void configureAndWatch(String configFilename, long delay) { PropertyWatchdog pdog = new PropertyWatchdog(configFilename); pdog.setDelay(delay); pdog.start(); } /** Read configuration options from properties. See {@link #doConfigure(String, LoggerRepository)} for the expected format. */ public void doConfigure(Properties properties, LoggerRepository hierarchy) { repository = hierarchy; String value = properties.getProperty(LogLog.DEBUG_KEY); if(value == null) { value = properties.getProperty("log4j.configDebug"); if(value != null) LogLog.warn("[log4j.configDebug] is deprecated. Use [log4j.debug] instead."); } if(value != null) { LogLog.setInternalDebugging(OptionConverter.toBoolean(value, true)); } // // if log4j.reset=true then // reset hierarchy String reset = properties.getProperty(RESET_KEY); if (reset != null && OptionConverter.toBoolean(reset, false)) { hierarchy.resetConfiguration(); } String thresholdStr = OptionConverter.findAndSubst(THRESHOLD_PREFIX, properties); if(thresholdStr != null) { hierarchy.setThreshold(OptionConverter.toLevel(thresholdStr, (Level) Level.ALL)); LogLog.debug("Hierarchy threshold set to ["+hierarchy.getThreshold()+"]."); } configureRootCategory(properties, hierarchy); configureLoggerFactory(properties); parseCatsAndRenderers(properties, hierarchy); LogLog.debug("Finished configuring."); // We don't want to hold references to appenders preventing their // garbage collection. registry.clear(); } /** * Read configuration options from url configURL. * * @since 1.2.17 */ public void doConfigure(InputStream inputStream, LoggerRepository hierarchy) { Properties props = new Properties(); try { props.load(inputStream); } catch (IOException e) { if (e instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.error("Could not read configuration file from InputStream [" + inputStream + "].", e); LogLog.error("Ignoring configuration InputStream [" + inputStream +"]."); return; } this.doConfigure(props, hierarchy); } /** Read configuration options from url configURL. */ public void doConfigure(java.net.URL configURL, LoggerRepository hierarchy) { Properties props = new Properties(); LogLog.debug("Reading configuration from URL " + configURL); InputStream istream = null; URLConnection uConn = null; try { uConn = configURL.openConnection(); uConn.setUseCaches(false); istream = uConn.getInputStream(); props.load(istream); } catch (Exception e) { if (e instanceof InterruptedIOException || e instanceof InterruptedException) { Thread.currentThread().interrupt(); } LogLog.error("Could not read configuration file from URL [" + configURL + "].", e); LogLog.error("Ignoring configuration file [" + configURL +"]."); return; } finally { if (istream != null) { try { istream.close(); } catch(InterruptedIOException ignore) { Thread.currentThread().interrupt(); } catch(IOException ignore) { } catch(RuntimeException ignore) { } } } doConfigure(props, hierarchy); } // -------------------------------------------------------------------------- // Internal stuff // -------------------------------------------------------------------------- /** Check the provided Properties object for a {@link org.apache.log4j.spi.LoggerFactory LoggerFactory} entry specified by {@link #LOGGER_FACTORY_KEY}. If such an entry exists, an attempt is made to create an instance using the default constructor. This instance is used for subsequent Category creations within this configurator. @see #parseCatsAndRenderers */ protected void configureLoggerFactory(Properties props) { String factoryClassName = OptionConverter.findAndSubst(LOGGER_FACTORY_KEY, props); if(factoryClassName != null) { LogLog.debug("Setting category factory to ["+factoryClassName+"]."); loggerFactory = (LoggerFactory) OptionConverter.instantiateByClassName(factoryClassName, LoggerFactory.class, loggerFactory); PropertySetter.setProperties(loggerFactory, props, FACTORY_PREFIX + "."); } } /* void configureOptionHandler(OptionHandler oh, String prefix, Properties props) { String[] options = oh.getOptionStrings(); if(options == null) return; String value; for(int i = 0; i < options.length; i++) { value = OptionConverter.findAndSubst(prefix + options[i], props); LogLog.debug( "Option " + options[i] + "=[" + (value == null? "N/A" : value)+"]."); // Some option handlers assume that null value are not passed to them. // So don't remove this check if(value != null) { oh.setOption(options[i], value); } } 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) 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); } } } /** Parse non-root elements, such non-root categories and renderers. */ protected void parseCatsAndRenderers(Properties props, LoggerRepository hierarchy) { Enumeration enumeration = props.propertyNames(); while(enumeration.hasMoreElements()) { String key = (String) enumeration.nextElement(); if(key.startsWith(CATEGORY_PREFIX) || key.startsWith(LOGGER_PREFIX)) { String loggerName = null; if(key.startsWith(CATEGORY_PREFIX)) { loggerName = key.substring(CATEGORY_PREFIX.length()); } else if(key.startsWith(LOGGER_PREFIX)) { loggerName = key.substring(LOGGER_PREFIX.length()); } String value = OptionConverter.findAndSubst(key, props); Logger logger = hierarchy.getLogger(loggerName, loggerFactory); synchronized(logger) { parseCategory(props, logger, key, loggerName, value); parseAdditivityForLogger(props, logger, loggerName); } } else if(key.startsWith(RENDERER_PREFIX)) { String renderedClass = key.substring(RENDERER_PREFIX.length()); String renderingClass = OptionConverter.findAndSubst(key, props); if(hierarchy instanceof RendererSupport) { RendererMap.addRenderer((RendererSupport) hierarchy, renderedClass, renderingClass); } } else if (key.equals(THROWABLE_RENDERER_PREFIX)) { if (hierarchy instanceof ThrowableRendererSupport) { ThrowableRenderer tr = (ThrowableRenderer) OptionConverter.instantiateByKey(props, THROWABLE_RENDERER_PREFIX, org.apache.log4j.spi.ThrowableRenderer.class, null); if(tr == null) { LogLog.error( "Could not instantiate throwableRenderer."); } else { PropertySetter setter = new PropertySetter(tr); setter.setProperties(props, THROWABLE_RENDERER_PREFIX + "."); ((ThrowableRendererSupport) hierarchy).setThrowableRenderer(tr); } } } } } /** Parse the additivity option for a non-root category. */ void parseAdditivityForLogger(Properties props, Logger cat, String loggerName) { String value = OptionConverter.findAndSubst(ADDITIVITY_PREFIX + loggerName, props); LogLog.debug("Handling "+ADDITIVITY_PREFIX + loggerName+"=["+value+"]"); // touch additivity only if necessary if((value != null) && (!value.equals(""))) { boolean additivity = OptionConverter.toBoolean(value, true); LogLog.debug("Setting additivity for \""+loggerName+"\" to "+ additivity); cat.setAdditivity(additivity); } } /** This method must work for the root category as well. */ void parseCategory(Properties props, Logger logger, String optionKey, String loggerName, String value) { 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 + "]."); // If the level value is inherited, set category level value to // null. We also check that the user has not specified inherited for the // root category. if(INHERITED.equalsIgnoreCase(levelStr) || NULL.equalsIgnoreCase(levelStr)) { if(loggerName.equals(INTERNAL_ROOT_NAME)) { LogLog.warn("The root logger cannot be set to null."); } else { logger.setLevel(null); } } else { logger.setLevel(OptionConverter.toLevel(levelStr, (Level) Level.DEBUG)); } LogLog.debug("Category " + loggerName + " set to " + logger.getLevel()); } // Begin by removing all existing appenders. logger.removeAllAppenders(); Appender appender; String appenderName; while(st.hasMoreTokens()) { appenderName = st.nextToken().trim(); if(appenderName == null || appenderName.equals(",")) continue; LogLog.debug("Parsing appender named \"" + appenderName +"\"."); appender = parseAppender(props, appenderName); if(appender != null) { logger.addAppender(appender); } } } Appender parseAppender(Properties props, String appenderName) { Appender appender = registryGet(appenderName); if((appender != null)) { LogLog.debug("Appender \"" + appenderName + "\" was already parsed."); return appender; } // Appender was not previously initialized. String prefix = APPENDER_PREFIX + appenderName; String layoutPrefix = prefix + ".layout"; appender = (Appender) OptionConverter.instantiateByKey(props, prefix, org.apache.log4j.Appender.class, null); if(appender == null) { LogLog.error( "Could not instantiate appender named \"" + appenderName+"\"."); return null; } appender.setName(appenderName); if(appender instanceof OptionHandler) { if(appender.requiresLayout()) { Layout layout = (Layout) OptionConverter.instantiateByKey(props, layoutPrefix, 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 +"\"."); } } final String errorHandlerPrefix = prefix + ".errorhandler"; String errorHandlerClass = OptionConverter.findAndSubst(errorHandlerPrefix, props); if (errorHandlerClass != null) { ErrorHandler eh = (ErrorHandler) OptionConverter.instantiateByKey(props, errorHandlerPrefix, ErrorHandler.class, null); if (eh != null) { appender.setErrorHandler(eh); LogLog.debug("Parsing errorhandler options for \"" + appenderName +"\"."); parseErrorHandler(eh, errorHandlerPrefix, props, repository); final Properties edited = new Properties(); final String[] keys = new String[] { errorHandlerPrefix + "." + ROOT_REF, errorHandlerPrefix + "." + LOGGER_REF, errorHandlerPrefix + "." + APPENDER_REF_TAG }; for(Iterator iter = props.entrySet().iterator();iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); int i = 0; for(; i < keys.length; i++) { if(keys[i].equals(entry.getKey())) break; } if (i == keys.length) { edited.put(entry.getKey(), entry.getValue()); } } PropertySetter.setProperties(eh, edited, errorHandlerPrefix + "."); LogLog.debug("End of errorhandler parsing for \"" + appenderName +"\"."); } } //configureOptionHandler((OptionHandler) appender, prefix + ".", props); PropertySetter.setProperties(appender, props, prefix + "."); LogLog.debug("Parsed \"" + appenderName +"\" options."); } parseAppenderFilters(props, appenderName, appender); registryPut(appender); return appender; } private void parseErrorHandler( final ErrorHandler eh, final String errorHandlerPrefix, final Properties props, final LoggerRepository hierarchy) { boolean rootRef = OptionConverter.toBoolean( OptionConverter.findAndSubst(errorHandlerPrefix + ROOT_REF, props), false); if (rootRef) { eh.setLogger(hierarchy.getRootLogger()); } String loggerName = OptionConverter.findAndSubst(errorHandlerPrefix + LOGGER_REF , props); if (loggerName != null) { Logger logger = (loggerFactory == null) ? hierarchy.getLogger(loggerName) : hierarchy.getLogger(loggerName, loggerFactory); eh.setLogger(logger); } String appenderName = OptionConverter.findAndSubst(errorHandlerPrefix + APPENDER_REF_TAG, props); if (appenderName != null) { Appender backup = parseAppender(props, appenderName); if (backup != null) { eh.setBackupAppender(backup); } } } void parseAppenderFilters(Properties props, String appenderName, Appender appender) { // extract filters and filter options from props into a hashtable mapping // the property name defining the filter class to a list of pre-parsed // name-value pairs associated to that filter final String filterPrefix = APPENDER_PREFIX + appenderName + ".filter."; int fIdx = filterPrefix.length(); Hashtable filters = new Hashtable(); Enumeration e = props.keys(); String name = ""; while (e.hasMoreElements()) { String key = (String) e.nextElement(); if (key.startsWith(filterPrefix)) { int dotIdx = key.indexOf('.', fIdx); String filterKey = key; if (dotIdx != -1) { filterKey = key.substring(0, dotIdx); name = key.substring(dotIdx+1); } Vector filterOpts = (Vector) filters.get(filterKey); if (filterOpts == null) { filterOpts = new Vector(); filters.put(filterKey, filterOpts); } if (dotIdx != -1) { String value = OptionConverter.findAndSubst(key, props); filterOpts.add(new NameValue(name, value)); } } } // sort filters by IDs, insantiate filters, set filter options, // add filters to the appender Enumeration g = new SortedKeyEnumeration(filters); while (g.hasMoreElements()) { String key = (String) g.nextElement(); String clazz = props.getProperty(key); if (clazz != null) { LogLog.debug("Filter key: ["+key+"] class: ["+props.getProperty(key) +"] props: "+filters.get(key)); Filter filter = (Filter) OptionConverter.instantiateByClassName(clazz, Filter.class, null); if (filter != null) { PropertySetter propSetter = new PropertySetter(filter); Vector v = (Vector)filters.get(key); Enumeration filterProps = v.elements(); while (filterProps.hasMoreElements()) { NameValue kv = (NameValue)filterProps.nextElement(); propSetter.setProperty(kv.key, kv.value); } propSetter.activate(); LogLog.debug("Adding filter of type ["+filter.getClass() +"] to appender named ["+appender.getName()+"]."); appender.addFilter(filter); } } else { LogLog.warn("Missing class definition for filter: ["+key+"]"); } } } void registryPut(Appender appender) { registry.put(appender.getName(), appender); } Appender registryGet(String name) { return (Appender) registry.get(name); } } class PropertyWatchdog extends FileWatchdog { PropertyWatchdog(String filename) { super(filename); } /** Call {@link PropertyConfigurator#configure(String)} with the filename to reconfigure log4j. */ public void doOnChange() { new PropertyConfigurator().doConfigure(filename, LogManager.getLoggerRepository()); } } class NameValue { String key, value; public NameValue(String key, String value) { this.key = key; this.value = value; } public String toString() { return key + "=" + value; } } class SortedKeyEnumeration implements Enumeration { private Enumeration e; public SortedKeyEnumeration(Hashtable ht) { Enumeration f = ht.keys(); Vector keys = new Vector(ht.size()); for (int i, last = 0; f.hasMoreElements(); ++last) { String key = (String) f.nextElement(); for (i = 0; i < last; ++i) { String s = (String) keys.get(i); if (key.compareTo(s) <= 0) break; } keys.add(i, key); } e = keys.elements(); } public boolean hasMoreElements() { return e.hasMoreElements(); } public Object nextElement() { return e.nextElement(); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/or/0000755000175000017500000000000012126647422022075 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/or/package.html0000644000175000017500000000176011751454704024364 0ustar tonytony org.apache.log4j.or package

ObjectRenders are resposible for rendering messages depending on their class type.


apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/or/DefaultRenderer.java0000644000175000017500000000250111751454704026013 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.or; /** The default Renderer renders objects by calling their toString method. @author Ceki Gülcü @since 1.0 */ class DefaultRenderer implements ObjectRenderer { DefaultRenderer() { } /** Render the object passed as parameter by calling its toString method. */ public String doRender(final Object o) { try { return o.toString(); } catch(Exception ex) { return ex.toString(); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/or/jms/0000755000175000017500000000000012126647422022666 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/or/jms/package.html0000644000175000017500000000163411751454704025155 0ustar tonytony This package contains the MessageRenderer which renders objects of type javax.jms.Message. apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/or/jms/MessageRenderer.java0000644000175000017500000000513211751454704026607 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.or.jms; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.or.ObjectRenderer; import javax.jms.Message; import javax.jms.JMSException; import javax.jms.DeliveryMode; /** Render javax.jms.Message objects. @author Ceki Gülcü @since 1.0 */ public class MessageRenderer implements ObjectRenderer { public MessageRenderer() { } /** Render a {@link javax.jms.Message}. */ public String doRender(Object o) { if(o instanceof Message) { StringBuffer sbuf = new StringBuffer(); Message m = (Message) o; try { sbuf.append("DeliveryMode="); switch(m.getJMSDeliveryMode()) { case DeliveryMode.NON_PERSISTENT : sbuf.append("NON_PERSISTENT"); break; case DeliveryMode.PERSISTENT : sbuf.append("PERSISTENT"); break; default: sbuf.append("UNKNOWN"); } sbuf.append(", CorrelationID="); sbuf.append(m.getJMSCorrelationID()); sbuf.append(", Destination="); sbuf.append(m.getJMSDestination()); sbuf.append(", Expiration="); sbuf.append(m.getJMSExpiration()); sbuf.append(", MessageID="); sbuf.append(m.getJMSMessageID()); sbuf.append(", Priority="); sbuf.append(m.getJMSPriority()); sbuf.append(", Redelivered="); sbuf.append(m.getJMSRedelivered()); sbuf.append(", ReplyTo="); sbuf.append(m.getJMSReplyTo()); sbuf.append(", Timestamp="); sbuf.append(m.getJMSTimestamp()); sbuf.append(", Type="); sbuf.append(m.getJMSType()); //Enumeration enum = m.getPropertyNames(); //while(enum.hasMoreElements()) { // String key = (String) enum.nextElement(); // sbuf.append("; "+key+"="); // sbuf.append(m.getStringProperty(key)); //} } catch(JMSException e) { LogLog.error("Could not parse Message.", e); } return sbuf.toString(); } else { return o.toString(); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/or/ThreadGroupRenderer.java0000644000175000017500000000466711751454704026672 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.or; import org.apache.log4j.Layout; /** Render {@link ThreadGroup} objects in a format similar to the information output by the {@link ThreadGroup#list} method. @author Ceki Gülcü @since 1.0 */ public class ThreadGroupRenderer implements ObjectRenderer { public ThreadGroupRenderer() { } /** Render a {@link ThreadGroup} object similar to the way that the {@link ThreadGroup#list} method output information.

The output of a simple program consisting of one main thread is:

     java.lang.ThreadGroup[name=main, maxpri=10]
         Thread=[main,5,false]
     

The boolean value in thread information is the value returned by {@link Thread#isDaemon}. */ public String doRender(Object o) { if(o instanceof ThreadGroup) { StringBuffer sbuf = new StringBuffer(); ThreadGroup tg = (ThreadGroup) o; sbuf.append("java.lang.ThreadGroup[name="); sbuf.append(tg.getName()); sbuf.append(", maxpri="); sbuf.append(tg.getMaxPriority()); sbuf.append("]"); Thread[] t = new Thread[tg.activeCount()]; tg.enumerate(t); for(int i = 0; i < t.length; i++) { sbuf.append(Layout.LINE_SEP); sbuf.append(" Thread=["); sbuf.append(t[i].getName()); sbuf.append(","); sbuf.append(t[i].getPriority()); sbuf.append(","); sbuf.append(t[i].isDaemon()); sbuf.append("]"); } return sbuf.toString(); } else { try { // this is the best we can do return o.toString(); } catch(Exception ex) { return ex.toString(); } } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/or/RendererMap.java0000644000175000017500000001350611751454704025153 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.or; 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; /** Map class objects to an {@link ObjectRenderer}. @author Ceki Gülcü @since version 1.0 */ public class RendererMap { Hashtable map; static ObjectRenderer defaultRenderer = new DefaultRenderer(); public RendererMap() { map = new Hashtable(); } /** Add a renderer to a hierarchy passed as parameter. */ static public void addRenderer(RendererSupport repository, String renderedClassName, String renderingClassName) { LogLog.debug("Rendering class: ["+renderingClassName+"], Rendered class: ["+ renderedClassName+"]."); ObjectRenderer renderer = (ObjectRenderer) OptionConverter.instantiateByClassName(renderingClassName, ObjectRenderer.class, null); if(renderer == null) { LogLog.error("Could not instantiate renderer ["+renderingClassName+"]."); return; } else { try { Class renderedClass = Loader.loadClass(renderedClassName); repository.setRenderer(renderedClass, renderer); } catch(ClassNotFoundException e) { LogLog.error("Could not find class ["+renderedClassName+"].", e); } } } /** Find the appropriate renderer for the class type of the o parameter. This is accomplished by calling the {@link #get(Class)} method. Once a renderer is found, it is applied on the object o and the result is returned as a {@link String}. */ public String findAndRender(Object o) { if(o == null) return null; else return get(o.getClass()).doRender(o); } /** Syntactic sugar method that calls {@link #get(Class)} with the class of the object parameter. */ public ObjectRenderer get(Object o) { if(o == null) return null; else return get(o.getClass()); } /** Search the parents of clazz for a renderer. The renderer closest in the hierarchy will be returned. If no renderers could be found, then the default renderer is returned.

The search first looks for a renderer configured for clazz. If a renderer could not be found, then the search continues by looking at all the interfaces implemented by clazz including the super-interfaces of each interface. If a renderer cannot be found, then the search looks for a renderer defined for the parent (superclass) of clazz. If that fails, then all the interfaces implemented by the parent of clazz are searched and so on.

For example, if A0, A1, A2 are classes and X0, X1, X2, Y0, Y1 are interfaces where A2 extends A1 which in turn extends A0 and similarly X2 extends X1 which extends X0 and Y1 extends Y0. Let us also assume that A1 implements the Y0 interface and that A2 implements the X2 interface.

The table below shows the results returned by the get(A2.class) method depending on the renderers added to the map.

Added renderersValue returned by get(A2.class)
A0Renderer A0Renderer
A0Renderer, A1Renderer A1Renderer
X0Renderer X0Renderer
A1Renderer, X0Renderer X0Renderer

This search algorithm is not the most natural, although it is particularly easy to implement. Future log4j versions may implement a more intuitive search algorithm. However, the present algorithm should be acceptable in the vast majority of circumstances. */ public ObjectRenderer get(Class 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; } else { Class[] ia = c.getInterfaces(); for(int i = 0; i < ia.length; i++) { r = searchInterfaces(ia[i]); if(r != null) return r; } } return null; } public ObjectRenderer getDefaultRenderer() { return defaultRenderer; } public void clear() { map.clear(); } /** Register an {@link ObjectRenderer} for clazz. */ public void put(Class clazz, ObjectRenderer or) { map.put(clazz, or); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/or/sax/0000755000175000017500000000000012126647422022670 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/or/sax/AttributesRenderer.java0000644000175000017500000000333211751454704027353 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.or.sax; import org.apache.log4j.or.ObjectRenderer; import org.xml.sax.Attributes; /** Render org.xml.sax.Attributes objects. @author Ceki Gülcü @since 1.2 */ public class AttributesRenderer implements ObjectRenderer { public AttributesRenderer() { } /** Render a {@link org.xml.sax.Attributes}. */ public String doRender(Object o) { if(o instanceof Attributes) { StringBuffer sbuf = new StringBuffer(); Attributes a = (Attributes) o; int len = a.getLength(); boolean first = true; for(int i = 0; i < len; i++) { if(first) { first = false; } else { sbuf.append(", "); } sbuf.append(a.getQName(i)); sbuf.append('='); sbuf.append(a.getValue(i)); } return sbuf.toString(); } else { try { return o.toString(); } catch(Exception ex) { return ex.toString(); } } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/or/sax/package.html0000644000175000017500000000164411751454704025160 0ustar tonytony This package contains the AttributesRenderer which renders object of class org.xml.sax.Attributes. apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/or/ObjectRenderer.java0000644000175000017500000000211411751454704025635 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.or; /** Implement this interface in order to render objects as strings. @author Ceki Gülcü @since 1.0 */ public interface ObjectRenderer { /** Render the object passed as parameter as a String. */ public String doRender(Object o); } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/MDC.java0000644000175000017500000001203711751454711022726 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Hashtable; import org.apache.log4j.helpers.Loader; import org.apache.log4j.helpers.ThreadLocalMap; /** The MDC class is similar to the {@link NDC} class except that it is based on a map instead of a stack. It provides mapped diagnostic contexts. A Mapped Diagnostic Context, or MDC in short, is an instrument for distinguishing interleaved log output from different sources. Log output is typically interleaved when a server handles multiple clients near-simultaneously.

The MDC is managed on a per thread basis. A child thread automatically inherits a copy of the mapped diagnostic context of its parent.

The MDC class requires JDK 1.2 or above. Under JDK 1.1 the MDC will always return empty values but otherwise will not affect or harm your application. @since 1.2 @author Ceki Gülcü */ public class MDC { final static MDC mdc = new MDC(); static final int HT_SIZE = 7; boolean java1; Object tlm; private Method removeMethod; private MDC() { java1 = Loader.isJava1(); if(!java1) { tlm = new ThreadLocalMap(); } try { removeMethod = ThreadLocal.class.getMethod("remove", null); } catch (NoSuchMethodException e) { // don't do anything - java prior 1.5 } } /** Put a context value (the o parameter) as identified with the key parameter into the current thread's context map.

If the current thread does not have a context map it is created as a side effect. */ static public void put(String key, Object o) { if (mdc != null) { mdc.put0(key, o); } } /** Get the context identified by the key parameter.

This method has no side effects. */ static public Object get(String key) { if (mdc != null) { return mdc.get0(key); } return null; } /** Remove the the context identified by the key parameter. */ static public void remove(String key) { if (mdc != null) { mdc.remove0(key); } } /** * Get the current thread's MDC as a hashtable. This method is * intended to be used internally. * */ public static Hashtable getContext() { if (mdc != null) { return mdc.getContext0(); } else { return null; } } /** * Remove all values from the MDC. * @since 1.2.16 */ public static void clear() { if (mdc != null) { mdc.clear0(); } } private void put0(String key, Object o) { if(java1 || tlm == null) { return; } else { Hashtable ht = (Hashtable) ((ThreadLocalMap)tlm).get(); if(ht == null) { ht = new Hashtable(HT_SIZE); ((ThreadLocalMap)tlm).set(ht); } ht.put(key, o); } } private Object get0(String key) { if(java1 || tlm == null) { return null; } else { Hashtable ht = (Hashtable) ((ThreadLocalMap)tlm).get(); if(ht != null && key != null) { return ht.get(key); } else { return null; } } } private void remove0(String key) { if(!java1 && tlm != null) { Hashtable ht = (Hashtable) ((ThreadLocalMap)tlm).get(); if(ht != null) { ht.remove(key); // clean up if this was the last key if (ht.isEmpty()) { clear0(); } } } } private Hashtable getContext0() { if(java1 || tlm == null) { return null; } else { return (Hashtable) ((ThreadLocalMap)tlm).get(); } } private void clear0() { if(!java1 && tlm != null) { Hashtable ht = (Hashtable) ((ThreadLocalMap)tlm).get(); if(ht != null) { ht.clear(); } if(removeMethod != null) { // java 1.3/1.4 does not have remove - will suffer from a memory leak try { removeMethod.invoke(tlm, null); } catch (IllegalAccessException e) { // should not happen } catch (InvocationTargetException e) { // should not happen } } } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/Hierarchy.java0000644000175000017500000004020411751454711024236 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // WARNING This class MUST not have references to the Category or // WARNING RootCategory classes in its static initiliazation neither // WARNING directly nor indirectly. // Contributors: // Luke Blanshard // Mario Schomburg - IBM Global Services/Germany // Anders Kristensen // Igor Poteryaev package org.apache.log4j; import java.util.Hashtable; import java.util.Enumeration; import java.util.Vector; import org.apache.log4j.spi.LoggerFactory; import org.apache.log4j.spi.HierarchyEventListener; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.RendererSupport; import org.apache.log4j.or.RendererMap; import org.apache.log4j.or.ObjectRenderer; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.spi.ThrowableRendererSupport; import org.apache.log4j.spi.ThrowableRenderer; /** This class is specialized in retrieving loggers by name and also maintaining the logger hierarchy.

The casual user does not have to deal with this class directly.

The structure of the logger hierarchy is maintained by the {@link #getLogger} method. The hierarchy is such that children link to their parent but parents do not have any pointers to their children. Moreover, loggers can be instantiated in any order, in particular descendant before ancestor.

In case a descendant is created before a particular ancestor, then it creates a provision node for the ancestor and adds itself to the provision node. Other descendants of the same ancestor add themselves to the previously created provision node. @author Ceki Gülcü */ public class Hierarchy implements LoggerRepository, RendererSupport, ThrowableRendererSupport { private LoggerFactory defaultFactory; private Vector listeners; Hashtable ht; Logger root; RendererMap rendererMap; int thresholdInt; Level threshold; boolean emittedNoAppenderWarning = false; boolean emittedNoResourceBundleWarning = false; private ThrowableRenderer throwableRenderer = null; /** Create a new logger hierarchy. @param root The root of the new hierarchy. */ public Hierarchy(Logger root) { ht = new Hashtable(); listeners = new Vector(1); this.root = root; // Enable all level levels by default. setThreshold(Level.ALL); this.root.setHierarchy(this); rendererMap = new RendererMap(); defaultFactory = new DefaultCategoryFactory(); } /** Add an object renderer for a specific class. */ public void addRenderer(Class classToRender, ObjectRenderer or) { rendererMap.put(classToRender, or); } public void addHierarchyEventListener(HierarchyEventListener listener) { if(listeners.contains(listener)) { LogLog.warn("Ignoring attempt to add an existent listener."); } else { listeners.addElement(listener); } } /** This call will clear all logger definitions from the internal hashtable. Invoking this method will irrevocably mess up the logger hierarchy.

You should really know what you are doing before invoking this method. @since 0.9.0 */ public void clear() { //System.out.println("\n\nAbout to clear internal hash table."); ht.clear(); } public void emitNoAppenderWarning(Category cat) { // No appenders in hierarchy, warn user only once. if(!this.emittedNoAppenderWarning) { LogLog.warn("No appenders could be found for logger (" + cat.getName() + ")."); LogLog.warn("Please initialize the log4j system properly."); LogLog.warn("See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info."); this.emittedNoAppenderWarning = true; } } /** Check if the named logger exists in the hierarchy. If so return its reference, otherwise returns null. @param name The name of the logger to search for. */ public Logger exists(String name) { Object o = ht.get(new CategoryKey(name)); if(o instanceof Logger) { return (Logger) o; } else { return null; } } /** The string form of {@link #setThreshold(Level)}. */ public void setThreshold(String levelStr) { Level l = (Level) Level.toLevel(levelStr, null); if(l != null) { setThreshold(l); } else { LogLog.warn("Could not convert ["+levelStr+"] to Level."); } } /** Enable logging for logging requests with level l or higher. By default all levels are enabled. @param l The minimum level for which logging requests are sent to their appenders. */ public void setThreshold(Level l) { if(l != null) { thresholdInt = l.level; threshold = l; } } public void fireAddAppenderEvent(Category logger, Appender appender) { if(listeners != null) { int size = listeners.size(); HierarchyEventListener listener; for(int i = 0; i < size; i++) { listener = (HierarchyEventListener) listeners.elementAt(i); listener.addAppenderEvent(logger, appender); } } } void fireRemoveAppenderEvent(Category logger, Appender appender) { if(listeners != null) { int size = listeners.size(); HierarchyEventListener listener; for(int i = 0; i < size; i++) { listener = (HierarchyEventListener) listeners.elementAt(i); listener.removeAppenderEvent(logger, appender); } } } /** Returns a {@link Level} representation of the enable state. @since 1.2 */ public Level getThreshold() { return threshold; } /** Returns an integer representation of the this repository's threshold. @since 1.2 */ //public //int getThresholdInt() { // return thresholdInt; //} /** Return a new logger instance named as the first parameter using the default factory.

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. */ public Logger getLogger(String name) { return getLogger(name, defaultFactory); } /** Return a new logger instance named as the first parameter using factory.

If a logger of that name already exists, then it will be returned. Otherwise, a new logger will be instantiated by the factory 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. */ public Logger getLogger(String name, LoggerFactory factory) { //System.out.println("getInstance("+name+") called."); 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); updateParents(logger); return logger; } else if(o instanceof Logger) { return (Logger) o; } else if (o instanceof ProvisionNode) { //System.out.println("("+name+") ht.get(this) returned ProvisionNode"); logger = factory.makeNewLoggerInstance(name); logger.setHierarchy(this); ht.put(key, logger); updateChildren((ProvisionNode) o, logger); updateParents(logger); return logger; } else { // It should be impossible to arrive here return null; // but let's keep the compiler happy. } } } /** Returns all the currently defined categories in this hierarchy as an {@link java.util.Enumeration Enumeration}.

The root logger is not included in the returned {@link Enumeration}. */ public Enumeration getCurrentLoggers() { // The accumlation in v is necessary because not all elements in // 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(); if(o instanceof Logger) { v.addElement(o); } } return v.elements(); } /** @deprecated Please use {@link #getCurrentLoggers} instead. */ public Enumeration getCurrentCategories() { return getCurrentLoggers(); } /** Get the renderer map for this hierarchy. */ public RendererMap getRendererMap() { return rendererMap; } /** Get the root of this hierarchy. @since 0.9.0 */ public Logger getRootLogger() { return root; } /** This method will return true if this repository is disabled for level object passed as parameter and false otherwise. See also the {@link #setThreshold(Level) threshold} emthod. */ public boolean isDisabled(int level) { return thresholdInt > level; } /** @deprecated Deprecated with no replacement. */ public void overrideAsNeeded(String override) { LogLog.warn("The Hiearchy.overrideAsNeeded method has been deprecated."); } /** Reset all values contained in this hierarchy instance to their default. This removes all appenders from all categories, sets the level of all non-root categories to null, sets their additivity flag to true and sets the level of the root logger to {@link Level#DEBUG DEBUG}. Moreover, message disabling is set its default "off" value.

Existing categories are not removed. They are just reset.

This method should be used sparingly and with care as it will block all logging until it is completed.

@since 0.8.5 */ public void resetConfiguration() { 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 Enumeration cats = getCurrentLoggers(); while(cats.hasMoreElements()) { Logger c = (Logger) cats.nextElement(); c.setLevel(null); c.setAdditivity(true); c.setResourceBundle(null); } } rendererMap.clear(); throwableRenderer = null; } /** Does nothing. @deprecated Deprecated with no replacement. */ public void setDisableOverride(String override) { LogLog.warn("The Hiearchy.setDisableOverride method has been deprecated."); } /** Used by subclasses to add a renderer to the hierarchy passed as parameter. */ public void setRenderer(Class renderedClass, ObjectRenderer renderer) { rendererMap.put(renderedClass, renderer); } /** * {@inheritDoc} */ public void setThrowableRenderer(final ThrowableRenderer renderer) { throwableRenderer = renderer; } /** * {@inheritDoc} */ public ThrowableRenderer getThrowableRenderer() { return throwableRenderer; } /** Shutting down a hierarchy will safely close and remove all appenders in all categories including the root logger.

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 lost.

The shutdown method is careful to close nested 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 void shutdown() { Logger root = getRootLogger(); // begin by closing nested appenders root.closeNestedAppenders(); synchronized(ht) { Enumeration cats = this.getCurrentLoggers(); while(cats.hasMoreElements()) { Logger c = (Logger) cats.nextElement(); c.closeNestedAppenders(); } // then, remove all appenders root.removeAllAppenders(); cats = this.getCurrentLoggers(); while(cats.hasMoreElements()) { Logger c = (Logger) cats.nextElement(); c.removeAllAppenders(); } } } /** This method loops through all the *potential* parents of 'cat'. There 3 possible cases: 1) No entry for the potential parent of 'cat' exists We create a ProvisionNode for this potential parent and insert 'cat' in that provision node. 2) There entry is of type Logger for the potential parent. The entry is 'cat's nearest existing parent. We update cat's 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. */ final private void updateParents(Logger cat) { 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; i = name.lastIndexOf('.', i-1)) { String substr = name.substring(0, i); //System.out.println("Updating parent : " + substr); CategoryKey key = new CategoryKey(substr); // simple constructor Object o = ht.get(key); // Create a provision node for a future parent. if(o == null) { //System.out.println("No parent "+substr+" found. Creating ProvisionNode."); ProvisionNode pn = new ProvisionNode(cat); ht.put(key, pn); } else if(o instanceof Category) { parentFound = true; cat.parent = (Category) o; //System.out.println("Linking " + cat.name + " -> " + ((Category) o).name); break; // no need to update the ancestors of the closest ancestor } else if(o instanceof ProvisionNode) { ((ProvisionNode) o).addElement(cat); } else { Exception e = new IllegalStateException("unexpected object type " + o.getClass() + " in ht."); e.printStackTrace(); } } // If we could not find any existing parents, then link with root. 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 children in 'pn' We loop on all the children 'c' in 'pn': If the child 'c' has been already linked to a child of 'cat' then there is no need to update 'c'. Otherwise, we set cat's parent field to c's parent and set c's parent field to cat. */ final private void updateChildren(ProvisionNode pn, Logger logger) { //System.out.println("updateChildren called for " + logger.name); final int last = pn.size(); for(int i = 0; i < last; i++) { Logger l = (Logger) pn.elementAt(i); //System.out.println("Updating child " +p.name); // Unless this child already points to a correct (lower) parent, // 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; } } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/0000755000175000017500000000000012126647422023132 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/package.html0000644000175000017500000000171511751454707025424 0ustar tonytony

Provides classes implementing format specifiers in conversion patterns.


apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/NameAbbreviator.java0000644000175000017500000002227011751454707027046 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import java.util.ArrayList; import java.util.List; /** * NameAbbreviator generates abbreviated logger and class names. * */ public abstract class NameAbbreviator { /** * Default (no abbreviation) abbreviator. */ private static final NameAbbreviator DEFAULT = new NOPAbbreviator(); /** * Gets an abbreviator. * * For example, "%logger{2}" will output only 2 elements of the logger name, * %logger{-2} will drop 2 elements from the logger name, * "%logger{1.}" will output only the first character of the non-final elements in the name, * "%logger{1~.2~} will output the first character of the first element, two characters of * the second and subsequent elements and will use a tilde to indicate abbreviated characters. * * @param pattern abbreviation pattern. * @return abbreviator, will not be null. */ public static NameAbbreviator getAbbreviator(final String pattern) { if (pattern.length() > 0) { // if pattern is just spaces and numbers then // use MaxElementAbbreviator String trimmed = pattern.trim(); if (trimmed.length() == 0) { return DEFAULT; } int i = 0; if (trimmed.length() > 0) { if (trimmed.charAt(0) == '-') { i++; } for (; (i < trimmed.length()) && (trimmed.charAt(i) >= '0') && (trimmed.charAt(i) <= '9'); i++) { } } // // if all blanks and digits // if (i == trimmed.length()) { int elements = Integer.parseInt(trimmed); if (elements >= 0) { return new MaxElementAbbreviator(elements); } else { return new DropElementAbbreviator(-elements); } } ArrayList fragments = new ArrayList(5); char ellipsis; int charCount; int pos = 0; while ((pos < trimmed.length()) && (pos >= 0)) { int ellipsisPos = pos; if (trimmed.charAt(pos) == '*') { charCount = Integer.MAX_VALUE; ellipsisPos++; } else { if ((trimmed.charAt(pos) >= '0') && (trimmed.charAt(pos) <= '9')) { charCount = trimmed.charAt(pos) - '0'; ellipsisPos++; } else { charCount = 0; } } ellipsis = '\0'; if (ellipsisPos < trimmed.length()) { ellipsis = trimmed.charAt(ellipsisPos); if (ellipsis == '.') { ellipsis = '\0'; } } fragments.add(new PatternAbbreviatorFragment(charCount, ellipsis)); pos = trimmed.indexOf(".", pos); if (pos == -1) { break; } pos++; } return new PatternAbbreviator(fragments); } // // no matching abbreviation, return defaultAbbreviator // return DEFAULT; } /** * Gets default abbreviator. * * @return default abbreviator. */ public static NameAbbreviator getDefaultAbbreviator() { return DEFAULT; } /** * Abbreviates a name in a StringBuffer. * * @param nameStart starting position of name in buf. * @param buf buffer, may not be null. */ public abstract void abbreviate(final int nameStart, final StringBuffer buf); /** * Abbreviator that simply appends full name to buffer. */ private static class NOPAbbreviator extends NameAbbreviator { /** * Constructor. */ public NOPAbbreviator() { } /** * {@inheritDoc} */ public void abbreviate(final int nameStart, final StringBuffer buf) { } } /** * Abbreviator that drops starting path elements. */ private static class MaxElementAbbreviator extends NameAbbreviator { /** * Maximum number of path elements to output. */ private final int count; /** * Create new instance. * @param count maximum number of path elements to output. */ public MaxElementAbbreviator(final int count) { this.count = count; } /** * Abbreviate name. * @param buf buffer to append abbreviation. * @param nameStart start of name to abbreviate. */ public void abbreviate(final int nameStart, final StringBuffer buf) { // 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. int end = buf.length() - 1; String bufString = buf.toString(); for (int i = count; i > 0; i--) { end = bufString.lastIndexOf(".", end - 1); if ((end == -1) || (end < nameStart)) { return; } } buf.delete(nameStart, end + 1); } } /** * Abbreviator that drops starting path elements. */ private static class DropElementAbbreviator extends NameAbbreviator { /** * Maximum number of path elements to output. */ private final int count; /** * Create new instance. * @param count maximum number of path elements to output. */ public DropElementAbbreviator(final int count) { this.count = count; } /** * Abbreviate name. * @param buf buffer to append abbreviation. * @param nameStart start of name to abbreviate. */ public void abbreviate(final int nameStart, final StringBuffer buf) { int i = count; for(int pos = buf.indexOf(".", nameStart); pos != -1; pos = buf.indexOf(".", pos + 1)) { if(--i == 0) { buf.delete(nameStart, pos + 1); break; } } } } /** * Fragment of an pattern abbreviator. * */ private static class PatternAbbreviatorFragment { /** * Count of initial characters of element to output. */ private final int charCount; /** * Character used to represent dropped characters. * '\0' indicates no representation of dropped characters. */ private final char ellipsis; /** * Creates a PatternAbbreviatorFragment. * @param charCount number of initial characters to preserve. * @param ellipsis character to represent elimination of characters, * '\0' if no ellipsis is desired. */ public PatternAbbreviatorFragment( final int charCount, final char ellipsis) { this.charCount = charCount; this.ellipsis = ellipsis; } /** * Abbreviate element of name. * @param buf buffer to receive element. * @param startPos starting index of name element. * @return starting index of next element. */ public int abbreviate(final StringBuffer buf, final int startPos) { int nextDot = buf.toString().indexOf(".", startPos); if (nextDot != -1) { if ((nextDot - startPos) > charCount) { buf.delete(startPos + charCount, nextDot); nextDot = startPos + charCount; if (ellipsis != '\0') { buf.insert(nextDot, ellipsis); nextDot++; } } nextDot++; } return nextDot; } } /** * Pattern abbreviator. * * */ private static class PatternAbbreviator extends NameAbbreviator { /** * Element abbreviation patterns. */ private final PatternAbbreviatorFragment[] fragments; /** * Create PatternAbbreviator. * * @param fragments element abbreviation patterns. */ public PatternAbbreviator(List fragments) { if (fragments.size() == 0) { throw new IllegalArgumentException( "fragments must have at least one element"); } this.fragments = new PatternAbbreviatorFragment[fragments.size()]; fragments.toArray(this.fragments); } /** * Abbreviate name. * @param buf buffer that abbreviated name is appended. * @param nameStart start of name. */ public void abbreviate(final int nameStart, final StringBuffer buf) { // // all non-terminal patterns are executed once // int pos = nameStart; for (int i = 0; (i < (fragments.length - 1)) && (pos < buf.length()); i++) { pos = fragments[i].abbreviate(buf, pos); } // // last pattern in executed repeatedly // PatternAbbreviatorFragment terminalFragment = fragments[fragments.length - 1]; while ((pos < buf.length()) && (pos >= 0)) { pos = terminalFragment.abbreviate(buf, pos); } } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/FullLocationPatternConverter.java0000644000175000017500000000353711751454707031633 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggingEvent; /** * Format the event's line location information. * * @author Ceki Gülcü */ public final class FullLocationPatternConverter extends LoggingEventPatternConverter { /** * Singleton. */ private static final FullLocationPatternConverter INSTANCE = new FullLocationPatternConverter(); /** * Private constructor. */ private FullLocationPatternConverter() { super("Full Location", "fullLocation"); } /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ public static FullLocationPatternConverter newInstance( final String[] options) { return INSTANCE; } /** * {@inheritDoc} */ public void format(final LoggingEvent event, final StringBuffer output) { LocationInfo locationInfo = event.getLocationInformation(); if (locationInfo != null) { output.append(locationInfo.fullInfo); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/BridgePatternParser.java0000644000175000017500000000275311751454707027720 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; /** * The class implements the pre log4j 1.3 org.apache.log4j.helpers.PatternConverter * contract by delegating to the log4j 1.3 pattern implementation. * * * @author Curt Arnold * */ public final class BridgePatternParser extends org.apache.log4j.helpers.PatternParser { /** * Create a new instance. * @param conversionPattern pattern, may not be null. */ public BridgePatternParser( final String conversionPattern) { super(conversionPattern); } /** * Create new pattern converter. * @return pattern converter. */ public org.apache.log4j.helpers.PatternConverter parse() { return new BridgePatternConverter(pattern); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/LoggerPatternConverter.java0000644000175000017500000000364511751454707030457 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.spi.LoggingEvent; /** * Formats a logger name. * * @author Ceki Gülcü * */ public final class LoggerPatternConverter extends NamePatternConverter { /** * Singleton. */ private static final LoggerPatternConverter INSTANCE = new LoggerPatternConverter(null); /** * Private constructor. * @param options options, may be null. */ private LoggerPatternConverter(final String[] options) { super("Logger", "logger", options); } /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ public static LoggerPatternConverter newInstance( final String[] options) { if ((options == null) || (options.length == 0)) { return INSTANCE; } return new LoggerPatternConverter(options); } /** * {@inheritDoc} */ public void format(final LoggingEvent event, final StringBuffer toAppendTo) { final int initialLength = toAppendTo.length(); toAppendTo.append(event.getLoggerName()); abbreviate(initialLength, toAppendTo); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/ThreadPatternConverter.java0000644000175000017500000000325711751454707030446 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.spi.LoggingEvent; /** * Formats the event thread name. * * @author Ceki Gülcü */ public class ThreadPatternConverter extends LoggingEventPatternConverter { /** * Singleton. */ private static final ThreadPatternConverter INSTANCE = new ThreadPatternConverter(); /** * Private constructor. */ private ThreadPatternConverter() { super("Thread", "thread"); } /** * Obtains an instance of ThreadPatternConverter. * @param options options, currently ignored, may be null. * @return instance of ThreadPatternConverter. */ public static ThreadPatternConverter newInstance( final String[] options) { return INSTANCE; } /** * {@inheritDoc} */ public void format(final LoggingEvent event, final StringBuffer toAppendTo) { toAppendTo.append(event.getThreadName()); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/FileDatePatternConverter.java0000644000175000017500000000313611751454707030710 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; /** * Formats an date by delegating to DatePatternConverter. The default * date pattern for a %d specifier in a file name is different than * the %d pattern in pattern layout. * * @author Curt Arnold */ public final class FileDatePatternConverter { /** * Private constructor. */ private FileDatePatternConverter() { } /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ public static PatternConverter newInstance( final String[] options) { if ((options == null) || (options.length == 0)) { return DatePatternConverter.newInstance( new String[] { "yyyy-MM-dd" }); } return DatePatternConverter.newInstance(options); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/LevelPatternConverter.java0000644000175000017500000000465611751454707030312 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.Level; import org.apache.log4j.spi.LoggingEvent; /** * Return the event's level in a StringBuffer. * * @author Ceki Gülcü */ public final class LevelPatternConverter extends LoggingEventPatternConverter { /** * Integer severity for Level.TRACE. */ private static final int TRACE_INT = 5000; /** * Singleton. */ private static final LevelPatternConverter INSTANCE = new LevelPatternConverter(); /** * Private constructor. */ private LevelPatternConverter() { super("Level", "level"); } /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ public static LevelPatternConverter newInstance( final String[] options) { return INSTANCE; } /** * {@inheritDoc} */ public void format(final LoggingEvent event, final StringBuffer output) { output.append(event.getLevel().toString()); } /** * {@inheritDoc} */ public String getStyleClass(Object e) { if (e instanceof LoggingEvent) { int lint = ((LoggingEvent) e).getLevel().toInt(); switch (lint) { case TRACE_INT: return "level trace"; case Level.DEBUG_INT: return "level debug"; case Level.INFO_INT: return "level info"; case Level.WARN_INT: return "level warn"; case Level.ERROR_INT: return "level error"; case Level.FATAL_INT: return "level fatal"; default: return "level " + ((LoggingEvent) e).getLevel().toString(); } } return "level"; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/LiteralPatternConverter.java0000644000175000017500000000306111751454707030624 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.spi.LoggingEvent; /** * Formats a string literal. * * @author Curt Arnold * */ public final class LiteralPatternConverter extends LoggingEventPatternConverter { /** * String literal. */ private final String literal; /** * Create a new instance. * @param literal string literal. */ public LiteralPatternConverter(final String literal) { super("Literal", "literal"); this.literal = literal; } /** * {@inheritDoc} */ public void format(final LoggingEvent event, final StringBuffer toAppendTo) { toAppendTo.append(literal); } /** * {@inheritDoc} */ public void format(final Object obj, final StringBuffer toAppendTo) { toAppendTo.append(literal); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/PatternParser.java0000644000175000017500000004622011751454707026600 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.helpers.Loader; import org.apache.log4j.helpers.LogLog; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; // Contributors: Nelson Minar <(nelson@monkey.org> // Igor E. Poteryaev // Reinhard Deschler /** * Most of the work of the {@link org.apache.log4j.EnhancedPatternLayout} class * is delegated to the PatternParser class. *

It is this class that parses conversion patterns and creates * a chained list of {@link PatternConverter PatternConverters}. * * @author James P. Cakalic * @author Ceki Gülcü * @author Anders Kristensen * @author Paul Smith * @author Curt Arnold * */ public final class PatternParser { /** * Escape character for format specifier. */ private static final char ESCAPE_CHAR = '%'; /** * Literal state. */ private static final int LITERAL_STATE = 0; /** * In converter name state. */ private static final int CONVERTER_STATE = 1; /** * Dot state. */ private static final int DOT_STATE = 3; /** * Min state. */ private static final int MIN_STATE = 4; /** * Max state. */ private static final int MAX_STATE = 5; /** * Standard format specifiers for EnhancedPatternLayout. */ private static final Map PATTERN_LAYOUT_RULES; /** * Standard format specifiers for rolling file appenders. */ private static final Map FILENAME_PATTERN_RULES; static { // We set the global rules in the static initializer of PatternParser class Map rules = new HashMap(17); rules.put("c", LoggerPatternConverter.class); rules.put("logger", LoggerPatternConverter.class); rules.put("C", ClassNamePatternConverter.class); rules.put("class", ClassNamePatternConverter.class); rules.put("d", DatePatternConverter.class); rules.put("date", DatePatternConverter.class); rules.put("F", FileLocationPatternConverter.class); rules.put("file", FileLocationPatternConverter.class); rules.put("l", FullLocationPatternConverter.class); rules.put("L", LineLocationPatternConverter.class); rules.put("line", LineLocationPatternConverter.class); rules.put("m", MessagePatternConverter.class); rules.put("message", MessagePatternConverter.class); rules.put("n", LineSeparatorPatternConverter.class); rules.put("M", MethodLocationPatternConverter.class); rules.put("method", MethodLocationPatternConverter.class); rules.put("p", LevelPatternConverter.class); rules.put("level", LevelPatternConverter.class); rules.put("r", RelativeTimePatternConverter.class); rules.put("relative", RelativeTimePatternConverter.class); rules.put("t", ThreadPatternConverter.class); rules.put("thread", ThreadPatternConverter.class); rules.put("x", NDCPatternConverter.class); rules.put("ndc", NDCPatternConverter.class); rules.put("X", PropertiesPatternConverter.class); rules.put("properties", PropertiesPatternConverter.class); rules.put("sn", SequenceNumberPatternConverter.class); rules.put("sequenceNumber", SequenceNumberPatternConverter.class); rules.put("throwable", ThrowableInformationPatternConverter.class); PATTERN_LAYOUT_RULES = new ReadOnlyMap(rules); Map fnameRules = new HashMap(4); fnameRules.put("d", FileDatePatternConverter.class); fnameRules.put("date", FileDatePatternConverter.class); fnameRules.put("i", IntegerPatternConverter.class); fnameRules.put("index", IntegerPatternConverter.class); FILENAME_PATTERN_RULES = new ReadOnlyMap(fnameRules); } /** * Private constructor. */ private PatternParser() { } /** * Get standard format specifiers for EnhancedPatternLayout. * @return read-only map of format converter classes keyed by format specifier strings. */ public static Map getPatternLayoutRules() { return PATTERN_LAYOUT_RULES; } /** * Get standard format specifiers for rolling file appender file specification. * @return read-only map of format converter classes keyed by format specifier strings. */ public static Map getFileNamePatternRules() { return FILENAME_PATTERN_RULES; } /** Extract the converter identifier found at position i. * * After this function returns, the variable i will point to the * first char after the end of the converter identifier. * * If i points to a char which is not a character acceptable at the * start of a unicode identifier, the value null is returned. * * @param lastChar last processed character. * @param pattern format string. * @param i current index into pattern format. * @param convBuf buffer to receive conversion specifier. * @param currentLiteral literal to be output in case format specifier in unrecognized. * @return position in pattern after converter. */ private static int extractConverter( char lastChar, final String pattern, int i, final StringBuffer convBuf, final StringBuffer currentLiteral) { convBuf.setLength(0); // When this method is called, lastChar points to the first character of the // conversion word. For example: // For "%hello" lastChar = 'h' // For "%-5hello" lastChar = 'h' //System.out.println("lastchar is "+lastChar); if (!Character.isUnicodeIdentifierStart(lastChar)) { return i; } convBuf.append(lastChar); while ( (i < pattern.length()) && Character.isUnicodeIdentifierPart(pattern.charAt(i))) { convBuf.append(pattern.charAt(i)); currentLiteral.append(pattern.charAt(i)); //System.out.println("conv buffer is now ["+convBuf+"]."); i++; } return i; } /** * Extract options. * @param pattern conversion pattern. * @param i start of options. * @param options array to receive extracted options * @return position in pattern after options. */ private static int extractOptions(String pattern, int i, List options) { while ((i < pattern.length()) && (pattern.charAt(i) == '{')) { int end = pattern.indexOf('}', i); if (end == -1) { break; } String r = pattern.substring(i + 1, end); options.add(r); i = end + 1; } return i; } /** * Parse a format specifier. * @param pattern pattern to parse. * @param patternConverters list to receive pattern converters. * @param formattingInfos list to receive field specifiers corresponding to pattern converters. * @param converterRegistry map of user-supported pattern converters keyed by format specifier, may be null. * @param rules map of stock pattern converters keyed by format specifier. */ public static void parse( final String pattern, final List patternConverters, final List formattingInfos, final Map converterRegistry, final Map rules) { if (pattern == null) { throw new NullPointerException("pattern"); } StringBuffer currentLiteral = new StringBuffer(32); int patternLength = pattern.length(); int state = LITERAL_STATE; char c; int i = 0; FormattingInfo formattingInfo = FormattingInfo.getDefault(); while (i < patternLength) { c = pattern.charAt(i++); switch (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. switch (pattern.charAt(i)) { case ESCAPE_CHAR: currentLiteral.append(c); i++; // move pointer break; default: if (currentLiteral.length() != 0) { patternConverters.add( new LiteralPatternConverter(currentLiteral.toString())); formattingInfos.add(FormattingInfo.getDefault()); } currentLiteral.setLength(0); currentLiteral.append(c); // append % state = CONVERTER_STATE; formattingInfo = FormattingInfo.getDefault(); } } else { currentLiteral.append(c); } break; case CONVERTER_STATE: currentLiteral.append(c); switch (c) { case '-': formattingInfo = new FormattingInfo( true, formattingInfo.getMinLength(), formattingInfo.getMaxLength()); break; case '.': state = DOT_STATE; break; default: if ((c >= '0') && (c <= '9')) { formattingInfo = new FormattingInfo( formattingInfo.isLeftAligned(), c - '0', formattingInfo.getMaxLength()); state = MIN_STATE; } else { i = finalizeConverter( c, pattern, i, currentLiteral, formattingInfo, converterRegistry, rules, patternConverters, formattingInfos); // Next pattern is assumed to be a literal. state = LITERAL_STATE; formattingInfo = FormattingInfo.getDefault(); currentLiteral.setLength(0); } } // switch break; case MIN_STATE: currentLiteral.append(c); if ((c >= '0') && (c <= '9')) { formattingInfo = new FormattingInfo( formattingInfo.isLeftAligned(), (formattingInfo.getMinLength() * 10) + (c - '0'), formattingInfo.getMaxLength()); } else if (c == '.') { state = DOT_STATE; } else { i = finalizeConverter( c, pattern, i, currentLiteral, formattingInfo, converterRegistry, rules, patternConverters, formattingInfos); state = LITERAL_STATE; formattingInfo = FormattingInfo.getDefault(); currentLiteral.setLength(0); } break; case DOT_STATE: currentLiteral.append(c); if ((c >= '0') && (c <= '9')) { formattingInfo = new FormattingInfo( formattingInfo.isLeftAligned(), formattingInfo.getMinLength(), c - '0'); state = MAX_STATE; } else { LogLog.error( "Error occured in position " + i + ".\n Was expecting digit, instead got char \"" + c + "\"."); state = LITERAL_STATE; } break; case MAX_STATE: currentLiteral.append(c); if ((c >= '0') && (c <= '9')) { formattingInfo = new FormattingInfo( formattingInfo.isLeftAligned(), formattingInfo.getMinLength(), (formattingInfo.getMaxLength() * 10) + (c - '0')); } else { i = finalizeConverter( c, pattern, i, currentLiteral, formattingInfo, converterRegistry, rules, patternConverters, formattingInfos); state = LITERAL_STATE; formattingInfo = FormattingInfo.getDefault(); currentLiteral.setLength(0); } break; } // switch } // while if (currentLiteral.length() != 0) { patternConverters.add( new LiteralPatternConverter(currentLiteral.toString())); formattingInfos.add(FormattingInfo.getDefault()); } } /** * Creates a new PatternConverter. * * * @param converterId converterId. * @param currentLiteral literal to be used if converter is unrecognized or following converter * if converterId contains extra characters. * @param converterRegistry map of user-supported pattern converters keyed by format specifier, may be null. * @param rules map of stock pattern converters keyed by format specifier. * @param options converter options. * @return converter or null. */ private static PatternConverter createConverter( final String converterId, final StringBuffer currentLiteral, final Map converterRegistry, final Map rules, final List options) { String converterName = converterId; Object converterObj = null; for (int i = converterId.length(); (i > 0) && (converterObj == null); i--) { converterName = converterName.substring(0, i); if (converterRegistry != null) { converterObj = converterRegistry.get(converterName); } if ((converterObj == null) && (rules != null)) { converterObj = rules.get(converterName); } } if (converterObj == null) { LogLog.error("Unrecognized format specifier [" + converterId + "]"); return null; } Class converterClass = null; if (converterObj instanceof Class) { converterClass = (Class) converterObj; } else { if (converterObj instanceof String) { try { converterClass = Loader.loadClass((String) converterObj); } catch (ClassNotFoundException ex) { LogLog.warn( "Class for conversion pattern %" + converterName + " not found", ex); return null; } } else { LogLog.warn( "Bad map entry for conversion pattern %" + converterName + "."); return null; } } try { Method factory = converterClass.getMethod( "newInstance", new Class[] { Class.forName("[Ljava.lang.String;") }); String[] optionsArray = new String[options.size()]; optionsArray = (String[]) options.toArray(optionsArray); Object newObj = factory.invoke(null, new Object[] { optionsArray }); if (newObj instanceof PatternConverter) { currentLiteral.delete( 0, currentLiteral.length() - (converterId.length() - converterName.length())); return (PatternConverter) newObj; } else { LogLog.warn( "Class " + converterClass.getName() + " does not extend PatternConverter."); } } catch (Exception ex) { LogLog.error("Error creating converter for " + converterId, ex); try { // // try default constructor PatternConverter pc = (PatternConverter) converterClass.newInstance(); currentLiteral.delete( 0, currentLiteral.length() - (converterId.length() - converterName.length())); return pc; } catch (Exception ex2) { LogLog.error("Error creating converter for " + converterId, ex2); } } return null; } /** * Processes a format specifier sequence. * * @param c initial character of format specifier. * @param pattern conversion pattern * @param i current position in conversion pattern. * @param currentLiteral current literal. * @param formattingInfo current field specifier. * @param converterRegistry map of user-provided pattern converters keyed by format specifier, may be null. * @param rules map of stock pattern converters keyed by format specifier. * @param patternConverters list to receive parsed pattern converter. * @param formattingInfos list to receive corresponding field specifier. * @return position after format specifier sequence. */ private static int finalizeConverter( char c, String pattern, int i, final StringBuffer currentLiteral, final FormattingInfo formattingInfo, final Map converterRegistry, final Map rules, final List patternConverters, final List formattingInfos) { StringBuffer convBuf = new StringBuffer(); i = extractConverter(c, pattern, i, convBuf, currentLiteral); String converterId = convBuf.toString(); List options = new ArrayList(); i = extractOptions(pattern, i, options); PatternConverter pc = createConverter( converterId, currentLiteral, converterRegistry, rules, options); if (pc == null) { StringBuffer msg; if ((converterId == null) || (converterId.length() == 0)) { msg = new StringBuffer("Empty conversion specifier starting at position "); } else { msg = new StringBuffer("Unrecognized conversion specifier ["); msg.append(converterId); msg.append("] starting at position "); } msg.append(Integer.toString(i)); msg.append(" in conversion pattern."); LogLog.error(msg.toString()); patternConverters.add( new LiteralPatternConverter(currentLiteral.toString())); formattingInfos.add(FormattingInfo.getDefault()); } else { patternConverters.add(pc); formattingInfos.add(formattingInfo); if (currentLiteral.length() > 0) { patternConverters.add( new LiteralPatternConverter(currentLiteral.toString())); formattingInfos.add(FormattingInfo.getDefault()); } } currentLiteral.setLength(0); return i; } /** * The class wraps another Map but throws exceptions on any attempt to modify the map. */ private static class ReadOnlyMap implements Map { /** * Wrapped map. */ private final Map map; /** * Constructor * @param src source map. */ public ReadOnlyMap(Map src) { map = src; } /** * {@inheritDoc} */ public void clear() { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ public boolean containsKey(Object key) { return map.containsKey(key); } /** * {@inheritDoc} */ public boolean containsValue(Object value) { return map.containsValue(value); } /** * {@inheritDoc} */ public Set entrySet() { return map.entrySet(); } /** * {@inheritDoc} */ public Object get(Object key) { return map.get(key); } /** * {@inheritDoc} */ public boolean isEmpty() { return map.isEmpty(); } /** * {@inheritDoc} */ public Set keySet() { return map.keySet(); } /** * {@inheritDoc} */ public Object put(Object key, Object value) { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ public void putAll(Map t) { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ public Object remove(Object key) { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ public int size() { return map.size(); } /** * {@inheritDoc} */ public Collection values() { return map.values(); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/FormattingInfo.java0000644000175000017500000000651411751454707026736 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; /** * Modifies the output of a pattern converter for a specified minimum * and maximum width and alignment. * * * @author Jim Cakalic * @author Ceki Gülcü * @author Curt Arnold * */ public final class FormattingInfo { /** * Array of spaces. */ private static final char[] SPACES = new char[] { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' }; /** * Default instance. */ private static final FormattingInfo DEFAULT = new FormattingInfo(false, 0, Integer.MAX_VALUE); /** * Minimum length. */ private final int minLength; /** * Maximum length. */ private final int maxLength; /** * Alignment. */ private final boolean leftAlign; /** * Creates new instance. * @param leftAlign left align if true. * @param minLength minimum length. * @param maxLength maximum length. */ public FormattingInfo( final boolean leftAlign, final int minLength, final int maxLength) { this.leftAlign = leftAlign; this.minLength = minLength; this.maxLength = maxLength; } /** * Gets default instance. * @return default instance. */ public static FormattingInfo getDefault() { return DEFAULT; } /** * Determine if left aligned. * @return true if left aligned. */ public boolean isLeftAligned() { return leftAlign; } /** * Get minimum length. * @return minimum length. */ public int getMinLength() { return minLength; } /** * Get maximum length. * @return maximum length. */ public int getMaxLength() { return maxLength; } /** * Adjust the content of the buffer based on the specified lengths and alignment. * * @param fieldStart start of field in buffer. * @param buffer buffer to be modified. */ public void format(final int fieldStart, final StringBuffer buffer) { final int rawLength = buffer.length() - fieldStart; if (rawLength > maxLength) { buffer.delete(fieldStart, buffer.length() - maxLength); } else if (rawLength < minLength) { if (leftAlign) { final int fieldEnd = buffer.length(); buffer.setLength(fieldStart + minLength); for (int i = fieldEnd; i < buffer.length(); i++) { buffer.setCharAt(i, ' '); } } else { int padLength = minLength - rawLength; for (; padLength > 8; padLength -= 8) { buffer.insert(fieldStart, SPACES); } buffer.insert(fieldStart, SPACES, 0, padLength); } } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/LogEvent.java0000644000175000017500000004416011751454707025532 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.Category; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.MDC; import org.apache.log4j.NDC; import org.apache.log4j.Priority; import org.apache.log4j.helpers.Loader; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.RendererSupport; import org.apache.log4j.spi.ThrowableInformation; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import java.util.Set; // Contributors: Nelson Minar // Wolf Siberski // Anders Kristensen /** * This class is a copy of o.a.l.spi.LoggingEvent from * log4j 1.2.15 which has been renamed to keep * the same overall class name length to allow a * serialization written with a prior instance of o.a.l.spi.LoggingEvent * to be deserialized with this class just by mangling the class name * in the byte stream. * */ public class LogEvent implements java.io.Serializable { private static long startTime = System.currentTimeMillis(); /** Fully qualified name of the calling category class. */ transient public final String fqnOfCategoryClass; /** * The category of the logging event. This field is not serialized * for performance reasons. * *

It is set by the LoggingEvent constructor or set by a remote * entity after deserialization. * * @deprecated This field will be marked as private or be completely * removed in future releases. Please do not use it. * */ transient private Category logger; /** *

The category (logger) name. * * @deprecated This field will be marked as private in future * releases. Please do not access it directly. Use the {@link * #getLoggerName} method instead. * */ final public 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. * *

This field should not be accessed directly. You shoud use the * {@link #getLevel} method instead. * * @deprecated This field will be marked as private in future * releases. Please do not access it directly. Use the {@link * #getLevel} method instead. * */ transient public Priority level; /** The nested diagnostic context (NDC) of logging event. */ private String ndc; /** The mapped diagnostic context (MDC) of logging event. */ private Hashtable mdcCopy; /** Have we tried to do an NDC lookup? If we did, there is no need * to do it again. Note that its value is always false when * serialized. Thus, a receiving SocketNode will never use it's own * (incorrect) NDC. See also writeObject method. */ private boolean ndcLookupRequired = true; /** Have we tried to do an MDC lookup? If we did, there is no need * to do it again. Note that its value is always false when * serialized. See also the getMDC and getMDCCopy methods. */ private boolean mdcCopyLookupRequired = true; /** The application supplied message of logging event. */ transient private Object message; /** The application supplied message rendered through the log4j objet rendering mechanism.*/ private String renderedMessage; /** The name of thread in which this logging event was generated. */ private String threadName; /** This variable contains information about this event's throwable */ private ThrowableInformation throwableInfo; /** The number of milliseconds elapsed from 1/1/1970 until logging event was created. */ public final long timeStamp; /** Location information for the caller. */ private LocationInfo locationInfo; // Serialization static final long serialVersionUID = -868428216207166145L; static final Integer[] PARAM_ARRAY = new Integer[1]; static final String TO_LEVEL = "toLevel"; static final Class[] TO_LEVEL_PARAMS = new Class[] {int.class}; static final Hashtable methodCache = new Hashtable(3); // use a tiny table /** Instantiate a LoggingEvent from the supplied parameters.

Except {@link #timeStamp} all the other fields of LoggingEvent are filled when actually needed.

@param logger The logger generating this event. @param level The level of this event. @param message The message of this event. @param throwable The throwable of this event. */ public LogEvent(String fqnOfCategoryClass, Category logger, Priority level, Object message, Throwable throwable) { this.fqnOfCategoryClass = fqnOfCategoryClass; this.logger = logger; this.categoryName = logger.getName(); this.level = level; this.message = message; if(throwable != null) { this.throwableInfo = new ThrowableInformation(throwable); } timeStamp = System.currentTimeMillis(); } /** Instantiate a LoggingEvent from the supplied parameters.

Except {@link #timeStamp} all the other fields of LoggingEvent are filled when actually needed.

@param logger The logger generating this event. @param timeStamp the timestamp of this logging event @param level The level of this event. @param message The message of this event. @param throwable The throwable of this event. */ public LogEvent(String fqnOfCategoryClass, Category logger, long timeStamp, Priority level, Object message, Throwable throwable) { this.fqnOfCategoryClass = fqnOfCategoryClass; this.logger = logger; this.categoryName = logger.getName(); this.level = level; this.message = message; if(throwable != null) { this.throwableInfo = new ThrowableInformation(throwable); } this.timeStamp = timeStamp; } /** Create new instance. @since 1.2.15 @param fqnOfCategoryClass Fully qualified class name of Logger implementation. @param logger The logger generating this event. @param timeStamp the timestamp of this logging event @param level The level of this event. @param message The message of this event. @param threadName thread name @param throwable The throwable of this event. @param ndc Nested diagnostic context @param info Location info @param properties MDC properties */ public LogEvent(final String fqnOfCategoryClass, final Logger logger, final long timeStamp, final Level level, final Object message, final String threadName, final ThrowableInformation throwable, final String ndc, final LocationInfo info, final java.util.Map properties) { super(); this.fqnOfCategoryClass = fqnOfCategoryClass; this.logger = logger; if (logger != null) { categoryName = logger.getName(); } else { categoryName = null; } this.level = level; this.message = message; if(throwable != null) { this.throwableInfo = throwable; } this.timeStamp = timeStamp; this.threadName = threadName; ndcLookupRequired = false; this.ndc = ndc; this.locationInfo = info; mdcCopyLookupRequired = false; if (properties != null) { mdcCopy = new java.util.Hashtable(properties); } } /** Set the location information for this logging event. The collected information is cached for future use. */ public LocationInfo getLocationInformation() { if(locationInfo == null) { locationInfo = new LocationInfo(new Throwable(), fqnOfCategoryClass); } return locationInfo; } /** * Return the level of this event. Use this form instead of directly * accessing the level field. */ public Level getLevel() { return (Level) level; } /** * Return the name of the logger. Use this form instead of directly * accessing the categoryName field. */ public String getLoggerName() { return categoryName; } /** Return the message for this logging event.

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. @since 1.1 */ public Object getMessage() { if(message != null) { return message; } else { return getRenderedMessage(); } } /** * This method returns the NDC for this event. It will return the * correct content even if the event was generated in a different * thread or even on a different machine. The {@link NDC#get} method * should never be called directly. */ public String getNDC() { if(ndcLookupRequired) { ndcLookupRequired = false; ndc = NDC.get(); } return ndc; } /** Returns the the context corresponding to the key parameter. If there is a local MDC copy, possibly because we are in a logging server or running inside AsyncAppender, then we search for the key in MDC copy, if a value is found it is returned. Otherwise, if the search in MDC copy returns a null result, then the current thread's MDC is used.

Note that both the local MDC copy and the current thread's MDC are searched. */ public Object getMDC(String key) { Object r; // Note the mdcCopy is used if it exists. Otherwise we use the MDC // that is associated with the thread. if(mdcCopy != null) { r = mdcCopy.get(key); if(r != null) { return r; } } return MDC.get(key); } /** Obtain a copy of this thread's MDC prior to serialization or asynchronous logging. */ public void getMDCCopy() { if(mdcCopyLookupRequired) { mdcCopyLookupRequired = false; // the clone call is required for asynchronous logging. // See also bug #5932. Hashtable t = (Hashtable) MDC.getContext(); if(t != null) { mdcCopy = (Hashtable) t.clone(); } } } public String getRenderedMessage() { if(renderedMessage == null && message != null) { if(message instanceof String) renderedMessage = (String) message; else { LoggerRepository repository = logger.getLoggerRepository(); if(repository instanceof RendererSupport) { RendererSupport rs = (RendererSupport) repository; renderedMessage= rs.getRendererMap().findAndRender(message); } else { renderedMessage = message.toString(); } } } return renderedMessage; } /** Returns the time when the application started, in milliseconds elapsed since 01.01.1970. */ public static long getStartTime() { return startTime; } public String getThreadName() { if(threadName == null) threadName = (Thread.currentThread()).getName(); return threadName; } /** Returns the throwable information contained within this event. May be null if there is no such information.

Note that the {@link Throwable} object contained within a {@link ThrowableInformation} does not survive serialization. @since 1.1 */ public ThrowableInformation getThrowableInformation() { return throwableInfo; } /** Return this event's throwable's string[] representaion. */ public String[] getThrowableStrRep() { if(throwableInfo == null) return null; else return throwableInfo.getThrowableStrRep(); } private void readLevel(ObjectInputStream ois) throws java.io.IOException, ClassNotFoundException { int p = ois.readInt(); try { String className = (String) ois.readObject(); if(className == null) { level = Level.toLevel(p); } else { Method m = (Method) methodCache.get(className); if(m == null) { Class clazz = Loader.loadClass(className); // Note that we use Class.getDeclaredMethod instead of // Class.getMethod. This assumes that the Level subclass // implements the toLevel(int) method which is a // requirement. Actually, it does not make sense for Level // subclasses NOT to implement this method. Also note that // only Level can be subclassed and not Priority. 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); } } catch(Exception e) { LogLog.warn("Level deserialization failed, reverting to default.", e); level = Level.toLevel(p); } } private void readObject(ObjectInputStream ois) throws java.io.IOException, ClassNotFoundException { ois.defaultReadObject(); readLevel(ois); // Make sure that no location info is available to Layouts if(locationInfo == null) locationInfo = new LocationInfo(null, null); } private 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 sets the renders the message in case it wasn't up to now. this.getRenderedMessage(); // This call has a side effect of setting this.ndc and // setting ndcLookupRequired to false if not already false. this.getNDC(); // This call has a side effect of setting this.mdcCopy and // setting mdcLookupRequired to false if not already false. this.getMDCCopy(); // This sets the throwable sting representation of the event throwable. this.getThrowableStrRep(); oos.defaultWriteObject(); // serialize this event's level writeLevel(oos); } private void writeLevel(ObjectOutputStream oos) throws java.io.IOException { oos.writeInt(level.toInt()); Class clazz = level.getClass(); if(clazz == Level.class) { oos.writeObject(null); } else { // writing directly the Class object would be nicer, except that // serialized a Class object can not be read back by JDK // 1.1.x. We have to resort to this hack instead. oos.writeObject(clazz.getName()); } } /** * Set value for MDC property. * This adds the specified MDC property to the event. * Access to the MDC is not synchronized, so this * method should only be called when it is known that * no other threads are accessing the MDC. * @since 1.2.15 * @param propName * @param propValue */ public final void setProperty(final String propName, final String propValue) { if (mdcCopy == null) { getMDCCopy(); } if (mdcCopy == null) { mdcCopy = new Hashtable(); } mdcCopy.put(propName, propValue); } /** * Return a property for this event. The return value can be null. * * Equivalent to getMDC(String) in log4j 1.2. Provided * for compatibility with log4j 1.3. * * @param key property name * @return property value or null if property not set * @since 1.2.15 */ public final String getProperty(final String key) { Object value = getMDC(key); String retval = null; if (value != null) { retval = value.toString(); } return retval; } /** * Check for the existence of location information without creating it * (a byproduct of calling getLocationInformation). * @return true if location information has been extracted. * @since 1.2.15 */ public final boolean locationInformationExists() { return (locationInfo != null); } /** * Getter for the event's time stamp. The time stamp is calculated starting * from 1970-01-01 GMT. * @return timestamp * * @since 1.2.15 */ public final long getTimeStamp() { return timeStamp; } /** * Returns the set of the key values in the properties * for the event. * * The returned set is unmodifiable by the caller. * * Provided for compatibility with log4j 1.3 * * @return Set an unmodifiable set of the property keys. * @since 1.2.15 */ public Set getPropertyKeySet() { return getProperties().keySet(); } /** * Returns the set of properties * for the event. * * The returned set is unmodifiable by the caller. * * Provided for compatibility with log4j 1.3 * * @return Set an unmodifiable map of the properties. * @since 1.2.15 */ public Map getProperties() { getMDCCopy(); Map properties; if (mdcCopy == null) { properties = new HashMap(); } else { properties = mdcCopy; } return Collections.unmodifiableMap(properties); } /** * Get the fully qualified name of the calling logger sub-class/wrapper. * Provided for compatibility with log4j 1.3 * @return fully qualified class name, may be null. * @since 1.2.15 */ public String getFQNOfLoggerClass() { return fqnOfCategoryClass; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/BridgePatternConverter.java0000644000175000017500000000736711751454707030441 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.spi.LoggingEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; /** * The class implements the pre log4j 1.3 org.apache.log4j.helpers.PatternConverter * contract by delegating to the log4j 1.3 pattern implementation. * * * @author Curt Arnold * */ public final class BridgePatternConverter extends org.apache.log4j.helpers.PatternConverter { /** * Pattern converters. */ private LoggingEventPatternConverter[] patternConverters; /** * Field widths and alignment corresponding to pattern converters. */ private FormattingInfo[] patternFields; /** * Does pattern process exceptions. */ private boolean handlesExceptions; /** * Create a new instance. * @param pattern pattern, may not be null. */ public BridgePatternConverter( final String pattern) { next = null; handlesExceptions = false; List converters = new ArrayList(); List fields = new ArrayList(); Map converterRegistry = null; PatternParser.parse( pattern, converters, fields, converterRegistry, PatternParser.getPatternLayoutRules()); patternConverters = new LoggingEventPatternConverter[converters.size()]; patternFields = new FormattingInfo[converters.size()]; int i = 0; Iterator converterIter = converters.iterator(); Iterator fieldIter = fields.iterator(); while (converterIter.hasNext()) { Object converter = converterIter.next(); if (converter instanceof LoggingEventPatternConverter) { patternConverters[i] = (LoggingEventPatternConverter) converter; handlesExceptions |= patternConverters[i].handlesThrowable(); } else { patternConverters[i] = new org.apache.log4j.pattern.LiteralPatternConverter(""); } if (fieldIter.hasNext()) { patternFields[i] = (FormattingInfo) fieldIter.next(); } else { patternFields[i] = FormattingInfo.getDefault(); } i++; } } /** * {@inheritDoc} */ protected String convert(final LoggingEvent event) { // // code should be unreachable. // StringBuffer sbuf = new StringBuffer(); format(sbuf, event); return sbuf.toString(); } /** Format event to string buffer. @param sbuf string buffer to receive formatted event, may not be null. @param e event to format, may not be null. */ public void format(final StringBuffer sbuf, final LoggingEvent e) { for (int i = 0; i < patternConverters.length; i++) { int startField = sbuf.length(); patternConverters[i].format(e, sbuf); patternFields[i].format(startField, sbuf); } } /** * Will return false if any of the conversion specifiers in the pattern * handles {@link Exception Exceptions}. * @return true if the pattern formats any information from exceptions. */ public boolean ignoresThrowable() { return !handlesExceptions; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/CachedDateFormat.java0000644000175000017500000002572011751454707027126 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import java.text.DateFormat; import java.text.FieldPosition; import java.text.NumberFormat; import java.text.ParsePosition; import java.util.Date; import java.util.TimeZone; /** * CachedDateFormat optimizes the performance of a wrapped * DateFormat. The implementation is not thread-safe. * If the millisecond pattern is not recognized, * the class will only use the cache if the * same value is requested. * */ public final class CachedDateFormat extends DateFormat { /** * Serialization version. */ private static final long serialVersionUID = 1; /** * Constant used to represent that there was no change * observed when changing the millisecond count. */ public static final int NO_MILLISECONDS = -2; /** * Supported digit set. If the wrapped DateFormat uses * a different unit set, the millisecond pattern * will not be recognized and duplicate requests * will use the cache. */ private static final String DIGITS = "0123456789"; /** * Constant used to represent that there was an * observed change, but was an expected change. */ public static final int UNRECOGNIZED_MILLISECONDS = -1; /** * First magic number used to detect the millisecond position. */ private static final int MAGIC1 = 654; /** * Expected representation of first magic number. */ private static final String MAGICSTRING1 = "654"; /** * Second magic number used to detect the millisecond position. */ private static final int MAGIC2 = 987; /** * Expected representation of second magic number. */ private static final String MAGICSTRING2 = "987"; /** * Expected representation of 0 milliseconds. */ private static final String ZERO_STRING = "000"; /** * Wrapped formatter. */ private final DateFormat formatter; /** * Index of initial digit of millisecond pattern or * UNRECOGNIZED_MILLISECONDS or NO_MILLISECONDS. */ private int millisecondStart; /** * Integral second preceding the previous convered Date. */ private long slotBegin; /** * Cache of previous conversion. */ private StringBuffer cache = new StringBuffer(50); /** * Maximum validity period for the cache. * Typically 1, use cache for duplicate requests only, or * 1000, use cache for requests within the same integral second. */ private final int expiration; /** * Date requested in previous conversion. */ private long previousTime; /** * Scratch date object used to minimize date object creation. */ private final Date tmpDate = new Date(0); /** * Creates a new CachedDateFormat object. * @param dateFormat Date format, may not be null. * @param expiration maximum cached range in milliseconds. * If the dateFormat is known to be incompatible with the * caching algorithm, use a value of 0 to totally disable * caching or 1 to only use cache for duplicate requests. */ public CachedDateFormat(final DateFormat dateFormat, final int expiration) { if (dateFormat == null) { throw new IllegalArgumentException("dateFormat cannot be null"); } if (expiration < 0) { throw new IllegalArgumentException("expiration must be non-negative"); } formatter = dateFormat; this.expiration = expiration; millisecondStart = 0; // // set the previousTime so the cache will be invalid // for the next request. previousTime = Long.MIN_VALUE; slotBegin = Long.MIN_VALUE; } /** * Finds start of millisecond field in formatted time. * @param time long time, must be integral number of seconds * @param formatted String corresponding formatted string * @param formatter DateFormat date format * @return int position in string of first digit of milliseconds, * -1 indicates no millisecond field, -2 indicates unrecognized * field (likely RelativeTimeDateFormat) */ public static int findMillisecondStart( final long time, final String formatted, final DateFormat formatter) { long slotBegin = (time / 1000) * 1000; if (slotBegin > time) { slotBegin -= 1000; } int millis = (int) (time - slotBegin); int magic = MAGIC1; String magicString = MAGICSTRING1; if (millis == MAGIC1) { magic = MAGIC2; magicString = MAGICSTRING2; } String plusMagic = formatter.format(new Date(slotBegin + magic)); /** * If the string lengths differ then * we can't use the cache except for duplicate requests. */ if (plusMagic.length() != formatted.length()) { return UNRECOGNIZED_MILLISECONDS; } else { // find first difference between values for (int i = 0; i < formatted.length(); i++) { if (formatted.charAt(i) != plusMagic.charAt(i)) { // // determine the expected digits for the base time StringBuffer formattedMillis = new StringBuffer("ABC"); millisecondFormat(millis, formattedMillis, 0); String plusZero = formatter.format(new Date(slotBegin)); // If the next 3 characters match the magic // string and the expected string if ( (plusZero.length() == formatted.length()) && magicString.regionMatches( 0, plusMagic, i, magicString.length()) && formattedMillis.toString().regionMatches( 0, formatted, i, magicString.length()) && ZERO_STRING.regionMatches( 0, plusZero, i, ZERO_STRING.length())) { return i; } else { return UNRECOGNIZED_MILLISECONDS; } } } } return NO_MILLISECONDS; } /** * Formats a Date into a date/time string. * * @param date the date to format. * @param sbuf the string buffer to write to. * @param fieldPosition remains untouched. * @return the formatted time string. */ public StringBuffer format( Date date, StringBuffer sbuf, FieldPosition fieldPosition) { format(date.getTime(), sbuf); return sbuf; } /** * Formats a millisecond count into a date/time string. * * @param now Number of milliseconds after midnight 1 Jan 1970 GMT. * @param buf the string buffer to write to. * @return the formatted time string. */ public StringBuffer format(long now, StringBuffer buf) { // // If the current requested time is identical to the previously // requested time, then append the cache contents. // if (now == previousTime) { buf.append(cache); return buf; } // // If millisecond pattern was not unrecognized // (that is if it was found or milliseconds did not appear) // if (millisecondStart != UNRECOGNIZED_MILLISECONDS && // Check if the cache is still valid. // If the requested time is within the same integral second // as the last request and a shorter expiration was not requested. (now < (slotBegin + expiration)) && (now >= slotBegin) && (now < (slotBegin + 1000L))) { // // if there was a millisecond field then update it // if (millisecondStart >= 0) { millisecondFormat((int) (now - slotBegin), cache, millisecondStart); } // // update the previously requested time // (the slot begin should be unchanged) previousTime = now; buf.append(cache); return buf; } // // could not use previous value. // Call underlying formatter to format date. cache.setLength(0); tmpDate.setTime(now); cache.append(formatter.format(tmpDate)); buf.append(cache); previousTime = now; slotBegin = (previousTime / 1000) * 1000; if (slotBegin > previousTime) { slotBegin -= 1000; } // // if the milliseconds field was previous found // then reevaluate in case it moved. // if (millisecondStart >= 0) { millisecondStart = findMillisecondStart(now, cache.toString(), formatter); } return buf; } /** * Formats a count of milliseconds (0-999) into a numeric representation. * @param millis Millisecond coun between 0 and 999. * @param buf String buffer, may not be null. * @param offset Starting position in buffer, the length of the * buffer must be at least offset + 3. */ private static void millisecondFormat( final int millis, final StringBuffer buf, final int offset) { buf.setCharAt(offset, DIGITS.charAt(millis / 100)); buf.setCharAt(offset + 1, DIGITS.charAt((millis / 10) % 10)); buf.setCharAt(offset + 2, DIGITS.charAt(millis % 10)); } /** * Set timezone. * * Setting the timezone using getCalendar().setTimeZone() * will likely cause caching to misbehave. * @param timeZone TimeZone new timezone */ public void setTimeZone(final TimeZone timeZone) { formatter.setTimeZone(timeZone); previousTime = Long.MIN_VALUE; slotBegin = Long.MIN_VALUE; } /** * This method is delegated to the formatter which most * likely returns null. * @param s string representation of date. * @param pos field position, unused. * @return parsed date, likely null. */ public Date parse(String s, ParsePosition pos) { return formatter.parse(s, pos); } /** * Gets number formatter. * * @return NumberFormat number formatter */ public NumberFormat getNumberFormat() { return formatter.getNumberFormat(); } /** * Gets maximum cache validity for the specified SimpleDateTime * conversion pattern. * @param pattern conversion pattern, may not be null. * @return Duration in milliseconds from an integral second * that the cache will return consistent results. */ public static int getMaximumCacheValidity(final String pattern) { // // If there are more "S" in the pattern than just one "SSS" then // (for example, "HH:mm:ss,SSS SSS"), then set the expiration to // one millisecond which should only perform duplicate request caching. // int firstS = pattern.indexOf('S'); if ((firstS >= 0) && (firstS != pattern.lastIndexOf("SSS"))) { return 1; } return 1000; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/LoggingEventPatternConverter.java0000644000175000017500000000434711751454707031630 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.spi.LoggingEvent; /** * LoggingEventPatternConverter is a base class for pattern converters * that can format information from instances of LoggingEvent. * * @author Curt Arnold * */ public abstract class LoggingEventPatternConverter extends PatternConverter { /** * Constructs an instance of LoggingEventPatternConverter. * @param name name of converter. * @param style CSS style for output. */ protected LoggingEventPatternConverter( final String name, final String style) { super(name, style); } /** * Formats an event into a string buffer. * @param event event to format, may not be null. * @param toAppendTo string buffer to which the formatted event will be appended. May not be null. */ public abstract void format( final LoggingEvent event, final StringBuffer toAppendTo); /** * {@inheritDoc} */ public void format(final Object obj, final StringBuffer output) { if (obj instanceof LoggingEvent) { format((LoggingEvent) obj, output); } } /** * Normally pattern converters are not meant to handle Exceptions although * few pattern converters might. * * By examining the return values for this method, the containing layout will * determine whether it handles throwables or not. * @return true if this PatternConverter handles throwables */ public boolean handlesThrowable() { return false; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/MessagePatternConverter.java0000644000175000017500000000327411751454707030622 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.spi.LoggingEvent; /** * Return the event's rendered message in a StringBuffer. * * @author Ceki Gülcü */ public final class MessagePatternConverter extends LoggingEventPatternConverter { /** * Singleton. */ private static final MessagePatternConverter INSTANCE = new MessagePatternConverter(); /** * Private constructor. */ private MessagePatternConverter() { super("Message", "message"); } /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ public static MessagePatternConverter newInstance( final String[] options) { return INSTANCE; } /** * {@inheritDoc} */ public void format(final LoggingEvent event, final StringBuffer toAppendTo) { toAppendTo.append(event.getRenderedMessage()); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/SequenceNumberPatternConverter.javaapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/SequenceNumberPatternConverter.ja0000644000175000017500000000332411751454707031624 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.spi.LoggingEvent; /** * Formats the event sequence number. * * @author Ceki Gülcü */ public class SequenceNumberPatternConverter extends LoggingEventPatternConverter { /** * Singleton. */ private static final SequenceNumberPatternConverter INSTANCE = new SequenceNumberPatternConverter(); /** * Private constructor. */ private SequenceNumberPatternConverter() { super("Sequence Number", "sn"); } /** * Obtains an instance of SequencePatternConverter. * @param options options, currently ignored, may be null. * @return instance of SequencePatternConverter. */ public static SequenceNumberPatternConverter newInstance( final String[] options) { return INSTANCE; } /** * {@inheritDoc} */ public void format(final LoggingEvent event, final StringBuffer toAppendTo) { toAppendTo.append("0"); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/IntegerPatternConverter.java0000644000175000017500000000334711751454707030634 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import java.util.Date; /** * Formats an integer. * * @author Curt Arnold */ public final class IntegerPatternConverter extends PatternConverter { /** * Singleton. */ private static final IntegerPatternConverter INSTANCE = new IntegerPatternConverter(); /** * Private constructor. */ private IntegerPatternConverter() { super("Integer", "integer"); } /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ public static IntegerPatternConverter newInstance( final String[] options) { return INSTANCE; } /** * {@inheritDoc} */ public void format(Object obj, final StringBuffer toAppendTo) { if (obj instanceof Integer) { toAppendTo.append(obj.toString()); } if (obj instanceof Date) { toAppendTo.append(Long.toString(((Date) obj).getTime())); } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/LineSeparatorPatternConverter.javaapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/LineSeparatorPatternConverter.jav0000644000175000017500000000366411751454707031650 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.Layout; import org.apache.log4j.spi.LoggingEvent; /** * Formats a line separator. * * @author Ceki Gülcü */ public final class LineSeparatorPatternConverter extends LoggingEventPatternConverter { /** * Singleton. */ private static final LineSeparatorPatternConverter INSTANCE = new LineSeparatorPatternConverter(); /** * Line separator. */ private final String lineSep; /** * Private constructor. */ private LineSeparatorPatternConverter() { super("Line Sep", "lineSep"); lineSep = Layout.LINE_SEP; } /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ public static LineSeparatorPatternConverter newInstance( final String[] options) { return INSTANCE; } /** * {@inheritDoc} */ public void format(LoggingEvent event, final StringBuffer toAppendTo) { toAppendTo.append(lineSep); } /** * {@inheritDoc} */ public void format(final Object obj, final StringBuffer toAppendTo) { toAppendTo.append(lineSep); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/ClassNamePatternConverter.java0000644000175000017500000000410011751454707031071 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggingEvent; /** * Formats the class name of the site of the logging request. * * @author Ceki Gülcü */ public final class ClassNamePatternConverter extends NamePatternConverter { /** * Private constructor. * @param options options, may be null. */ private ClassNamePatternConverter( final String[] options) { super("Class Name", "class name", options); } /** * Gets an instance of ClassNamePatternConverter. * @param options options, may be null. * @return instance of pattern converter. */ public static ClassNamePatternConverter newInstance( final String[] options) { return new ClassNamePatternConverter(options); } /** * Format a logging event. * @param event event to format. * @param toAppendTo string buffer to which class name will be appended. */ public void format(final LoggingEvent event, final StringBuffer toAppendTo) { final int initialLength = toAppendTo.length(); LocationInfo li = event.getLocationInformation(); if (li == null) { toAppendTo.append(LocationInfo.NA); } else { toAppendTo.append(li.getClassName()); } abbreviate(initialLength, toAppendTo); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/NamePatternConverter.java0000644000175000017500000000372211751454707030114 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; /** * * Base class for other pattern converters which can return only parts of their name. * * @author Ceki Gülcü * @author Curt Arnold * */ public abstract class NamePatternConverter extends LoggingEventPatternConverter { /** * Abbreviator. */ private final NameAbbreviator abbreviator; /** * Constructor. * @param name name of converter. * @param style style name for associated output. * @param options options, may be null, first element will be interpreted as an abbreviation pattern. */ protected NamePatternConverter( final String name, final String style, final String[] options) { super(name, style); if ((options != null) && (options.length > 0)) { abbreviator = NameAbbreviator.getAbbreviator(options[0]); } else { abbreviator = NameAbbreviator.getDefaultAbbreviator(); } } /** * Abbreviate name in string buffer. * @param nameStart starting position of name to abbreviate. * @param buf string buffer containing name. */ protected final void abbreviate(final int nameStart, final StringBuffer buf) { abbreviator.abbreviate(nameStart, buf); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/FileLocationPatternConverter.java0000644000175000017500000000355611751454707031611 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggingEvent; /** * Return the event's line location information in a StringBuffer. * * @author Ceki Gülcü */ public final class FileLocationPatternConverter extends LoggingEventPatternConverter { /** * Singleton. */ private static final FileLocationPatternConverter INSTANCE = new FileLocationPatternConverter(); /** * Private constructor. */ private FileLocationPatternConverter() { super("File Location", "file"); } /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ public static FileLocationPatternConverter newInstance( final String[] options) { return INSTANCE; } /** * {@inheritDoc} */ public void format(final LoggingEvent event, final StringBuffer output) { LocationInfo locationInfo = event.getLocationInformation(); if (locationInfo != null) { output.append(locationInfo.getFileName()); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/LineLocationPatternConverter.java0000644000175000017500000000354711751454707031621 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggingEvent; /** * Return the event's line location information in a StringBuffer. * * @author Ceki Gülcü */ public final class LineLocationPatternConverter extends LoggingEventPatternConverter { /** * Singleton. */ private static final LineLocationPatternConverter INSTANCE = new LineLocationPatternConverter(); /** * Private constructor. */ private LineLocationPatternConverter() { super("Line", "line"); } /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ public static LineLocationPatternConverter newInstance( final String[] options) { return INSTANCE; } /** * {@inheritDoc} */ public void format(final LoggingEvent event, final StringBuffer output) { LocationInfo locationInfo = event.getLocationInformation(); if (locationInfo != null) { output.append(locationInfo.getLineNumber()); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/PropertiesPatternConverter.java0000644000175000017500000000641111751454707031366 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.spi.LoggingEvent; import java.util.Iterator; import java.util.Set; import org.apache.log4j.helpers.*; /** * Able to handle the contents of the LoggingEvent's Property bundle and either * output the entire contents of the properties in a similar format to the * java.util.Hashtable.toString(), or to output the value of a specific key * within the property bundle * when this pattern converter has the option set. * * @author Paul Smith * @author Ceki Gülcü */ public final class PropertiesPatternConverter extends LoggingEventPatternConverter { /** * Name of property to output. */ private final String option; /** * Private constructor. * @param options options, may be null. */ private PropertiesPatternConverter( final String[] options) { super( ((options != null) && (options.length > 0)) ? ("Property{" + options[0] + "}") : "Properties", "property"); if ((options != null) && (options.length > 0)) { option = options[0]; } else { option = null; } } /** * Obtains an instance of PropertiesPatternConverter. * @param options options, may be null or first element contains name of property to format. * @return instance of PropertiesPatternConverter. */ public static PropertiesPatternConverter newInstance( final String[] options) { return new PropertiesPatternConverter(options); } /** * {@inheritDoc} */ public void format(final LoggingEvent event, final StringBuffer toAppendTo) { // if there is no additional options, we output every single // Key/Value pair for the MDC in a similar format to Hashtable.toString() if (option == null) { toAppendTo.append("{"); try { Set keySet = MDCKeySetExtractor.INSTANCE.getPropertyKeySet(event); if (keySet != null) { for (Iterator i = keySet.iterator(); i.hasNext();) { Object item = i.next(); Object val = event.getMDC(item.toString()); toAppendTo.append("{").append(item).append(",").append(val).append( "}"); } } } catch(Exception ex) { LogLog.error("Unexpected exception while extracting MDC keys", ex); } toAppendTo.append("}"); } else { // otherwise they just want a single key output Object val = event.getMDC(option); if (val != null) { toAppendTo.append(val); } } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/DatePatternConverter.java0000644000175000017500000001336711751454707030117 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.spi.LoggingEvent; import java.text.SimpleDateFormat; import java.text.DateFormat; import java.text.FieldPosition; import java.text.ParsePosition; import java.util.Date; import java.util.TimeZone; /** * Convert and format the event's date in a StringBuffer. * * @author Ceki Gülcü */ public final class DatePatternConverter extends LoggingEventPatternConverter { /** * ABSOLUTE string literal. */ private static final String ABSOLUTE_FORMAT = "ABSOLUTE"; /** * SimpleTimePattern for ABSOLUTE. */ private static final String ABSOLUTE_TIME_PATTERN = "HH:mm:ss,SSS"; /** * DATE string literal. */ private static final String DATE_AND_TIME_FORMAT = "DATE"; /** * SimpleTimePattern for DATE. */ private static final String DATE_AND_TIME_PATTERN = "dd MMM yyyy HH:mm:ss,SSS"; /** * ISO8601 string literal. */ private static final String ISO8601_FORMAT = "ISO8601"; /** * SimpleTimePattern for ISO8601. */ private static final String ISO8601_PATTERN = "yyyy-MM-dd HH:mm:ss,SSS"; /** * Date format. */ private final CachedDateFormat df; /** * This class wraps a DateFormat and forces the time zone to the * default time zone before each format and parse request. */ private static class DefaultZoneDateFormat extends DateFormat { /** * Serialization version ID. */ private static final long serialVersionUID = 1; /** * Wrapped instance of DateFormat. */ private final DateFormat dateFormat; /** * Construct new instance. * @param format format, may not be null. */ public DefaultZoneDateFormat(final DateFormat format) { dateFormat = format; } /** * @{inheritDoc} */ public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { dateFormat.setTimeZone(TimeZone.getDefault()); return dateFormat.format(date, toAppendTo, fieldPosition); } /** * @{inheritDoc} */ public Date parse(String source, ParsePosition pos) { dateFormat.setTimeZone(TimeZone.getDefault()); return dateFormat.parse(source, pos); } } /** * Private constructor. * @param options options, may be null. */ private DatePatternConverter(final String[] options) { super("Date", "date"); String patternOption; if ((options == null) || (options.length == 0)) { // the branch could be optimized, but here we are making explicit // that null values for patternOption are allowed. patternOption = null; } else { patternOption = options[0]; } String pattern; if ( (patternOption == null) || patternOption.equalsIgnoreCase(ISO8601_FORMAT)) { pattern = ISO8601_PATTERN; } else if (patternOption.equalsIgnoreCase(ABSOLUTE_FORMAT)) { pattern = ABSOLUTE_TIME_PATTERN; } else if (patternOption.equalsIgnoreCase(DATE_AND_TIME_FORMAT)) { pattern = DATE_AND_TIME_PATTERN; } else { pattern = patternOption; } int maximumCacheValidity = 1000; DateFormat simpleFormat = null; try { simpleFormat = new SimpleDateFormat(pattern); maximumCacheValidity = CachedDateFormat.getMaximumCacheValidity(pattern); } catch (IllegalArgumentException e) { LogLog.warn( "Could not instantiate SimpleDateFormat with pattern " + patternOption, e); // default to the ISO8601 format simpleFormat = new SimpleDateFormat(ISO8601_PATTERN); } // if the option list contains a TZ option, then set it. if ((options != null) && (options.length > 1)) { TimeZone tz = TimeZone.getTimeZone((String) options[1]); simpleFormat.setTimeZone(tz); } else { simpleFormat = new DefaultZoneDateFormat(simpleFormat); } df = new CachedDateFormat(simpleFormat, maximumCacheValidity); } /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ public static DatePatternConverter newInstance( final String[] options) { return new DatePatternConverter(options); } /** * {@inheritDoc} */ public void format(final LoggingEvent event, final StringBuffer output) { synchronized(this) { df.format(event.timeStamp, output); } } /** * {@inheritDoc} */ public void format(final Object obj, final StringBuffer output) { if (obj instanceof Date) { format((Date) obj, output); } super.format(obj, output); } /** * Append formatted date to string buffer. * @param date date * @param toAppendTo buffer to which formatted date is appended. */ public void format(final Date date, final StringBuffer toAppendTo) { synchronized(this) { df.format(date.getTime(), toAppendTo); } } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/MethodLocationPatternConverter.javaapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/MethodLocationPatternConverter.ja0000644000175000017500000000362711751454707031622 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggingEvent; /** * Return the event's line location information in a StringBuffer. * * @author Ceki Gülcü */ public final class MethodLocationPatternConverter extends LoggingEventPatternConverter { /** * Singleton. */ private static final MethodLocationPatternConverter INSTANCE = new MethodLocationPatternConverter(); /** * Private constructor. */ private MethodLocationPatternConverter() { super("Method", "method"); } /** * Obtains an instance of MethodLocationPatternConverter. * @param options options, may be null. * @return instance of MethodLocationPatternConverter. */ public static MethodLocationPatternConverter newInstance( final String[] options) { return INSTANCE; } /** * {@inheritDoc} */ public void format(final LoggingEvent event, final StringBuffer toAppendTo) { LocationInfo locationInfo = event.getLocationInformation(); if (locationInfo != null) { toAppendTo.append(locationInfo.getMethodName()); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/RelativeTimePatternConverter.java0000644000175000017500000000602611751454707031626 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.spi.LoggingEvent; /** * Return the relative time in milliseconds since loading of the LoggingEvent * class. * * @author Ceki Gülcü */ public class RelativeTimePatternConverter extends LoggingEventPatternConverter { /** * Cached formatted timestamp. */ private CachedTimestamp lastTimestamp = new CachedTimestamp(0, ""); /** * Private constructor. */ public RelativeTimePatternConverter() { super("Time", "time"); } /** * Obtains an instance of RelativeTimePatternConverter. * @param options options, currently ignored, may be null. * @return instance of RelativeTimePatternConverter. */ public static RelativeTimePatternConverter newInstance( final String[] options) { return new RelativeTimePatternConverter(); } /** * {@inheritDoc} */ public void format(final LoggingEvent event, final StringBuffer toAppendTo) { long timestamp = event.timeStamp; if (!lastTimestamp.format(timestamp, toAppendTo)) { final String formatted = Long.toString(timestamp - LoggingEvent.getStartTime()); toAppendTo.append(formatted); lastTimestamp = new CachedTimestamp(timestamp, formatted); } } /** * Cached timestamp and formatted value. */ private static final class CachedTimestamp { /** * Cached timestamp. */ private final long timestamp; /** * Cached formatted timestamp. */ private final String formatted; /** * Creates a new instance. * @param timestamp timestamp. * @param formatted formatted timestamp. */ public CachedTimestamp(long timestamp, final String formatted) { this.timestamp = timestamp; this.formatted = formatted; } /** * Appends the cached formatted timestamp to the buffer if timestamps match. * @param newTimestamp requested timestamp. * @param toAppendTo buffer to append formatted timestamp. * @return true if requested timestamp matched cached timestamp. */ public boolean format(long newTimestamp, final StringBuffer toAppendTo) { if (newTimestamp == timestamp) { toAppendTo.append(formatted); return true; } return false; } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/NDCPatternConverter.java0000644000175000017500000000321511751454707027635 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.spi.LoggingEvent; /** * Return the event's NDC in a StringBuffer. * * @author Ceki Gülcü */ public final class NDCPatternConverter extends LoggingEventPatternConverter { /** * Singleton. */ private static final NDCPatternConverter INSTANCE = new NDCPatternConverter(); /** * Private constructor. */ private NDCPatternConverter() { super("NDC", "ndc"); } /** * Obtains an instance of NDCPatternConverter. * @param options options, may be null. * @return instance of NDCPatternConverter. */ public static NDCPatternConverter newInstance( final String[] options) { return INSTANCE; } /** * {@inheritDoc} */ public void format(final LoggingEvent event, final StringBuffer toAppendTo) { toAppendTo.append(event.getNDC()); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/ThrowableInformationPatternConverter.javaapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/ThrowableInformationPatternConver0000644000175000017500000000625611751454707031743 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.ThrowableInformation; /** * Outputs the ThrowableInformation portion of the LoggingEvent. * By default, outputs the full stack trace. %throwable{none} * or %throwable{0} suppresses the stack trace. %throwable{short} * or %throwable{1} outputs just the first line. %throwable{n} * will output n lines for a positive integer or drop the last * -n lines for a negative integer. * * @author Paul Smith * */ public class ThrowableInformationPatternConverter extends LoggingEventPatternConverter { /** * Maximum lines of stack trace to output. */ private int maxLines = Integer.MAX_VALUE; /** * Private constructor. * @param options options, may be null. */ private ThrowableInformationPatternConverter( final String[] options) { super("Throwable", "throwable"); if ((options != null) && (options.length > 0)) { if("none".equals(options[0])) { maxLines = 0; } else if("short".equals(options[0])) { maxLines = 1; } else { try { maxLines = Integer.parseInt(options[0]); } catch(NumberFormatException ex) { } } } } /** * Gets an instance of the class. * @param options pattern options, may be null. If first element is "short", * only the first line of the throwable will be formatted. * @return instance of class. */ public static ThrowableInformationPatternConverter newInstance( final String[] options) { return new ThrowableInformationPatternConverter(options); } /** * {@inheritDoc} */ public void format(final LoggingEvent event, final StringBuffer toAppendTo) { if (maxLines != 0) { ThrowableInformation information = event.getThrowableInformation(); if (information != null) { String[] stringRep = information.getThrowableStrRep(); int length = stringRep.length; if (maxLines < 0) { length += maxLines; } else if (length > maxLines) { length = maxLines; } for (int i = 0; i < length; i++) { String string = stringRep[i]; toAppendTo.append(string).append("\n"); } } } } /** * This converter obviously handles throwables. * @return true. */ public boolean handlesThrowable() { return true; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/pattern/PatternConverter.java0000644000175000017500000000515011751454707027310 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.pattern; /**

PatternConverter is an abstract class that provides the formatting functionality that derived classes need.

Conversion specifiers in a conversion patterns are parsed to individual PatternConverters. Each of which is responsible for converting an object in a converter specific manner. @author James P. Cakalic @author Ceki Gülcü @author Chris Nokes @author Curt Arnold */ public abstract class PatternConverter { /** * Converter name. */ private final String name; /** * Converter style name. */ private final String style; /** * Create a new pattern converter. * @param name name for pattern converter. * @param style CSS style for formatted output. */ protected PatternConverter(final String name, final String style) { this.name = name; this.style = style; } /** * Formats an object into a string buffer. * @param obj event to format, may not be null. * @param toAppendTo string buffer to which the formatted event will be appended. May not be null. */ public abstract void format(final Object obj, final StringBuffer toAppendTo); /** * This method returns the name of the conversion pattern. * * The name can be useful to certain Layouts such as HTMLLayout. * * @return the name of the conversion pattern */ public final String getName() { return name; } /** * This method returns the CSS style class that should be applied to * the LoggingEvent passed as parameter, which can be null. * * This information is currently used only by HTMLLayout. * * @param e null values are accepted * @return the name of the conversion pattern */ public String getStyleClass(Object e) { return style; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/varia/0000755000175000017500000000000012126647422022557 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/varia/package.html0000644000175000017500000000204411751454706025044 0ustar tonytony

Contains various appenders, filters and other odds and ends.


Last modified: Tue Mar 21 20:28:14 MET 2000 apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/varia/Roller.java0000644000175000017500000000576111751454706024676 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.varia; import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator; import java.io.IOException; import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.Socket; /** A simple application to send roll over messages to a potentially remote {@link ExternallyRolledFileAppender}.

It takes two arguments, the host_name and port_number where the ExternallyRolledFileAppender is listening. @author Ceki Gülcü @since version 0.9.0 */ public class Roller { static Logger cat = Logger.getLogger(Roller.class); static String host; static int port; // Static class. Roller() { } /** Send a "RollOver" message to ExternallyRolledFileAppender on host and port. */ public static void main(String argv[]) { BasicConfigurator.configure(); if(argv.length == 2) init(argv[0], argv[1]); else usage("Wrong number of arguments."); roll(); } static void usage(String msg) { System.err.println(msg); System.err.println( "Usage: java " + Roller.class.getName() + "host_name port_number"); System.exit(1); } static void init(String hostArg, String portArg) { host = hostArg; try { port = Integer.parseInt(portArg); } catch(java.lang.NumberFormatException e) { usage("Second argument "+portArg+" is not a valid integer."); } } static void roll() { try { Socket socket = new Socket(host, port); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); DataInputStream dis = new DataInputStream(socket.getInputStream()); dos.writeUTF(ExternallyRolledFileAppender.ROLL_OVER); String rc = dis.readUTF(); if(ExternallyRolledFileAppender.OK.equals(rc)) { cat.info("Roll over signal acknowledged by remote appender."); } else { cat.warn("Unexpected return code "+rc+" from remote entity."); System.exit(2); } } catch(IOException e) { cat.error("Could not send roll signal on host "+host+" port "+port+" .", e); System.exit(2); } System.exit(0); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/varia/LevelMatchFilter.java0000644000175000017500000000575711751454706026636 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.varia; import org.apache.log4j.Level; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.helpers.OptionConverter; /** This is a very simple filter based on level matching.

The filter admits two options LevelToMatch and AcceptOnMatch. If there is an exact match between the value of the LevelToMatch option and the level of the {@link LoggingEvent}, then the {@link #decide} method returns {@link Filter#ACCEPT} in case the AcceptOnMatch option value is set to true, if it is false then {@link Filter#DENY} is returned. If there is no match, {@link Filter#NEUTRAL} is returned. @author Ceki Gülcü @since 1.2 */ public class LevelMatchFilter extends Filter { /** Do we return ACCEPT when a match occurs. Default is true. */ boolean acceptOnMatch = true; /** */ Level levelToMatch; public void setLevelToMatch(String level) { levelToMatch = OptionConverter.toLevel(level, null); } public String getLevelToMatch() { return levelToMatch == null ? null : levelToMatch.toString(); } public void setAcceptOnMatch(boolean acceptOnMatch) { this.acceptOnMatch = acceptOnMatch; } public boolean getAcceptOnMatch() { return acceptOnMatch; } /** Return the decision of this filter. Returns {@link Filter#NEUTRAL} if the LevelToMatch option is not set or if there is not match. Otherwise, if there is a match, then the returned decision is {@link Filter#ACCEPT} if the AcceptOnMatch property is set to true. The returned decision is {@link Filter#DENY} if the AcceptOnMatch property is set to false. */ public int decide(LoggingEvent event) { if(this.levelToMatch == null) { return Filter.NEUTRAL; } boolean matchOccured = false; if(this.levelToMatch.equals(event.getLevel())) { matchOccured = true; } if(matchOccured) { if(this.acceptOnMatch) return Filter.ACCEPT; else return Filter.DENY; } else { return Filter.NEUTRAL; } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/varia/FallbackErrorHandler.java0000644000175000017500000000756311751454706027450 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.varia; import org.apache.log4j.spi.ErrorHandler; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.Appender; import org.apache.log4j.Logger; import org.apache.log4j.helpers.LogLog; import java.util.Vector; import java.io.InterruptedIOException; /** * * The FallbackErrorHandler implements the ErrorHandler * interface such that a secondary appender may be specified. This * secondary appender takes over if the primary appender fails for * whatever reason. * *

The error message is printed on System.err, and * logged in the new secondary appender. * * @author Ceki Gücü * */ public class FallbackErrorHandler implements ErrorHandler { Appender backup; Appender primary; Vector loggers; public FallbackErrorHandler() { } /** Adds the logger passed as parameter to the list of loggers that we need to search for in case of appender failure. */ public void setLogger(Logger logger) { LogLog.debug("FB: Adding logger [" + logger.getName() + "]."); if(loggers == null) { loggers = new Vector(); } loggers.addElement(logger); } /** No options to activate. */ public void activateOptions() { } /** Prints the message and the stack trace of the exception on System.err. */ public void error(String message, Exception e, int errorCode) { error(message, e, errorCode, null); } /** Prints the message and the stack trace of the exception on System.err. */ public void error(String message, Exception e, int errorCode, LoggingEvent event) { if (e instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.debug("FB: The following error reported: " + message, e); LogLog.debug("FB: INITIATING FALLBACK PROCEDURE."); if (loggers != null) { for(int i = 0; i < loggers.size(); i++) { Logger l = (Logger) loggers.elementAt(i); LogLog.debug("FB: Searching for ["+primary.getName()+"] in logger [" +l.getName() + "]."); LogLog.debug("FB: Replacing ["+primary.getName()+"] by [" + backup.getName() + "] in logger ["+ l.getName() +"]."); l.removeAppender(primary); LogLog.debug("FB: Adding appender ["+backup.getName()+"] to logger " + l.getName()); l.addAppender(backup); } } } /** Print a the error message passed as parameter on System.err. */ public void error(String message) { //if(firstTime) { //LogLog.error(message); //firstTime = false; //} } /** The appender to which this error handler is attached. */ public void setAppender(Appender primary) { LogLog.debug("FB: Setting primary appender to [" + primary.getName() + "]."); this.primary = primary; } /** Set the backup appender. */ public void setBackupAppender(Appender backup) { LogLog.debug("FB: Setting backup appender to [" + backup.getName() + "]."); this.backup = backup; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/varia/NullAppender.java0000644000175000017500000000412511751454706026021 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.varia; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.spi.LoggingEvent; /** * A NullAppender merely exists, it never outputs a message to any * device. * @author Ceki Gülc¨ */ public class NullAppender extends AppenderSkeleton { private static NullAppender instance = new NullAppender(); public NullAppender() { } /** * There are no options to acticate. * */ public void activateOptions() { } /** * Whenever you can, use this method to retreive an instance instead * of instantiating a new one with new. * @deprecated Use getNullAppender instead. getInstance should have been static. * */ public NullAppender getInstance() { return instance; } /** * Whenever you can, use this method to retreive an instance instead * of instantiating a new one with new. * */ public static NullAppender getNullAppender() { return instance; } public void close() { } /** * Does not do anything. * */ public void doAppend(LoggingEvent event) { } /** * Does not do anything. * */ protected void append(LoggingEvent event) { } /** * NullAppenders do not need a layout. * */ public boolean requiresLayout() { return false; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/varia/DenyAllFilter.java0000644000175000017500000000401211751454706026121 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.varia; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; /** This filter drops all logging events.

You can add this filter to the end of a filter chain to switch from the default "accept all unless instructed otherwise" filtering behaviour to a "deny all unless instructed otherwise" behaviour. @author Ceki Gülcü @since 0.9.0 */ public class DenyAllFilter extends Filter { /** Returns null as there are no options. @deprecated We now use JavaBeans introspection to configure components. Options strings are no longer needed. */ public String[] getOptionStrings() { return null; } /** No options to set. @deprecated Use the setter method for the option directly instead of the generic setOption method. */ public void setOption(String key, String value) { } /** Always returns the integer constant {@link Filter#DENY} regardless of the {@link LoggingEvent} parameter. @param event The LoggingEvent to filter. @return Always returns {@link Filter#DENY}. */ public int decide(LoggingEvent event) { return Filter.DENY; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/varia/ReloadingPropertyConfigurator.java0000644000175000017500000000260511751454706031465 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.varia; import java.io.InputStream; import java.net.URL; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.spi.Configurator; import org.apache.log4j.spi.LoggerRepository; public class ReloadingPropertyConfigurator implements Configurator { PropertyConfigurator delegate = new PropertyConfigurator(); public ReloadingPropertyConfigurator() { } /** * @since 1.2.17 */ public void doConfigure(InputStream inputStream, LoggerRepository repository) { } public void doConfigure(URL url, LoggerRepository repository) { } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/varia/ExternallyRolledFileAppender.java0000644000175000017500000001207711751454706031205 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.varia; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InterruptedIOException; import java.net.ServerSocket; import java.net.Socket; import org.apache.log4j.RollingFileAppender; import org.apache.log4j.helpers.LogLog; /** This appender listens on a socket on the port specified by the Port property for a "RollOver" message. When such a message is received, the underlying log file is rolled over and an acknowledgment message is sent back to the process initiating the roll over.

This method of triggering roll over has the advantage of being operating system independent, fast and reliable.

A simple application {@link Roller} is provided to initiate the roll over.

Note that the initiator is not authenticated. Anyone can trigger a rollover. In production environments, it is recommended that you add some form of protection to prevent undesired rollovers. @author Ceki Gülcü @since version 0.9.0 */ public class ExternallyRolledFileAppender extends RollingFileAppender { /** The string constant sent to initiate a roll over. Current value of this string constant is RollOver. */ static final public String ROLL_OVER = "RollOver"; /** The string constant sent to acknowledge a roll over. Current value of this string constant is OK. */ static final public String OK = "OK"; int port = 0; HUP hup; /** The default constructor does nothing but calls its super-class constructor. */ public ExternallyRolledFileAppender() { } /** The Port [roperty is used for setting the port for listening to external roll over messages. */ public void setPort(int port) { this.port = port; } /** Returns value of the Port option. */ public int getPort() { return port; } /** Start listening on the port specified by a preceding call to {@link #setPort}. */ public void activateOptions() { super.activateOptions(); if(port != 0) { if(hup != null) { hup.interrupt(); } hup = new HUP(this, port); hup.setDaemon(true); hup.start(); } } } class HUP extends Thread { int port; ExternallyRolledFileAppender er; HUP(ExternallyRolledFileAppender er, int port) { this.er = er; this.port = port; } public void run() { while(!isInterrupted()) { try { ServerSocket serverSocket = new ServerSocket(port); while(true) { Socket socket = serverSocket.accept(); LogLog.debug("Connected to client at " + socket.getInetAddress()); new Thread(new HUPNode(socket, er), "ExternallyRolledFileAppender-HUP").start(); } } catch(InterruptedIOException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } catch(RuntimeException e) { e.printStackTrace(); } } } } class HUPNode implements Runnable { Socket socket; DataInputStream dis; DataOutputStream dos; ExternallyRolledFileAppender er; public HUPNode(Socket socket, ExternallyRolledFileAppender er) { this.socket = socket; this.er = er; try { dis = new DataInputStream(socket.getInputStream()); dos = new DataOutputStream(socket.getOutputStream()); } catch(InterruptedIOException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } catch(RuntimeException e) { e.printStackTrace(); } } public void run() { try { String line = dis.readUTF(); LogLog.debug("Got external roll over signal."); if(ExternallyRolledFileAppender.ROLL_OVER.equals(line)) { synchronized(er) { er.rollOver(); } dos.writeUTF(ExternallyRolledFileAppender.OK); } else { dos.writeUTF("Expecting [RollOver] string."); } dos.close(); } catch(InterruptedIOException e) { Thread.currentThread().interrupt(); LogLog.error("Unexpected exception. Exiting HUPNode.", e); } catch(IOException e) { LogLog.error("Unexpected exception. Exiting HUPNode.", e); } catch(RuntimeException e) { LogLog.error("Unexpected exception. Exiting HUPNode.", e); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/varia/LevelRangeFilter.java0000644000175000017500000001021111751454706026613 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.varia; import org.apache.log4j.Level; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; /** This is a very simple filter based on level matching, which can be used to reject messages with priorities outside a certain range.

The filter admits three options LevelMin, LevelMax and AcceptOnMatch.

If the level of the {@link LoggingEvent} is not between Min and Max (inclusive), then {@link Filter#DENY} is returned.

If the Logging event level is within the specified range, then if AcceptOnMatch is true, {@link Filter#ACCEPT} is returned, and if AcceptOnMatch is false, {@link Filter#NEUTRAL} is returned.

If LevelMinw is not defined, then there is no minimum acceptable level (ie a level is never rejected for being too "low"/unimportant). If LevelMax is not defined, then there is no maximum acceptable level (ie a level is never rejected for beeing too "high"/important).

Refer to the {@link org.apache.log4j.AppenderSkeleton#setThreshold setThreshold} method available to all appenders extending {@link org.apache.log4j.AppenderSkeleton} for a more convenient way to filter out events by level. @author Simon Kitching @author based on code by Ceki Gülcü */ public class LevelRangeFilter extends Filter { /** Do we return ACCEPT when a match occurs. Default is false, so that later filters get run by default */ boolean acceptOnMatch = false; Level levelMin; Level levelMax; /** Return the decision of this filter. */ public int decide(LoggingEvent event) { if(this.levelMin != null) { if (event.getLevel().isGreaterOrEqual(levelMin) == false) { // level of event is less than minimum return Filter.DENY; } } if(this.levelMax != null) { if (event.getLevel().toInt() > levelMax.toInt()) { // level of event is greater than maximum // Alas, there is no Level.isGreater method. and using // a combo of isGreaterOrEqual && !Equal seems worse than // checking the int values of the level objects.. return Filter.DENY; } } if (acceptOnMatch) { // this filter set up to bypass later filters and always return // accept if level in range return Filter.ACCEPT; } else { // event is ok for this filter; allow later filters to have a look.. return Filter.NEUTRAL; } } /** Get the value of the LevelMax option. */ public Level getLevelMax() { return levelMax; } /** Get the value of the LevelMin option. */ public Level getLevelMin() { return levelMin; } /** Get the value of the AcceptOnMatch option. */ public boolean getAcceptOnMatch() { return acceptOnMatch; } /** Set the LevelMax option. */ public void setLevelMax(Level levelMax) { this.levelMax = levelMax; } /** Set the LevelMin option. */ public void setLevelMin(Level levelMin) { this.levelMin = levelMin; } /** Set the AcceptOnMatch option. */ public void setAcceptOnMatch(boolean acceptOnMatch) { this.acceptOnMatch = acceptOnMatch; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/varia/StringMatchFilter.java0000644000175000017500000000714711751454706027030 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.varia; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.helpers.OptionConverter; /** * This is a very simple filter based on string matching. * *

The filter admits two options StringToMatch and * AcceptOnMatch. If there is a match between the value of the * StringToMatch option and the message of the {@link org.apache.log4j.spi.LoggingEvent}, * then the {@link #decide(LoggingEvent)} method returns {@link org.apache.log4j.spi.Filter#ACCEPT} if * the AcceptOnMatch option value is true, if it is false then * {@link org.apache.log4j.spi.Filter#DENY} is returned. If there is no match, {@link * org.apache.log4j.spi.Filter#NEUTRAL} is returned. * * @author Ceki Gülcü * @since 0.9.0 */ public class StringMatchFilter extends Filter { /** @deprecated Options are now handled using the JavaBeans paradigm. This constant is not longer needed and will be removed in the near term. */ public static final String STRING_TO_MATCH_OPTION = "StringToMatch"; /** @deprecated Options are now handled using the JavaBeans paradigm. This constant is not longer needed and will be removed in the near term. */ public static final String ACCEPT_ON_MATCH_OPTION = "AcceptOnMatch"; boolean acceptOnMatch = true; String stringToMatch; /** @deprecated We now use JavaBeans introspection to configure components. Options strings are no longer needed. */ public String[] getOptionStrings() { return new String[] {STRING_TO_MATCH_OPTION, ACCEPT_ON_MATCH_OPTION}; } /** @deprecated Use the setter method for the option directly instead of the generic setOption method. */ public void setOption(String key, String value) { if(key.equalsIgnoreCase(STRING_TO_MATCH_OPTION)) { stringToMatch = value; } else if (key.equalsIgnoreCase(ACCEPT_ON_MATCH_OPTION)) { acceptOnMatch = OptionConverter.toBoolean(value, acceptOnMatch); } } public void setStringToMatch(String s) { stringToMatch = s; } public String getStringToMatch() { return stringToMatch; } public void setAcceptOnMatch(boolean acceptOnMatch) { this.acceptOnMatch = acceptOnMatch; } public boolean getAcceptOnMatch() { return acceptOnMatch; } /** Returns {@link Filter#NEUTRAL} is there is no string match. */ public int decide(LoggingEvent event) { String msg = event.getRenderedMessage(); if(msg == null || stringToMatch == null) return Filter.NEUTRAL; if( msg.indexOf(stringToMatch) == -1 ) { return Filter.NEUTRAL; } else { // we've got a match if(acceptOnMatch) { return Filter.ACCEPT; } else { return Filter.DENY; } } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/Layout.java0000644000175000017500000000477111751454711023606 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.spi.OptionHandler; import org.apache.log4j.spi.LoggingEvent; /** Extend this abstract class to create your own log layout format. @author Ceki Gülcü */ public abstract class Layout implements OptionHandler { // Note that the line.separator property can be looked up even by // applets. public final static String LINE_SEP = System.getProperty("line.separator"); public final static int LINE_SEP_LEN = LINE_SEP.length(); /** Implement this method to create your own layout format. */ abstract public String format(LoggingEvent event); /** Returns the content type output by this layout. The base class returns "text/plain". */ public String getContentType() { return "text/plain"; } /** Returns the header for the layout format. The base class returns null. */ public String getHeader() { return null; } /** Returns the footer for the layout format. The base class returns null. */ public String getFooter() { return null; } /** If the layout handles the throwable object contained within {@link LoggingEvent}, then the layout should return false. Otherwise, if the layout ignores throwable object, then the layout should return true. If ignoresThrowable is true, the appender is responsible for rendering the throwable.

The {@link SimpleLayout}, {@link TTCCLayout}, {@link PatternLayout} all return true. The {@link org.apache.log4j.xml.XMLLayout} returns false. @since 0.8.4 */ abstract public boolean ignoresThrowable(); } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/PatternLayout.java0000644000175000017500000003674011751454711025145 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.helpers.PatternParser; import org.apache.log4j.helpers.PatternConverter; // Contributors: Nelson Minar // Anders Kristensen /** A flexible layout configurable with pattern string. This code is known to have synchronization and other issues which are not present in org.apache.log4j.EnhancedPatternLayout. EnhancedPatternLayout should be used in preference to PatternLayout. EnhancedPatternLayout is distributed in the log4j extras companion.

The goal of this class is to {@link #format format} a {@link LoggingEvent} and return the results as a String. The results depend on the conversion pattern.

The conversion pattern is closely related to the conversion pattern of the printf function in C. A conversion pattern is composed of literal text and format control expressions called conversion specifiers.

You are free to insert any literal text within the conversion pattern.

Each conversion specifier starts with a percent sign (%) and is followed by optional format modifiers and a conversion character. The conversion character specifies the type of data, e.g. category, priority, date, thread name. The format modifiers control such things as field width, padding, left and right justification. The following is a simple example.

Let the conversion pattern be "%-5p [%t]: %m%n" and assume that the log4j environment was set to use a PatternLayout. Then the statements

   Category root = Category.getRoot();
   root.debug("Message 1");
   root.warn("Message 2");
   
would yield the output
   DEBUG [main]: Message 1
   WARN  [main]: Message 2
   

Note that there is no explicit separator between text and conversion specifiers. The pattern parser knows when it has reached the end of a conversion specifier when it reads a conversion character. In the example above the conversion specifier %-5p means the priority of the logging event should be left justified to a width of five characters. The recognized conversion characters are

Conversion Character Effect
c Used to output the category of the logging event. The category conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets.

If a precision specifier is given, then only the corresponding number of right most components of the category name will be printed. By default the category name is printed in full.

For example, for the category name "a.b.c" the pattern %c{2} will output "b.c".

C Used to output the fully qualified class name of the caller issuing the logging request. This conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets.

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.

For example, for the class name "org.apache.xyz.SomeClass", the pattern %C{1} will output "SomeClass".

WARNING Generating the caller class information is slow. Thus, use should be avoided unless execution speed is not an issue.

d Used to output the date of the logging event. The date conversion specifier may be followed by a date format specifier enclosed between braces. For example, %d{HH:mm:ss,SSS} or %d{dd MMM yyyy HH:mm:ss,SSS}. If no date format specifier is given then ISO8601 format is assumed.

The date format specifier admits the same syntax as the time pattern string of the {@link java.text.SimpleDateFormat}. Although part of the standard JDK, the performance of SimpleDateFormat is quite poor.

For better results it is recommended to use the log4j date formatters. These can be specified using one of the strings "ABSOLUTE", "DATE" and "ISO8601" for specifying {@link org.apache.log4j.helpers.AbsoluteTimeDateFormat AbsoluteTimeDateFormat}, {@link org.apache.log4j.helpers.DateTimeDateFormat DateTimeDateFormat} and respectively {@link org.apache.log4j.helpers.ISO8601DateFormat ISO8601DateFormat}. For example, %d{ISO8601} or %d{ABSOLUTE}.

These dedicated date formatters perform significantly better than {@link java.text.SimpleDateFormat}.

F Used to output the file name where the logging request was issued.

WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue.

l Used to output location information of the caller which generated the logging event.

The location information depends on the JVM implementation but usually consists of the fully qualified name of the calling method followed by the callers source the file name and line number between parentheses.

The location information can be very useful. However, its generation is extremely slow and should be avoided unless execution speed is not an issue.

L Used to output the line number from where the logging request was issued.

WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue.

m Used to output the application supplied message associated with the logging event.
M Used to output the method name where the logging request was issued.

WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue.

n Outputs the platform dependent line separator character or characters.

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.

p Used to output the priority of the logging event.
r Used to output the number of milliseconds elapsed from the construction of the layout until the creation of the logging event.
t Used to output the name of the thread that generated the logging event.
x Used to output the NDC (nested diagnostic context) associated with the thread that generated the logging event.
X

Used to output the MDC (mapped diagnostic context) associated with the thread that generated the logging event. The X conversion character must be followed by the key for the map placed between braces, as in %X{clientNumber} where clientNumber is the key. The value in the MDC corresponding to the key will be output.

See {@link MDC} class for more details.

% The sequence %% outputs a single percent sign.

By default the relevant information is output as is. However, with the aid of format modifiers it is possible to change the minimum field width, the maximum field width and justification.

The optional format modifier is placed between the percent sign and the conversion character.

The first optional format modifier is the left justification flag which is just the minus (-) character. Then comes the optional minimum field width modifier. This is a decimal constant that represents the minimum number of characters to output. If the data item requires fewer characters, it is padded on either the left or the right until the minimum width is reached. The default is to pad on the left (right justify) but you can specify right padding with the left justification flag. The padding character is space. If the data item is larger than the minimum field width, the field is expanded to accommodate the data. The value is never truncated.

This behavior can be changed using the maximum field width modifier which is designated by a period followed by a decimal constant. If the data item is longer than the maximum field, then the extra characters are removed from the beginning of the data item and not from the end. For example, it the maximum field width is eight and the data item is ten characters long, then the first two characters of the data item are dropped. This behavior deviates from the printf function in C where truncation is done from the end.

Below are various format modifier examples for the category conversion specifier.

Format modifier left justify minimum width maximum width comment
%20c false 20 none Left pad with spaces if the category name is less than 20 characters long.
%-20c true 20 none Right pad with spaces if the category name is less than 20 characters long.
%.30c NA none 30 Truncate from the beginning if the category name is longer than 30 characters.
%20.30c false 20 30 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.
%-20.30c true 20 30 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.

Below are some examples of conversion patterns.

%r [%t] %-5p %c %x - %m%n

This is essentially the TTCC layout.

%-6r [%15.15t] %-5p %30.30c %x - %m%n

Similar to the TTCC layout except that the relative time is right padded if less than 6 digits, thread name is right padded if less than 15 characters and truncated if longer and the category name is left padded if shorter than 30 characters and truncated if longer.

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 James P. Cakalic @author Ceki Gülcü @since 0.8.2 */ public class PatternLayout extends Layout { /** Default pattern string for log output. Currently set to the string "%m%n" which just prints the application supplied message. */ public final static String DEFAULT_CONVERSION_PATTERN ="%m%n"; /** A conversion pattern equivalent to the TTCCCLayout. Current value is %r [%t] %p %c %x - %m%n. */ 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; /** Constructs a PatternLayout using the DEFAULT_LAYOUT_PATTERN. The default pattern just produces the application supplied message. */ public PatternLayout() { this(DEFAULT_CONVERSION_PATTERN); } /** Constructs a PatternLayout using the supplied conversion pattern. */ public PatternLayout(String pattern) { this.pattern = pattern; head = createPatternParser((pattern == null) ? DEFAULT_CONVERSION_PATTERN : pattern).parse(); } /** Set the ConversionPattern option. This is the string which controls formatting and consists of a mix of literal content and conversion specifiers. */ public void setConversionPattern(String conversionPattern) { pattern = conversionPattern; head = createPatternParser(conversionPattern).parse(); } /** Returns the value of the ConversionPattern option. */ public String getConversionPattern() { return pattern; } /** 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 true. @since 0.8.4 */ public boolean ignoresThrowable() { return true; } /** Returns PatternParser used to parse the conversion string. Subclasses may override this to return a subclass of PatternParser which recognize custom conversion characters. @since 0.9.0 */ protected PatternParser createPatternParser(String pattern) { return new PatternParser(pattern); } /** Produces a formatted string as specified by the conversion pattern. */ public String format(LoggingEvent event) { // Reset working stringbuffer if(sbuf.capacity() > MAX_CAPACITY) { sbuf = new StringBuffer(BUF_SIZE); } else { sbuf.setLength(0); } PatternConverter c = head; while(c != null) { c.format(sbuf, event); c = c.next; } return sbuf.toString(); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/xml/0000755000175000017500000000000012126647422022255 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/xml/XMLLayout.java0000644000175000017500000001605211751454711024762 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Contributors: Mathias Bogaert package org.apache.log4j.xml; import org.apache.log4j.Layout; import org.apache.log4j.helpers.Transform; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggingEvent; import java.util.Set; import java.util.Arrays; /** * The output of the XMLLayout consists of a series of log4j:event * elements as defined in the log4j.dtd. It does not output a * complete well-formed XML file. The output is designed to be * included as an external entity in a separate file to form * a correct XML file. * *

For example, if abc is the name of the file where * the XMLLayout ouput goes, then a well-formed XML file would be: *

   <?xml version="1.0" ?>
 
  <!DOCTYPE log4j:eventSet PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd" [<!ENTITY data SYSTEM "abc">]>
 
  <log4j:eventSet version="1.2" xmlns:log4j="http://jakarta.apache.org/log4j/">
 	  &data;
  </log4j:eventSet>
  
*

This approach enforces the independence of the XMLLayout and the * appender where it is embedded. * *

The version attribute helps components to correctly * intrepret output generated by XMLLayout. The value of this * attribute should be "1.1" for output generated by log4j versions * prior to log4j 1.2 (final release) and "1.2" for relase 1.2 and * later. * * Appenders using this layout should have their encoding * set to UTF-8 or UTF-16, otherwise events containing * non ASCII characters could result in corrupted * log files. * * @author Ceki Gülcü * @since 0.9.0 * */ public class XMLLayout extends Layout { private final int DEFAULT_SIZE = 256; private final int UPPER_LIMIT = 2048; private StringBuffer buf = new StringBuffer(DEFAULT_SIZE); private boolean locationInfo = false; private boolean properties = false; /** * The LocationInfo option takes a boolean value. By 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. * *

If you are embedding this layout within an {@link * org.apache.log4j.net.SMTPAppender} then make sure to set the * LocationInfo option of that appender as well. * */ public void setLocationInfo(boolean flag) { locationInfo = flag; } /** Returns the current value of the LocationInfo option. */ public boolean getLocationInfo() { return locationInfo; } /** * Sets whether MDC key-value pairs should be output, default false. * @param flag new value. * @since 1.2.15 */ public void setProperties(final boolean flag) { properties = flag; } /** * Gets whether MDC key-value pairs should be output. * @return true if MDC key-value pairs are output. * @since 1.2.15 */ public boolean getProperties() { return properties; } /** No options to activate. */ public void activateOptions() { } /** * Formats a {@link org.apache.log4j.spi.LoggingEvent} in conformance with the log4j.dtd. * */ public String format(final LoggingEvent event) { // Reset working buffer. If the buffer is too large, then we need a new // one in order to avoid the penalty of creating a large array. if(buf.capacity() > UPPER_LIMIT) { buf = new StringBuffer(DEFAULT_SIZE); } else { buf.setLength(0); } // We yield to the \r\n heresy. buf.append("\r\n"); buf.append("\r\n"); String ndc = event.getNDC(); if(ndc != null) { buf.append("\r\n"); } String[] s = event.getThrowableStrRep(); if(s != null) { buf.append("\r\n"); } if(locationInfo) { LocationInfo locationInfo = event.getLocationInformation(); buf.append("\r\n"); } if (properties) { Set keySet = event.getPropertyKeySet(); if (keySet.size() > 0) { buf.append("\r\n"); Object[] keys = keySet.toArray(); Arrays.sort(keys); for (int i = 0; i < keys.length; i++) { String key = keys[i].toString(); Object val = event.getMDC(key); if (val != null) { buf.append("\r\n"); } } buf.append("\r\n"); } } buf.append("\r\n\r\n"); return buf.toString(); } /** The XMLLayout prints and does not ignore exceptions. Hence the return value false. */ public boolean ignoresThrowable() { return false; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/xml/package.html0000644000175000017500000000200011751454711024526 0ustar tonytony

XML based components.


Last modified: Mon Mar 27 21:17:13 MDT 2000 apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/xml/DOMConfigurator.java0000644000175000017500000011544411751454711026133 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.xml; import org.apache.log4j.Appender; import org.apache.log4j.Layout; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.config.PropertySetter; import org.apache.log4j.helpers.FileWatchdog; import org.apache.log4j.helpers.Loader; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.helpers.OptionConverter; import org.apache.log4j.or.RendererMap; import org.apache.log4j.spi.AppenderAttachable; import org.apache.log4j.spi.Configurator; import org.apache.log4j.spi.ErrorHandler; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggerFactory; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.RendererSupport; import org.apache.log4j.spi.ThrowableRenderer; import org.apache.log4j.spi.ThrowableRendererSupport; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.Reader; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.net.URLConnection; import java.util.Hashtable; import java.util.Properties; // Contributors: Mark Womack // Arun Katkere /** Use this class to initialize the log4j environment using a DOM tree.

The DTD is specified in log4j.dtd.

Sometimes it is useful to see how log4j is reading configuration files. You can enable log4j internal logging by defining the log4j.debug variable on the java command line. Alternatively, set the debug attribute in the log4j:configuration element. As in

   <log4j:configuration debug="true" xmlns:log4j="http://jakarta.apache.org/log4j/">
   ...
   </log4j:configuration>

There are sample XML files included in the package. @author Christopher Taylor @author Ceki Gülcü @author Anders Kristensen @since 0.8.3 */ public class DOMConfigurator implements Configurator { static final String CONFIGURATION_TAG = "log4j:configuration"; static final String OLD_CONFIGURATION_TAG = "configuration"; static final String RENDERER_TAG = "renderer"; private static final String THROWABLE_RENDERER_TAG = "throwableRenderer"; static final String APPENDER_TAG = "appender"; static final String APPENDER_REF_TAG = "appender-ref"; static final String PARAM_TAG = "param"; static final String LAYOUT_TAG = "layout"; static final String CATEGORY = "category"; static final String LOGGER = "logger"; static final String LOGGER_REF = "logger-ref"; static final String CATEGORY_FACTORY_TAG = "categoryFactory"; static final String LOGGER_FACTORY_TAG = "loggerFactory"; static final String NAME_ATTR = "name"; static final String CLASS_ATTR = "class"; static final String VALUE_ATTR = "value"; static final String ROOT_TAG = "root"; static final String ROOT_REF = "root-ref"; static final String LEVEL_TAG = "level"; static final String PRIORITY_TAG = "priority"; static final String FILTER_TAG = "filter"; static final String ERROR_HANDLER_TAG = "errorHandler"; static final String REF_ATTR = "ref"; static final String ADDITIVITY_ATTR = "additivity"; static final String THRESHOLD_ATTR = "threshold"; static final String CONFIG_DEBUG_ATTR = "configDebug"; static final String INTERNAL_DEBUG_ATTR = "debug"; private static final String RESET_ATTR = "reset"; static final String RENDERING_CLASS_ATTR = "renderingClass"; static final String RENDERED_CLASS_ATTR = "renderedClass"; static final String EMPTY_STR = ""; static final Class[] ONE_STRING_PARAM = new Class[] {String.class}; final static String dbfKey = "javax.xml.parsers.DocumentBuilderFactory"; // key: appenderName, value: appender Hashtable appenderBag; Properties props; LoggerRepository repository; protected LoggerFactory catFactory = null; /** No argument constructor. */ public DOMConfigurator () { appenderBag = new Hashtable(); } /** Used internally to parse appenders by IDREF name. */ protected Appender findAppenderByName(Document doc, String appenderName) { Appender appender = (Appender) appenderBag.get(appenderName); if(appender != null) { return appender; } else { // Doesn't work on DOM Level 1 : // Element element = doc.getElementById(appenderName); // Endre's hack: Element element = null; NodeList list = doc.getElementsByTagName("appender"); for (int t=0; t < list.getLength(); t++) { Node node = list.item(t); NamedNodeMap map= node.getAttributes(); Node attrNode = map.getNamedItem("name"); if (appenderName.equals(attrNode.getNodeValue())) { element = (Element) node; break; } } // Hack finished. if(element == null) { LogLog.error("No appender named ["+appenderName+"] could be found."); return null; } else { appender = parseAppender(element); if (appender != null) { appenderBag.put(appenderName, appender); } return appender; } } } /** Used internally to parse appenders by IDREF element. */ protected Appender findAppenderByReference(Element appenderRef) { String appenderName = subst(appenderRef.getAttribute(REF_ATTR)); Document doc = appenderRef.getOwnerDocument(); return findAppenderByName(doc, appenderName); } /** * Delegates unrecognized content to created instance if * it supports UnrecognizedElementParser. * @since 1.2.15 * @param instance instance, may be null. * @param element element, may not be null. * @param props properties * @throws IOException thrown if configuration of owner object * should be abandoned. */ private static void parseUnrecognizedElement(final Object instance, final Element element, final Properties props) throws Exception { boolean recognized = false; if (instance instanceof UnrecognizedElementHandler) { recognized = ((UnrecognizedElementHandler) instance).parseUnrecognizedElement( element, props); } if (!recognized) { LogLog.warn("Unrecognized element " + element.getNodeName()); } } /** * Delegates unrecognized content to created instance if * it supports UnrecognizedElementParser and catches and * logs any exception. * @since 1.2.15 * @param instance instance, may be null. * @param element element, may not be null. * @param props properties */ private static void quietParseUnrecognizedElement(final Object instance, final Element element, final Properties props) { try { parseUnrecognizedElement(instance, element, props); } catch (Exception ex) { if (ex instanceof InterruptedException || ex instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.error("Error in extension content: ", ex); } } /** Used internally to parse an appender element. */ protected Appender parseAppender (Element appenderElement) { String className = subst(appenderElement.getAttribute(CLASS_ATTR)); LogLog.debug("Class name: [" + className+']'); try { Object instance = Loader.loadClass(className).newInstance(); Appender appender = (Appender)instance; PropertySetter propSetter = new PropertySetter(appender); appender.setName(subst(appenderElement.getAttribute(NAME_ATTR))); NodeList children = appenderElement.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = children.item(loop); /* We're only interested in Elements */ if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element)currentNode; // Parse appender parameters if (currentElement.getTagName().equals(PARAM_TAG)) { setParameter(currentElement, propSetter); } // Set appender layout else if (currentElement.getTagName().equals(LAYOUT_TAG)) { appender.setLayout(parseLayout(currentElement)); } // Add filters else if (currentElement.getTagName().equals(FILTER_TAG)) { parseFilters(currentElement, appender); } else if (currentElement.getTagName().equals(ERROR_HANDLER_TAG)) { parseErrorHandler(currentElement, appender); } else if (currentElement.getTagName().equals(APPENDER_REF_TAG)) { String refName = subst(currentElement.getAttribute(REF_ATTR)); if(appender instanceof AppenderAttachable) { AppenderAttachable aa = (AppenderAttachable) appender; LogLog.debug("Attaching appender named ["+ refName+ "] to appender named ["+ appender.getName()+"]."); aa.addAppender(findAppenderByReference(currentElement)); } else { LogLog.error("Requesting attachment of appender named ["+ refName+ "] to appender named ["+ appender.getName()+ "] which does not implement org.apache.log4j.spi.AppenderAttachable."); } } else { parseUnrecognizedElement(instance, currentElement, props); } } } propSetter.activate(); return appender; } /* Yes, it's ugly. But all of these exceptions point to the same problem: we can't create an Appender */ catch (Exception oops) { if (oops instanceof InterruptedException || oops instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.error("Could not create an Appender. Reported error follows.", oops); return null; } } /** Used internally to parse an {@link ErrorHandler} element. */ protected void parseErrorHandler(Element element, Appender appender) { ErrorHandler eh = (ErrorHandler) OptionConverter.instantiateByClassName( subst(element.getAttribute(CLASS_ATTR)), org.apache.log4j.spi.ErrorHandler.class, null); if(eh != null) { eh.setAppender(appender); PropertySetter propSetter = new PropertySetter(eh); NodeList children = element.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) currentNode; String tagName = currentElement.getTagName(); if(tagName.equals(PARAM_TAG)) { setParameter(currentElement, propSetter); } else if(tagName.equals(APPENDER_REF_TAG)) { eh.setBackupAppender(findAppenderByReference(currentElement)); } else if(tagName.equals(LOGGER_REF)) { String loggerName = currentElement.getAttribute(REF_ATTR); Logger logger = (catFactory == null) ? repository.getLogger(loggerName) : repository.getLogger(loggerName, catFactory); eh.setLogger(logger); } else if(tagName.equals(ROOT_REF)) { Logger root = repository.getRootLogger(); eh.setLogger(root); } else { quietParseUnrecognizedElement(eh, currentElement, props); } } } propSetter.activate(); appender.setErrorHandler(eh); } } /** Used internally to parse a filter element. */ protected void parseFilters(Element element, Appender appender) { String clazz = subst(element.getAttribute(CLASS_ATTR)); Filter filter = (Filter) OptionConverter.instantiateByClassName(clazz, Filter.class, null); if(filter != null) { PropertySetter propSetter = new PropertySetter(filter); NodeList children = element.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) currentNode; String tagName = currentElement.getTagName(); if(tagName.equals(PARAM_TAG)) { setParameter(currentElement, propSetter); } else { quietParseUnrecognizedElement(filter, currentElement, props); } } } propSetter.activate(); LogLog.debug("Adding filter of type ["+filter.getClass() +"] to appender named ["+appender.getName()+"]."); appender.addFilter(filter); } } /** Used internally to parse an category element. */ protected void parseCategory (Element loggerElement) { // Create a new org.apache.log4j.Category object from the element. String catName = subst(loggerElement.getAttribute(NAME_ATTR)); Logger cat; String className = subst(loggerElement.getAttribute(CLASS_ATTR)); if(EMPTY_STR.equals(className)) { LogLog.debug("Retreiving an instance of org.apache.log4j.Logger."); cat = (catFactory == null) ? repository.getLogger(catName) : repository.getLogger(catName, catFactory); } else { LogLog.debug("Desired logger sub-class: ["+className+']'); try { Class clazz = Loader.loadClass(className); Method getInstanceMethod = clazz.getMethod("getLogger", ONE_STRING_PARAM); cat = (Logger) getInstanceMethod.invoke(null, new Object[] {catName}); } catch (InvocationTargetException oops) { if (oops.getTargetException() instanceof InterruptedException || oops.getTargetException() instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.error("Could not retrieve category ["+catName+ "]. Reported error follows.", oops); return; } catch (Exception oops) { LogLog.error("Could not retrieve category ["+catName+ "]. Reported error follows.", oops); return; } } // Setting up a category needs to be an atomic operation, in order // to protect potential log operations while category // configuration is in progress. synchronized(cat) { boolean additivity = OptionConverter.toBoolean( subst(loggerElement.getAttribute(ADDITIVITY_ATTR)), true); LogLog.debug("Setting ["+cat.getName()+"] additivity to ["+additivity+"]."); cat.setAdditivity(additivity); parseChildrenOfLoggerElement(loggerElement, cat, false); } } /** Used internally to parse the category factory element. */ protected void parseCategoryFactory(Element factoryElement) { String className = subst(factoryElement.getAttribute(CLASS_ATTR)); if(EMPTY_STR.equals(className)) { LogLog.error("Category Factory tag " + CLASS_ATTR + " attribute not found."); LogLog.debug("No Category Factory configured."); } else { LogLog.debug("Desired category factory: ["+className+']'); Object factory = OptionConverter.instantiateByClassName(className, LoggerFactory.class, null); if (factory instanceof LoggerFactory) { catFactory = (LoggerFactory) factory; } else { LogLog.error("Category Factory class " + className + " does not implement org.apache.log4j.LoggerFactory"); } PropertySetter propSetter = new PropertySetter(factory); Element currentElement = null; Node currentNode = null; NodeList children = factoryElement.getChildNodes(); final int length = children.getLength(); for (int loop=0; loop < length; loop++) { currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { currentElement = (Element)currentNode; if (currentElement.getTagName().equals(PARAM_TAG)) { setParameter(currentElement, propSetter); } else { quietParseUnrecognizedElement(factory, currentElement, props); } } } } } /** Used internally to parse the roor category element. */ protected void parseRoot (Element rootElement) { Logger root = repository.getRootLogger(); // category configuration needs to be atomic synchronized(root) { parseChildrenOfLoggerElement(rootElement, root, true); } } /** Used internally to parse the children of a category element. */ protected void parseChildrenOfLoggerElement(Element catElement, Logger cat, boolean isRoot) { PropertySetter propSetter = new PropertySetter(cat); // Remove all existing appenders from cat. They will be // reconstructed if need be. cat.removeAllAppenders(); NodeList children = catElement.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) currentNode; String tagName = currentElement.getTagName(); if (tagName.equals(APPENDER_REF_TAG)) { Element appenderRef = (Element) currentNode; Appender appender = findAppenderByReference(appenderRef); String refName = subst(appenderRef.getAttribute(REF_ATTR)); if(appender != null) LogLog.debug("Adding appender named ["+ refName+ "] to category ["+cat.getName()+"]."); else LogLog.debug("Appender named ["+ refName + "] not found."); cat.addAppender(appender); } else if(tagName.equals(LEVEL_TAG)) { parseLevel(currentElement, cat, isRoot); } else if(tagName.equals(PRIORITY_TAG)) { parseLevel(currentElement, cat, isRoot); } else if(tagName.equals(PARAM_TAG)) { setParameter(currentElement, propSetter); } else { quietParseUnrecognizedElement(cat, currentElement, props); } } } propSetter.activate(); } /** Used internally to parse a layout element. */ protected Layout parseLayout (Element layout_element) { String className = subst(layout_element.getAttribute(CLASS_ATTR)); LogLog.debug("Parsing layout of class: \""+className+"\""); try { Object instance = Loader.loadClass(className).newInstance(); Layout layout = (Layout)instance; PropertySetter propSetter = new PropertySetter(layout); NodeList params = layout_element.getChildNodes(); final int length = params.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = (Node)params.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) currentNode; String tagName = currentElement.getTagName(); if(tagName.equals(PARAM_TAG)) { setParameter(currentElement, propSetter); } else { parseUnrecognizedElement(instance, currentElement, props); } } } propSetter.activate(); return layout; } catch (Exception oops) { if (oops instanceof InterruptedException || oops instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.error("Could not create the Layout. Reported error follows.", oops); return null; } } protected void parseRenderer(Element element) { String renderingClass = subst(element.getAttribute(RENDERING_CLASS_ATTR)); String renderedClass = subst(element.getAttribute(RENDERED_CLASS_ATTR)); if(repository instanceof RendererSupport) { RendererMap.addRenderer((RendererSupport) repository, renderedClass, renderingClass); } } /** * Parses throwable renderer. * @param element throwableRenderer element. * @return configured throwable renderer. * @since 1.2.16. */ protected ThrowableRenderer parseThrowableRenderer(final Element element) { String className = subst(element.getAttribute(CLASS_ATTR)); LogLog.debug("Parsing throwableRenderer of class: \""+className+"\""); try { Object instance = Loader.loadClass(className).newInstance(); ThrowableRenderer tr = (ThrowableRenderer)instance; PropertySetter propSetter = new PropertySetter(tr); NodeList params = element.getChildNodes(); final int length = params.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = (Node)params.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) currentNode; String tagName = currentElement.getTagName(); if(tagName.equals(PARAM_TAG)) { setParameter(currentElement, propSetter); } else { parseUnrecognizedElement(instance, currentElement, props); } } } propSetter.activate(); return tr; } catch (Exception oops) { if (oops instanceof InterruptedException || oops instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.error("Could not create the ThrowableRenderer. Reported error follows.", oops); return null; } } /** Used internally to parse a level element. */ protected void parseLevel(Element element, Logger logger, boolean isRoot) { String catName = logger.getName(); if(isRoot) { catName = "root"; } String priStr = subst(element.getAttribute(VALUE_ATTR)); LogLog.debug("Level value for "+catName+" is ["+priStr+"]."); if(INHERITED.equalsIgnoreCase(priStr) || NULL.equalsIgnoreCase(priStr)) { if(isRoot) { LogLog.error("Root level cannot be inherited. Ignoring directive."); } else { logger.setLevel(null); } } else { String className = subst(element.getAttribute(CLASS_ATTR)); if(EMPTY_STR.equals(className)) { logger.setLevel(OptionConverter.toLevel(priStr, Level.DEBUG)); } else { LogLog.debug("Desired Level sub-class: ["+className+']'); try { Class clazz = Loader.loadClass(className); Method toLevelMethod = clazz.getMethod("toLevel", ONE_STRING_PARAM); Level pri = (Level) toLevelMethod.invoke(null, new Object[] {priStr}); logger.setLevel(pri); } catch (Exception oops) { if (oops instanceof InterruptedException || oops instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.error("Could not create level ["+priStr+ "]. Reported error follows.", oops); return; } } } LogLog.debug(catName + " level set to " + logger.getLevel()); } protected void setParameter(Element elem, PropertySetter propSetter) { String name = subst(elem.getAttribute(NAME_ATTR)); String value = (elem.getAttribute(VALUE_ATTR)); value = subst(OptionConverter.convertSpecialChars(value)); propSetter.setProperty(name, value); } /** Configure log4j using a configuration element as defined in the log4j.dtd. */ static public void configure (Element element) { DOMConfigurator configurator = new DOMConfigurator(); configurator.doConfigure(element, LogManager.getLoggerRepository()); } /** Like {@link #configureAndWatch(String, long)} except that the default delay as defined by {@link FileWatchdog#DEFAULT_DELAY} is used. @param configFilename A log4j configuration file in XML format. */ static public void configureAndWatch(String configFilename) { configureAndWatch(configFilename, FileWatchdog.DEFAULT_DELAY); } /** Read the configuration file configFilename if it exists. Moreover, a thread will be created that will periodically check if configFilename has been created or modified. The period is determined by the delay argument. If a change or file creation is detected, then configFilename is read to configure log4j. @param configFilename A log4j configuration file in XML format. @param delay The delay in milliseconds to wait between each check. */ static public void configureAndWatch(String configFilename, long delay) { XMLWatchdog xdog = new XMLWatchdog(configFilename); xdog.setDelay(delay); xdog.start(); } private interface ParseAction { Document parse(final DocumentBuilder parser) throws SAXException, IOException; } public void doConfigure(final String filename, LoggerRepository repository) { ParseAction action = new ParseAction() { public Document parse(final DocumentBuilder parser) throws SAXException, IOException { return parser.parse(new File(filename)); } public String toString() { return "file [" + filename + "]"; } }; doConfigure(action, repository); } public void doConfigure(final URL url, LoggerRepository repository) { ParseAction action = new ParseAction() { public Document parse(final DocumentBuilder parser) throws SAXException, IOException { URLConnection uConn = url.openConnection(); uConn.setUseCaches(false); InputStream stream = uConn.getInputStream(); try { InputSource src = new InputSource(stream); src.setSystemId(url.toString()); return parser.parse(src); } finally { stream.close(); } } public String toString() { return "url [" + url.toString() + "]"; } }; doConfigure(action, repository); } /** Configure log4j by reading in a log4j.dtd compliant XML configuration file. */ public void doConfigure(final InputStream inputStream, LoggerRepository repository) throws FactoryConfigurationError { ParseAction action = new ParseAction() { public Document parse(final DocumentBuilder parser) throws SAXException, IOException { InputSource inputSource = new InputSource(inputStream); inputSource.setSystemId("dummy://log4j.dtd"); return parser.parse(inputSource); } public String toString() { return "input stream [" + inputStream.toString() + "]"; } }; doConfigure(action, repository); } /** Configure log4j by reading in a log4j.dtd compliant XML configuration file. */ public void doConfigure(final Reader reader, LoggerRepository repository) throws FactoryConfigurationError { ParseAction action = new ParseAction() { public Document parse(final DocumentBuilder parser) throws SAXException, IOException { InputSource inputSource = new InputSource(reader); inputSource.setSystemId("dummy://log4j.dtd"); return parser.parse(inputSource); } public String toString() { return "reader [" + reader.toString() + "]"; } }; doConfigure(action, repository); } /** Configure log4j by reading in a log4j.dtd compliant XML configuration file. */ protected void doConfigure(final InputSource inputSource, LoggerRepository repository) throws FactoryConfigurationError { if (inputSource.getSystemId() == null) { inputSource.setSystemId("dummy://log4j.dtd"); } ParseAction action = new ParseAction() { public Document parse(final DocumentBuilder parser) throws SAXException, IOException { return parser.parse(inputSource); } public String toString() { return "input source [" + inputSource.toString() + "]"; } }; doConfigure(action, repository); } private final void doConfigure(final ParseAction action, final LoggerRepository repository) throws FactoryConfigurationError { DocumentBuilderFactory dbf = null; this.repository = repository; try { LogLog.debug("System property is :"+ OptionConverter.getSystemProperty(dbfKey, null)); dbf = DocumentBuilderFactory.newInstance(); LogLog.debug("Standard DocumentBuilderFactory search succeded."); LogLog.debug("DocumentBuilderFactory is: "+dbf.getClass().getName()); } catch(FactoryConfigurationError fce) { Exception e = fce.getException(); LogLog.debug("Could not instantiate a DocumentBuilderFactory.", e); throw fce; } try { dbf.setValidating(true); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); docBuilder.setErrorHandler(new SAXErrorHandler()); docBuilder.setEntityResolver(new Log4jEntityResolver()); Document doc = action.parse(docBuilder); parse(doc.getDocumentElement()); } catch (Exception e) { if (e instanceof InterruptedException || e instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } // I know this is miserable... LogLog.error("Could not parse "+ action.toString() + ".", e); } } /** Configure by taking in an DOM element. */ public void doConfigure(Element element, LoggerRepository repository) { this.repository = repository; parse(element); } /** A static version of {@link #doConfigure(String, LoggerRepository)}. */ static public void configure(String filename) throws FactoryConfigurationError { new DOMConfigurator().doConfigure(filename, LogManager.getLoggerRepository()); } /** A static version of {@link #doConfigure(URL, LoggerRepository)}. */ static public void configure(URL url) throws FactoryConfigurationError { new DOMConfigurator().doConfigure(url, LogManager.getLoggerRepository()); } /** Used internally to configure the log4j framework by parsing a DOM tree of XML elements based on log4j.dtd. */ protected void parse(Element element) { String rootElementName = element.getTagName(); if (!rootElementName.equals(CONFIGURATION_TAG)) { if(rootElementName.equals(OLD_CONFIGURATION_TAG)) { LogLog.warn("The <"+OLD_CONFIGURATION_TAG+ "> element has been deprecated."); LogLog.warn("Use the <"+CONFIGURATION_TAG+"> element instead."); } else { LogLog.error("DOM element is - not a <"+CONFIGURATION_TAG+"> element."); return; } } String debugAttrib = subst(element.getAttribute(INTERNAL_DEBUG_ATTR)); LogLog.debug("debug attribute= \"" + debugAttrib +"\"."); // if the log4j.dtd is not specified in the XML file, then the // "debug" attribute is returned as the empty string. if(!debugAttrib.equals("") && !debugAttrib.equals("null")) { LogLog.setInternalDebugging(OptionConverter.toBoolean(debugAttrib, true)); } else { LogLog.debug("Ignoring " + INTERNAL_DEBUG_ATTR + " attribute."); } // // reset repository before configuration if reset="true" // on configuration element. // String resetAttrib = subst(element.getAttribute(RESET_ATTR)); LogLog.debug("reset attribute= \"" + resetAttrib +"\"."); if(!("".equals(resetAttrib))) { if (OptionConverter.toBoolean(resetAttrib, false)) { repository.resetConfiguration(); } } String confDebug = subst(element.getAttribute(CONFIG_DEBUG_ATTR)); if(!confDebug.equals("") && !confDebug.equals("null")) { LogLog.warn("The \""+CONFIG_DEBUG_ATTR+"\" attribute is deprecated."); LogLog.warn("Use the \""+INTERNAL_DEBUG_ATTR+"\" attribute instead."); LogLog.setInternalDebugging(OptionConverter.toBoolean(confDebug, true)); } String thresholdStr = subst(element.getAttribute(THRESHOLD_ATTR)); LogLog.debug("Threshold =\"" + thresholdStr +"\"."); if(!"".equals(thresholdStr) && !"null".equals(thresholdStr)) { repository.setThreshold(thresholdStr); } //Hashtable appenderBag = new Hashtable(11); /* Building Appender objects, placing them in a local namespace for future reference */ // First configure each category factory under the root element. // Category factories need to be configured before any of // categories they support. // String tagName = null; Element currentElement = null; Node currentNode = null; NodeList children = element.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { currentElement = (Element) currentNode; tagName = currentElement.getTagName(); if (tagName.equals(CATEGORY_FACTORY_TAG) || tagName.equals(LOGGER_FACTORY_TAG)) { parseCategoryFactory(currentElement); } } } for (int loop = 0; loop < length; loop++) { currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { currentElement = (Element) currentNode; tagName = currentElement.getTagName(); if (tagName.equals(CATEGORY) || tagName.equals(LOGGER)) { parseCategory(currentElement); } else if (tagName.equals(ROOT_TAG)) { parseRoot(currentElement); } else if(tagName.equals(RENDERER_TAG)) { parseRenderer(currentElement); } else if(tagName.equals(THROWABLE_RENDERER_TAG)) { if (repository instanceof ThrowableRendererSupport) { ThrowableRenderer tr = parseThrowableRenderer(currentElement); if (tr != null) { ((ThrowableRendererSupport) repository).setThrowableRenderer(tr); } } } else if (!(tagName.equals(APPENDER_TAG) || tagName.equals(CATEGORY_FACTORY_TAG) || tagName.equals(LOGGER_FACTORY_TAG))) { quietParseUnrecognizedElement(repository, currentElement, props); } } } } protected String subst(final String value) { return subst(value, props); } /** * Substitutes property value for any references in expression. * * @param value value from configuration file, may contain * literal text, property references or both * @param props properties. * @return evaluated expression, may still contain expressions * if unable to expand. * @since 1.2.15 */ public static String subst(final String value, final Properties props) { try { return OptionConverter.substVars(value, props); } catch (IllegalArgumentException e) { LogLog.warn("Could not perform variable substitution.", e); return value; } } /** * Sets a parameter based from configuration file content. * * @param elem param element, may not be null. * @param propSetter property setter, may not be null. * @param props properties * @since 1.2.15 */ public static void setParameter(final Element elem, final PropertySetter propSetter, final Properties props) { String name = subst(elem.getAttribute("name"), props); String value = (elem.getAttribute("value")); value = subst(OptionConverter.convertSpecialChars(value), props); propSetter.setProperty(name, value); } /** * Creates an object and processes any nested param elements * but does not call activateOptions. If the class also supports * UnrecognizedElementParser, the parseUnrecognizedElement method * will be call for any child elements other than param. * * @param element element, may not be null. * @param props properties * @param expectedClass interface or class expected to be implemented * by created class * @return created class or null. * @throws Exception thrown if the contain object should be abandoned. * @since 1.2.15 */ public static Object parseElement(final Element element, final Properties props, final Class expectedClass) throws Exception { String clazz = subst(element.getAttribute("class"), props); Object instance = OptionConverter.instantiateByClassName(clazz, expectedClass, null); if (instance != null) { PropertySetter propSetter = new PropertySetter(instance); NodeList children = element.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) currentNode; String tagName = currentElement.getTagName(); if (tagName.equals("param")) { setParameter(currentElement, propSetter, props); } else { parseUnrecognizedElement(instance, currentElement, props); } } } return instance; } return null; } } class XMLWatchdog extends FileWatchdog { XMLWatchdog(String filename) { super(filename); } /** Call {@link DOMConfigurator#configure(String)} with the filename to reconfigure log4j. */ public void doOnChange() { new DOMConfigurator().doConfigure(filename, LogManager.getLoggerRepository()); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/xml/SAXErrorHandler.java0000644000175000017500000000301611751454711026063 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.xml; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException; import org.apache.log4j.helpers.LogLog; public class SAXErrorHandler implements ErrorHandler { public void error(final SAXParseException ex) { emitMessage("Continuable parsing error ", ex); } public void fatalError(final SAXParseException ex) { emitMessage("Fatal parsing error ", ex); } public void warning(final SAXParseException ex) { emitMessage("Parsing warning ", ex); } private static void emitMessage(final String msg, final SAXParseException ex) { LogLog.warn(msg +ex.getLineNumber()+" and column " +ex.getColumnNumber()); LogLog.warn(ex.getMessage(), ex.getException()); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/xml/UnrecognizedElementHandler.java0000644000175000017500000000331311751454711030364 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.xml; import org.w3c.dom.Element; import java.util.Properties; /** * When implemented by an object configured by DOMConfigurator, * the handle method will be called when an unrecognized child * element is encountered. Unrecognized child elements of * the log4j:configuration element will be dispatched to * the logger repository if it supports this interface. * * @since 1.2.15 */ public interface UnrecognizedElementHandler { /** * Called to inform a configured object when * an unrecognized child element is encountered. * @param element element, may not be null. * @param props properties in force, may be null. * @return true if configured object recognized the element * @throws Exception throw an exception to prevent activation * of the configured object. */ boolean parseUnrecognizedElement(Element element, Properties props) throws Exception; }apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/xml/Log4jEntityResolver.java0000644000175000017500000000351411751454711027021 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.xml; import org.apache.log4j.helpers.LogLog; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import java.io.InputStream; import java.io.ByteArrayInputStream; /** * An {@link EntityResolver} specifically designed to return * log4j.dtd which is embedded within the log4j jar * file. * * @author Paul Austin * */ public class Log4jEntityResolver implements EntityResolver { private static final String PUBLIC_ID = "-//APACHE//DTD LOG4J 1.2//EN"; public InputSource resolveEntity (String publicId, String systemId) { if (systemId.endsWith("log4j.dtd") || PUBLIC_ID.equals(publicId)) { Class clazz = getClass(); InputStream in = clazz.getResourceAsStream("/org/apache/log4j/xml/log4j.dtd"); if (in == null) { LogLog.warn("Could not find [log4j.dtd] using [" + clazz.getClassLoader() + "] class loader, parsed without DTD."); in = new ByteArrayInputStream(new byte[0]); } return new InputSource(in); } else { return null; } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/DefaultCategoryFactory.java0000644000175000017500000000206211751454711026732 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.spi.LoggerFactory; class DefaultCategoryFactory implements LoggerFactory { DefaultCategoryFactory() { } public Logger makeNewLoggerInstance(String name) { return new Logger(name); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/LogMF.java0000755000175000017500000016755711751454711023314 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.spi.LoggingEvent; import java.text.DateFormat; import java.text.MessageFormat; import java.text.NumberFormat; import java.util.Date; import java.util.ResourceBundle; import java.util.Locale; /** * This class provides parameterized logging services * using the pattern syntax of java.text.MessageFormat. * Message formatting is only performed when the * request exceeds the threshold level of the logger. * When the pattern only contains literal text and * default conversion patterns (that is "{0}" and similar) * a simple fast compatible formatter is used. * If the pattern contains more complex conversion patterns, * formatting will be delegated to java.text.MessageFormatter * which can be substantially slower. * * @see org.apache.log4j.LogSF * @since 1.2.16 * */ public final class LogMF extends LogXF { /** * private constructor. * */ private LogMF() { } /** * Number format. */ private static NumberFormat numberFormat = null; /** * Locale at time of last number format request. */ private static Locale numberLocale = null; /** * Date format. */ private static DateFormat dateFormat = null; /** * Locale at time of last date format request. */ private static Locale dateLocale = null; /** * Format number. * @param n number to format, may not be null. * @return formatted value. */ private static synchronized String formatNumber(final Object n) { Locale currentLocale = Locale.getDefault(); if (currentLocale != numberLocale || numberFormat == null) { numberLocale = currentLocale; numberFormat = NumberFormat.getInstance(currentLocale); } return numberFormat.format(n); } /** * Format date. * @param d date, may not be null. * @return formatted value. */ private static synchronized String formatDate(final Object d) { Locale currentLocale = Locale.getDefault(); if (currentLocale != dateLocale || dateFormat == null) { dateLocale = currentLocale; dateFormat = DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.SHORT, currentLocale); } return dateFormat.format(d); } /** * Format a single parameter like a "{0}" formatting specifier. * * @param arg0 parameter, may be null. * @return string representation of arg0. */ private static String formatObject(final Object arg0) { if (arg0 instanceof String) { return arg0.toString(); } else if (arg0 instanceof Double || arg0 instanceof Float) { return formatNumber(arg0); } else if (arg0 instanceof Date) { return formatDate(arg0); } return String.valueOf(arg0); } /** * Determines if pattern contains only {n} format elements * and not apostrophes. * * @param pattern pattern, may not be null. * @return true if pattern only contains {n} format elements. */ private static boolean isSimple(final String pattern) { if (pattern.indexOf('\'') != -1) { return false; } for(int pos = pattern.indexOf('{'); pos != -1; pos = pattern.indexOf('{', pos + 1)) { if (pos + 2 >= pattern.length() || pattern.charAt(pos+2) != '}' || pattern.charAt(pos+1) < '0' || pattern.charAt(pos+1) > '9') { return false; } } return true; } /** * Formats arguments using MessageFormat. * @param pattern pattern, may be malformed or null. * @param arguments arguments, may be null or mismatched. * @return Message string or null */ private static String format(final String pattern, final Object[] arguments) { if (pattern == null) { return null; } else if(isSimple(pattern)) { String formatted[] = new String[10]; int prev = 0; String retval = ""; int pos = pattern.indexOf('{'); while(pos >= 0) { if(pos + 2 < pattern.length() && pattern.charAt(pos+2) == '}' && pattern.charAt(pos+1) >= '0' && pattern.charAt(pos+1) <= '9') { int index = pattern.charAt(pos+1) - '0'; retval += pattern.substring(prev, pos); if (formatted[index] == null) { if (arguments == null || index >= arguments.length) { formatted[index] = pattern.substring(pos, pos+3); } else { formatted[index] = formatObject(arguments[index]); } } retval += formatted[index]; prev = pos + 3; pos = pattern.indexOf('{', prev); } else { pos = pattern.indexOf('{', pos + 1); } } retval += pattern.substring(prev); return retval; } try { return MessageFormat.format(pattern, arguments); } catch (IllegalArgumentException ex) { return pattern; } } /** * Formats a single argument using MessageFormat. * @param pattern pattern, may be malformed or null. * @param arguments arguments, may be null or mismatched. * @return Message string or null */ private static String format(final String pattern, final Object arg0) { if (pattern == null) { return null; } else if(isSimple(pattern)) { String formatted = null; int prev = 0; String retval = ""; int pos = pattern.indexOf('{'); while(pos >= 0) { if(pos + 2 < pattern.length() && pattern.charAt(pos+2) == '}' && pattern.charAt(pos+1) >= '0' && pattern.charAt(pos+1) <= '9') { int index = pattern.charAt(pos+1) - '0'; retval += pattern.substring(prev, pos); if (index != 0) { retval += pattern.substring(pos, pos+3); } else { if (formatted == null) { formatted = formatObject(arg0); } retval += formatted; } prev = pos + 3; pos = pattern.indexOf('{', prev); } else { pos = pattern.indexOf('{', pos + 1); } } retval += pattern.substring(prev); return retval; } try { return MessageFormat.format(pattern, new Object[] { arg0 }); } catch (IllegalArgumentException ex) { return pattern; } } /** * Formats arguments using MessageFormat using a pattern from * a resource bundle. * @param resourceBundleName name of resource bundle, may be null. * @param key key for pattern in resource bundle, may be null. * @param arguments arguments, may be null or mismatched. * @return Message string or null */ private static String format( final String resourceBundleName, final String key, final Object[] arguments) { String pattern; if (resourceBundleName != null) { try { ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName); pattern = bundle.getString(key); } catch (Exception ex) { pattern = key; } } else { pattern = key; } return format(pattern, arguments); } /** * Fully Qualified Class Name of this class. */ private static final String FQCN = LogMF.class.getName(); /** * Equivalent of Logger.forcedLog. * * @param logger logger, may not be null. * @param level level, may not be null. * @param msg message, may be null. */ private static void forcedLog(final Logger logger, final Level level, final String msg) { logger.callAppenders(new LoggingEvent(FQCN, logger, level, msg, null)); } /** * Equivalent of Logger.forcedLog. * * @param logger logger, may not be null. * @param level level, may not be null. * @param msg message, may be null. * @param t throwable. */ private static void forcedLog(final Logger logger, final Level level, final String msg, final Throwable t) { logger.callAppenders(new LoggingEvent(FQCN, logger, level, msg, t)); } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be * formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final Object[] arguments) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, arguments)); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final Object[] arguments) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, arguments)); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final Object[] arguments) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, arguments)); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final Object[] arguments) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, arguments)); } } /** * Log a parameterized message at error level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void error(final Logger logger, final String pattern, final Object[] arguments) { if (logger.isEnabledFor(Level.ERROR)) { forcedLog(logger, Level.ERROR, format(pattern, arguments)); } } /** * Log a parameterized message at fatal level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void fatal(final Logger logger, final String pattern, final Object[] arguments) { if (logger.isEnabledFor(Level.FATAL)) { forcedLog(logger, Level.FATAL, format(pattern, arguments)); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param t throwable, may be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be * formatted and substituted. */ public static void trace(final Logger logger, final Throwable t, final String pattern, final Object[] arguments) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, arguments), t); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param t throwable, may be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void debug(final Logger logger, final Throwable t, final String pattern, final Object[] arguments) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, arguments), t); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param t throwable, may be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void info(final Logger logger, final Throwable t, final String pattern, final Object[] arguments) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, arguments), t); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param t throwable, may be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void warn(final Logger logger, final Throwable t, final String pattern, final Object[] arguments) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, arguments), t); } } /** * Log a parameterized message at error level. * @param logger logger, may not be null. * @param t throwable, may be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void error(final Logger logger, final Throwable t, final String pattern, final Object[] arguments) { if (logger.isEnabledFor(Level.ERROR)) { forcedLog(logger, Level.ERROR, format(pattern, arguments), t); } } /** * Log a parameterized message at fatal level. * @param logger logger, may not be null. * @param t throwable, may be null. * @param pattern pattern, may be null. * @param arguments an array of arguments to be formatted and substituted. */ public static void fatal(final Logger logger, final Throwable t, final String pattern, final Object[] arguments) { if (logger.isEnabledFor(Level.FATAL)) { forcedLog(logger, Level.FATAL, format(pattern, arguments), t); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final boolean argument) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final char argument) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final byte argument) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final short argument) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final int argument) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final long argument) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final float argument) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final double argument) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final Object argument) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, argument)); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final Object arg0, final Object arg1) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, toArray(arg0, arg1))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final Object arg0, final Object arg1, final Object arg2) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, toArray(arg0, arg1, arg2))); } } /** * Log a parameterized message at trace level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. * @param arg3 a value to be formatted and substituted. */ public static void trace(final Logger logger, final String pattern, final Object arg0, final Object arg1, final Object arg2, final Object arg3) { if (logger.isEnabledFor(TRACE)) { forcedLog(logger, TRACE, format(pattern, toArray(arg0, arg1, arg2, arg3))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final boolean argument) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final char argument) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final byte argument) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final short argument) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final int argument) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final long argument) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final float argument) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final double argument) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final Object argument) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, argument)); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final Object arg0, final Object arg1) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, toArray(arg0, arg1))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final Object arg0, final Object arg1, final Object arg2) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, toArray(arg0, arg1, arg2))); } } /** * Log a parameterized message at debug level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. * @param arg3 a value to be formatted and substituted. */ public static void debug(final Logger logger, final String pattern, final Object arg0, final Object arg1, final Object arg2, final Object arg3) { if (logger.isDebugEnabled()) { forcedLog(logger, Level.DEBUG, format(pattern, toArray(arg0, arg1, arg2, arg3))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final boolean argument) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final char argument) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final byte argument) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final short argument) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final int argument) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final long argument) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final float argument) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final double argument) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final Object argument) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, argument)); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final Object arg0, final Object arg1) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, toArray(arg0, arg1))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final Object arg0, final Object arg1, final Object arg2) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, toArray(arg0, arg1, arg2))); } } /** * Log a parameterized message at info level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. * @param arg3 a value to be formatted and substituted. */ public static void info(final Logger logger, final String pattern, final Object arg0, final Object arg1, final Object arg2, final Object arg3) { if (logger.isInfoEnabled()) { forcedLog(logger, Level.INFO, format(pattern, toArray(arg0, arg1, arg2, arg3))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final boolean argument) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final char argument) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final byte argument) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final short argument) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final int argument) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final long argument) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final float argument) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final double argument) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, valueOf(argument))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param argument a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final Object argument) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, argument)); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final Object arg0, final Object arg1) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, toArray(arg0, arg1))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final Object arg0, final Object arg1, final Object arg2) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, toArray(arg0, arg1, arg2))); } } /** * Log a parameterized message at warn level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. * @param arg3 a value to be formatted and substituted. */ public static void warn(final Logger logger, final String pattern, final Object arg0, final Object arg1, final Object arg2, final Object arg3) { if (logger.isEnabledFor(Level.WARN)) { forcedLog(logger, Level.WARN, format(pattern, toArray(arg0, arg1, arg2, arg3))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param parameters parameters to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final Object[] parameters) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, parameters)); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param t throwable, may be null. * @param pattern pattern, may be null. * @param parameters parameters to the log message. */ public static void log(final Logger logger, final Level level, final Throwable t, final String pattern, final Object[] parameters) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, parameters), t); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param param1 parameter to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final Object param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(param1))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param param1 parameter to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final boolean param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(valueOf(param1)))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param param1 parameter to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final byte param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(valueOf(param1)))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param param1 parameter to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final char param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(valueOf(param1)))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param param1 parameter to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final short param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(valueOf(param1)))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param param1 parameter to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final int param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(valueOf(param1)))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param param1 parameter to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final long param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(valueOf(param1)))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param param1 parameter to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final float param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(valueOf(param1)))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param param1 parameter to the log message. */ public static void log(final Logger logger, final Level level, final String pattern, final double param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(valueOf(param1)))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. */ public static void log(final Logger logger, final Level level, final String pattern, final Object arg0, final Object arg1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(arg0, arg1))); } } /** * Log a parameterized message at specifed level. * @param logger logger, may not be null. * @param level level, may not be null. * @param pattern pattern, may be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. */ public static void log(final Logger logger, final Level level, final String pattern, final Object arg0, final Object arg1, final Object arg2) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(arg0, arg1, arg2))); } } /** * Log a parameterized message at specified level. * @param logger logger, may not be null. * @param pattern pattern, may be null. * @param level level, may not be null. * @param arg0 a value to be formatted and substituted. * @param arg1 a value to be formatted and substituted. * @param arg2 a value to be formatted and substituted. * @param arg3 a value to be formatted and substituted. */ public static void log(final Logger logger, final Level level, final String pattern, final Object arg0, final Object arg1, final Object arg2, final Object arg3) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(pattern, toArray(arg0, arg1, arg2, arg3))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param parameters parameters to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final Object[] parameters) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, parameters)); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param t throwable, may be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param parameters parameters to the log message. */ public static void logrb(final Logger logger, final Level level, final Throwable t, final String bundleName, final String key, final Object[] parameters) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, parameters), t); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final Object param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(param1))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final boolean param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(valueOf(param1)))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final char param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(valueOf(param1)))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final byte param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(valueOf(param1)))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final short param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(valueOf(param1)))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final int param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(valueOf(param1)))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final long param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(valueOf(param1)))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final float param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(valueOf(param1)))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final double param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(valueOf(param1)))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param0 Parameter to the log message. * @param param1 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final Object param0, final Object param1) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(param0, param1))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param0 Parameter to the log message. * @param param1 Parameter to the log message. * @param param2 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final Object param0, final Object param1, final Object param2) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(param0, param1, param2))); } } /** * Log a parameterized message using a pattern from a resource bundle. * @param logger logger, may not be null. * @param level level, may not be null. * @param bundleName resource bundle name, may be null. * @param key key, may be null. * @param param0 Parameter to the log message. * @param param1 Parameter to the log message. * @param param2 Parameter to the log message. * @param param3 Parameter to the log message. */ public static void logrb(final Logger logger, final Level level, final String bundleName, final String key, final Object param0, final Object param1, final Object param2, final Object param3) { if (logger.isEnabledFor(level)) { forcedLog(logger, level, format(bundleName, key, toArray(param0, param1, param2, param3))); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/TTCCLayout.java0000644000175000017500000001505011751454711024254 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Contributors: Christopher Williams // Mathias Bogaert package org.apache.log4j; import org.apache.log4j.helpers.DateLayout; import org.apache.log4j.spi.LoggingEvent; /** TTCC layout format consists of time, thread, category and nested diagnostic context information, hence the name.

Each of the four fields can be individually enabled or disabled. The time format depends on the DateFormat used.

Here is an example TTCCLayout output with the {@link org.apache.log4j.helpers.RelativeTimeDateFormat}.

176 [main] INFO  org.apache.log4j.examples.Sort - Populating an array of 2 elements in reverse order.
225 [main] INFO  org.apache.log4j.examples.SortAlgo - Entered the sort method.
262 [main] DEBUG org.apache.log4j.examples.SortAlgo.OUTER i=1 - Outer loop.
276 [main] DEBUG org.apache.log4j.examples.SortAlgo.SWAP i=1 j=0 - Swapping intArray[0] = 1 and intArray[1] = 0
290 [main] DEBUG org.apache.log4j.examples.SortAlgo.OUTER i=0 - Outer loop.
304 [main] INFO  org.apache.log4j.examples.SortAlgo.DUMP - Dump of interger array:
317 [main] INFO  org.apache.log4j.examples.SortAlgo.DUMP - Element [0] = 0
331 [main] INFO  org.apache.log4j.examples.SortAlgo.DUMP - Element [1] = 1
343 [main] INFO  org.apache.log4j.examples.Sort - The next log statement should be an error message.
346 [main] ERROR org.apache.log4j.examples.SortAlgo.DUMP - Tried to dump an uninitialized array.
        at org.apache.log4j.examples.SortAlgo.dump(SortAlgo.java:58)
        at org.apache.log4j.examples.Sort.main(Sort.java:64)
467 [main] INFO  org.apache.log4j.examples.Sort - Exiting main method.

The first field is the number of milliseconds elapsed since the start of the program. The second field is the thread outputting the log statement. The third field is the level, the fourth field is the category to which the statement belongs.

The fifth field (just before the '-') is the nested diagnostic context. Note the nested diagnostic context may be empty as in the first two statements. The text after the '-' is the message of the statement.

WARNING Do not use the same TTCCLayout instance from within different appenders. The TTCCLayout is not thread safe when used in his way. However, it is perfectly safe to use a TTCCLayout instance from just one appender.

{@link PatternLayout} offers a much more flexible alternative. @author Ceki Gülcü @author Heinz Richter */ public class TTCCLayout extends DateLayout { // Internal representation of options private boolean threadPrinting = true; private boolean categoryPrefixing = true; private boolean contextPrinting = true; protected final StringBuffer buf = new StringBuffer(256); /** Instantiate a TTCCLayout object with {@link org.apache.log4j.helpers.RelativeTimeDateFormat} as the date formatter in the local time zone. @since 0.7.5 */ public TTCCLayout() { this.setDateFormat(RELATIVE_TIME_DATE_FORMAT, null); } /** Instantiate a TTCCLayout object using the local time zone. The DateFormat used will depend on the dateFormatType.

This constructor just calls the {@link DateLayout#setDateFormat} method. */ public TTCCLayout(String dateFormatType) { this.setDateFormat(dateFormatType); } /** The ThreadPrinting option specifies whether the name of the current thread is part of log output or not. This is true by default. */ public void setThreadPrinting(boolean threadPrinting) { this.threadPrinting = threadPrinting; } /** Returns value of the ThreadPrinting option. */ public boolean getThreadPrinting() { return threadPrinting; } /** The CategoryPrefixing option specifies whether {@link Category} name is part of log output or not. This is true by default. */ public void setCategoryPrefixing(boolean categoryPrefixing) { this.categoryPrefixing = categoryPrefixing; } /** Returns value of the CategoryPrefixing option. */ public boolean getCategoryPrefixing() { return categoryPrefixing; } /** The ContextPrinting option specifies log output will include the nested context information belonging to the current thread. This is true by default. */ public void setContextPrinting(boolean contextPrinting) { this.contextPrinting = contextPrinting; } /** Returns value of the ContextPrinting option. */ public boolean getContextPrinting() { return contextPrinting; } /** In addition to the level of the statement and message, the returned byte array includes time, thread, category and {@link NDC} information.

Time, thread, category and diagnostic context are printed depending on options. @param event The event to format */ public String format(LoggingEvent event) { // Reset buf buf.setLength(0); dateFormat(buf, event); if(this.threadPrinting) { buf.append('['); buf.append(event.getThreadName()); buf.append("] "); } buf.append(event.getLevel().toString()); buf.append(' '); if(this.categoryPrefixing) { buf.append(event.getLoggerName()); buf.append(' '); } 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); return buf.toString(); } /** The TTCCLayout does not handle the throwable contained within {@link LoggingEvent LoggingEvents}. Thus, it returns true. @since version 0.8.4 */ public boolean ignoresThrowable() { return true; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/LogXF.java0000644000175000017500000002714311751454711023306 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.spi.LoggingEvent; /** * This is a base class for LogMF and LogSF parameterized logging classes. * * * @see org.apache.log4j.LogMF * @see org.apache.log4j.LogSF * @since 1.2.16 */ public abstract class LogXF { /** * Trace level. */ protected static final Level TRACE = new Level(5000, "TRACE", 7); /** * Fully Qualified Class Name of this class. */ private static final String FQCN = LogXF.class.getName(); protected LogXF() { } /** * Returns a Boolean instance representing the specified boolean. * Boolean.valueOf was added in JDK 1.4. * * @param b a boolean value. * @return a Boolean instance representing b. */ protected static Boolean valueOf(final boolean b) { if (b) { return Boolean.TRUE; } return Boolean.FALSE; } /** * Returns a Character instance representing the specified char. * Character.valueOf was added in JDK 1.5. * * @param c a character value. * @return a Character instance representing c. */ protected static Character valueOf(final char c) { return new Character(c); } /** * Returns a Byte instance representing the specified byte. * Byte.valueOf was added in JDK 1.5. * * @param b a byte value. * @return a Byte instance representing b. */ protected static Byte valueOf(final byte b) { return new Byte(b); } /** * Returns a Short instance representing the specified short. * Short.valueOf was added in JDK 1.5. * * @param b a short value. * @return a Byte instance representing b. */ protected static Short valueOf(final short b) { return new Short(b); } /** * Returns an Integer instance representing the specified int. * Integer.valueOf was added in JDK 1.5. * * @param b an int value. * @return an Integer instance representing b. */ protected static Integer valueOf(final int b) { return new Integer(b); } /** * Returns a Long instance representing the specified long. * Long.valueOf was added in JDK 1.5. * * @param b a long value. * @return a Long instance representing b. */ protected static Long valueOf(final long b) { return new Long(b); } /** * Returns a Float instance representing the specified float. * Float.valueOf was added in JDK 1.5. * * @param b a float value. * @return a Float instance representing b. */ protected static Float valueOf(final float b) { return new Float(b); } /** * Returns a Double instance representing the specified double. * Double.valueOf was added in JDK 1.5. * * @param b a double value. * @return a Byte instance representing b. */ protected static Double valueOf(final double b) { return new Double(b); } /** * Create new array. * * @param param1 parameter 1. * @return new array. */ protected static Object[] toArray(final Object param1) { return new Object[]{ param1 }; } /** * Create new array. * * @param param1 parameter 1. * @param param2 parameter 2. * @return new array. */ protected static Object[] toArray(final Object param1, final Object param2) { return new Object[]{ param1, param2 }; } /** * Create new array. * * @param param1 parameter 1. * @param param2 parameter 2. * @param param3 parameter 3. * @return new array. */ protected static Object[] toArray(final Object param1, final Object param2, final Object param3) { return new Object[]{ param1, param2, param3 }; } /** * Create new array. * * @param param1 parameter 1. * @param param2 parameter 2. * @param param3 parameter 3. * @param param4 parameter 4. * @return new array. */ protected static Object[] toArray(final Object param1, final Object param2, final Object param3, final Object param4) { return new Object[]{ param1, param2, param3, param4 }; } /** * Log an entering message at DEBUG level. * * @param logger logger, may not be null. * @param sourceClass source class, may be null. * @param sourceMethod method, may be null. */ public static void entering(final Logger logger, final String sourceClass, final String sourceMethod) { if (logger.isDebugEnabled()) { logger.callAppenders(new LoggingEvent(FQCN, logger, Level.DEBUG, sourceClass + "." + sourceMethod + " ENTRY", null)); } } /** * Log an entering message with a parameter at DEBUG level. * * @param logger logger, may not be null. * @param sourceClass source class, may be null. * @param sourceMethod method, may be null. * @param param parameter, may be null. */ public static void entering(final Logger logger, final String sourceClass, final String sourceMethod, final String param) { if (logger.isDebugEnabled()) { String msg = sourceClass + "." + sourceMethod + " ENTRY " + param; logger.callAppenders(new LoggingEvent(FQCN, logger, Level.DEBUG, msg, null)); } } /** * Log an entering message with a parameter at DEBUG level. * * @param logger logger, may not be null. * @param sourceClass source class, may be null. * @param sourceMethod method, may be null. * @param param parameter, may be null. */ public static void entering(final Logger logger, final String sourceClass, final String sourceMethod, final Object param) { if (logger.isDebugEnabled()) { String msg = sourceClass + "." + sourceMethod + " ENTRY "; if (param == null) { msg += "null"; } else { try { msg += param; } catch(Throwable ex) { msg += "?"; } } logger.callAppenders(new LoggingEvent(FQCN, logger, Level.DEBUG, msg, null)); } } /** * Log an entering message with an array of parameters at DEBUG level. * * @param logger logger, may not be null. * @param sourceClass source class, may be null. * @param sourceMethod method, may be null. * @param params parameters, may be null. */ public static void entering(final Logger logger, final String sourceClass, final String sourceMethod, final Object[] params) { if (logger.isDebugEnabled()) { String msg = sourceClass + "." + sourceMethod + " ENTRY "; if (params != null && params.length > 0) { String delim = "{"; for (int i = 0; i < params.length; i++) { try { msg += delim + params[i]; } catch(Throwable ex) { msg += delim + "?"; } delim = ","; } msg += "}"; } else { msg += "{}"; } logger.callAppenders(new LoggingEvent(FQCN, logger, Level.DEBUG, msg, null)); } } /** * Log an exiting message at DEBUG level. * * @param logger logger, may not be null. * @param sourceClass source class, may be null. * @param sourceMethod method, may be null. */ public static void exiting(final Logger logger, final String sourceClass, final String sourceMethod) { if (logger.isDebugEnabled()) { logger.callAppenders(new LoggingEvent(FQCN, logger, Level.DEBUG, sourceClass + "." + sourceMethod + " RETURN", null)); } } /** * Log an exiting message with result at DEBUG level. * * @param logger logger, may not be null. * @param sourceClass source class, may be null. * @param sourceMethod method, may be null. * @param result result, may be null. */ public static void exiting( final Logger logger, final String sourceClass, final String sourceMethod, final String result) { if (logger.isDebugEnabled()) { logger.callAppenders(new LoggingEvent(FQCN, logger, Level.DEBUG, sourceClass + "." + sourceMethod + " RETURN " + result, null)); } } /** * Log an exiting message with result at DEBUG level. * * @param logger logger, may not be null. * @param sourceClass source class, may be null. * @param sourceMethod method, may be null. * @param result result, may be null. */ public static void exiting( final Logger logger, final String sourceClass, final String sourceMethod, final Object result) { if (logger.isDebugEnabled()) { String msg = sourceClass + "." + sourceMethod + " RETURN "; if (result == null) { msg += "null"; } else { try { msg += result; } catch(Throwable ex) { msg += "?"; } } logger.callAppenders(new LoggingEvent(FQCN, logger, Level.DEBUG, msg, null)); } } /** * Logs a throwing message at DEBUG level. * * @param logger logger, may not be null. * @param sourceClass source class, may be null. * @param sourceMethod method, may be null. * @param thrown throwable, may be null. */ public static void throwing( final Logger logger, final String sourceClass, final String sourceMethod, final Throwable thrown) { if (logger.isDebugEnabled()) { logger.callAppenders(new LoggingEvent(FQCN, logger, Level.DEBUG, sourceClass + "." + sourceMethod + " THROW", thrown)); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/LogManager.java0000644000175000017500000002221411751454711024335 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.LoggerFactory; import org.apache.log4j.spi.RepositorySelector; import org.apache.log4j.spi.DefaultRepositorySelector; import org.apache.log4j.spi.RootLogger; import org.apache.log4j.spi.NOPLoggerRepository; import org.apache.log4j.helpers.Loader; import org.apache.log4j.helpers.OptionConverter; import org.apache.log4j.helpers.LogLog; import java.net.URL; import java.net.MalformedURLException; import java.util.Enumeration; import java.io.StringWriter; import java.io.PrintWriter; /** * Use the LogManager class to retreive {@link Logger} * instances or to operate on the current {@link * LoggerRepository}. When the LogManager class is loaded * into memory the default initalzation procedure is inititated. The * default intialization procedure is described in the short log4j manual. * * @author Ceki Gülcü */ public class LogManager { /** * @deprecated This variable is for internal use only. It will * become package protected in future versions. * */ static public final String DEFAULT_CONFIGURATION_FILE = "log4j.properties"; static final String DEFAULT_XML_CONFIGURATION_FILE = "log4j.xml"; /** * @deprecated This variable is for internal use only. It will * become private in future versions. * */ static final public String DEFAULT_CONFIGURATION_KEY="log4j.configuration"; /** * @deprecated This variable is for internal use only. It will * become private in future versions. * */ static final public String CONFIGURATOR_CLASS_KEY="log4j.configuratorClass"; /** * @deprecated This variable is for internal use only. It will * become private in future versions. */ public static final String DEFAULT_INIT_OVERRIDE_KEY = "log4j.defaultInitOverride"; static private Object guard = null; static private RepositorySelector repositorySelector; static { // By default we use a DefaultRepositorySelector which always returns 'h'. Hierarchy h = new Hierarchy(new RootLogger((Level) Level.DEBUG)); repositorySelector = new DefaultRepositorySelector(h); /** Search for the properties file log4j.properties in the CLASSPATH. */ String override =OptionConverter.getSystemProperty(DEFAULT_INIT_OVERRIDE_KEY, null); // if there is no default init override, then get the resource // specified by the user or the default config file. if(override == null || "false".equalsIgnoreCase(override)) { String configurationOptionStr = OptionConverter.getSystemProperty( DEFAULT_CONFIGURATION_KEY, null); String configuratorClassName = OptionConverter.getSystemProperty( CONFIGURATOR_CLASS_KEY, null); URL url = null; // if the user has not specified the log4j.configuration // property, we search first for the file "log4j.xml" and then // "log4j.properties" if(configurationOptionStr == null) { url = Loader.getResource(DEFAULT_XML_CONFIGURATION_FILE); if(url == null) { url = Loader.getResource(DEFAULT_CONFIGURATION_FILE); } } else { try { url = new URL(configurationOptionStr); } catch (MalformedURLException ex) { // so, resource is not a URL: // attempt to get the resource from the class path url = Loader.getResource(configurationOptionStr); } } // If we have a non-null url, then delegate the rest of the // configuration to the OptionConverter.selectAndConfigure // method. if(url != null) { LogLog.debug("Using URL ["+url+"] for automatic log4j configuration."); try { OptionConverter.selectAndConfigure(url, configuratorClassName, LogManager.getLoggerRepository()); } catch (NoClassDefFoundError e) { LogLog.warn("Error during default initialization", e); } } else { LogLog.debug("Could not find resource: ["+configurationOptionStr+"]."); } } else { LogLog.debug("Default initialization of overridden by " + DEFAULT_INIT_OVERRIDE_KEY + "property."); } } /** Sets LoggerFactory but only if the correct guard is passed as parameter.

Initally the guard is null. If the guard is null, then invoking this method sets the logger factory and the guard. Following invocations will throw a {@link IllegalArgumentException}, unless the previously set guard is passed as the second parameter.

This allows a high-level component to set the {@link RepositorySelector} used by the LogManager.

For example, when tomcat starts it will be able to install its own repository selector. However, if and when Tomcat is embedded within JBoss, then JBoss will install its own repository selector and Tomcat will use the repository selector set by its container, JBoss. */ static public void setRepositorySelector(RepositorySelector selector, Object guard) throws IllegalArgumentException { if((LogManager.guard != null) && (LogManager.guard != guard)) { throw new IllegalArgumentException( "Attempted to reset the LoggerFactory without possessing the guard."); } if(selector == null) { throw new IllegalArgumentException("RepositorySelector must be non-null."); } LogManager.guard = guard; LogManager.repositorySelector = selector; } /** * This method tests if called from a method that * is known to result in class members being abnormally * set to null but is assumed to be harmless since the * all classes are in the process of being unloaded. * * @param ex exception used to determine calling stack. * @return true if calling stack is recognized as likely safe. */ private static boolean isLikelySafeScenario(final Exception ex) { StringWriter stringWriter = new StringWriter(); ex.printStackTrace(new PrintWriter(stringWriter)); String msg = stringWriter.toString(); return msg.indexOf("org.apache.catalina.loader.WebappClassLoader.stop") != -1; } static public LoggerRepository getLoggerRepository() { if (repositorySelector == null) { repositorySelector = new DefaultRepositorySelector(new NOPLoggerRepository()); guard = null; Exception ex = new IllegalStateException("Class invariant violation"); String msg = "log4j called after unloading, see http://logging.apache.org/log4j/1.2/faq.html#unload."; if (isLikelySafeScenario(ex)) { LogLog.debug(msg, ex); } else { LogLog.error(msg, ex); } } return repositorySelector.getLoggerRepository(); } /** Retrieve the appropriate root logger. */ public static Logger getRootLogger() { // Delegate the actual manufacturing of the logger to the logger repository. return getLoggerRepository().getRootLogger(); } /** Retrieve the appropriate {@link Logger} instance. */ public static Logger getLogger(final String name) { // Delegate the actual manufacturing of the logger to the logger repository. return getLoggerRepository().getLogger(name); } /** Retrieve the appropriate {@link Logger} instance. */ public static Logger getLogger(final Class clazz) { // Delegate the actual manufacturing of the logger to the logger repository. return getLoggerRepository().getLogger(clazz.getName()); } /** Retrieve the appropriate {@link Logger} instance. */ public static Logger getLogger(final String name, final LoggerFactory factory) { // Delegate the actual manufacturing of the logger to the logger repository. return getLoggerRepository().getLogger(name, factory); } public static Logger exists(final String name) { return getLoggerRepository().exists(name); } public static Enumeration getCurrentLoggers() { return getLoggerRepository().getCurrentLoggers(); } public static void shutdown() { getLoggerRepository().shutdown(); } public static void resetConfiguration() { getLoggerRepository().resetConfiguration(); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/ProvisionNode.java0000644000175000017500000000203011751454711025111 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import java.util.Vector; class ProvisionNode extends Vector { private static final long serialVersionUID = -4479121426311014469L; ProvisionNode(Logger logger) { super(); this.addElement(logger); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/SimpleLayout.java0000644000175000017500000000420011751454711024743 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.spi.LoggingEvent; /** SimpleLayout consists of the level of the log statement, followed by " - " and then the log message itself. For example,

           DEBUG - Hello world
   

@author Ceki Gülcü @since version 0.7.0

{@link PatternLayout} offers a much more powerful alternative. */ public class SimpleLayout extends Layout { StringBuffer sbuf = new StringBuffer(128); public SimpleLayout() { } public void activateOptions() { } /** Returns the log statement in a format consisting of the level, followed by " - " and then the message. For example,

 INFO - "A message"
     

The category parameter is ignored.

@return A byte array in SimpleLayout format. */ public String format(LoggingEvent event) { sbuf.setLength(0); sbuf.append(event.getLevel().toString()); sbuf.append(" - "); sbuf.append(event.getRenderedMessage()); sbuf.append(LINE_SEP); return sbuf.toString(); } /** The SimpleLayout does not handle the throwable contained within {@link LoggingEvent LoggingEvents}. Thus, it returns true. @since version 0.8.4 */ public boolean ignoresThrowable() { return true; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/Appender.java0000644000175000017500000000707711751454711024071 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.ErrorHandler; import org.apache.log4j.spi.LoggingEvent; /** Implement this interface for your own strategies for outputting log statements. @author Ceki Gülcü */ public interface Appender { /** Add a filter to the end of the filter list. @since 0.9.0 */ void addFilter(Filter newFilter); /** Returns the head Filter. The Filters are organized in a linked list and so all Filters on this Appender are available through the result. @return the head Filter or null, if no Filters are present @since 1.1 */ public Filter getFilter(); /** Clear the list of filters by removing all the filters in it. @since 0.9.0 */ public void clearFilters(); /** Release any resources allocated within the appender such as file handles, network connections, etc.

It is a programming error to append to a closed appender. @since 0.8.4 */ public void close(); /** Log in Appender specific way. When appropriate, Loggers will call the doAppend method of appender implementations in order to log. */ public void doAppend(LoggingEvent event); /** Get the name of this appender. @return name, may be null.*/ public String getName(); /** Set the {@link ErrorHandler} for this appender. @since 0.9.0 */ public void setErrorHandler(ErrorHandler errorHandler); /** Returns the {@link ErrorHandler} for this appender. @since 1.1 */ public ErrorHandler getErrorHandler(); /** Set the {@link Layout} for this appender. @since 0.8.1 */ public void setLayout(Layout layout); /** Returns this appenders layout. @since 1.1 */ public Layout getLayout(); /** Set the name of this appender. The name is used by other components to identify this appender. @since 0.8.1 */ public void setName(String name); /** Configurators call this method to determine if the appender requires a layout. If this method returns true, meaning that layout is required, then the configurator will configure an layout using the configuration information at its disposal. If this method returns false, meaning that a layout is not required, then layout configuration will be skipped even if there is available layout configuration information at the disposal of the configurator..

In the rather exceptional case, where the appender implementation admits a layout but can also work without it, then the appender should return true. @since 0.8.4 */ public boolean requiresLayout(); } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/jdbc/0000755000175000017500000000000012126647422022357 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/jdbc/package.html0000644000175000017500000000156111751454706024647 0ustar tonytony The JDBCAppender provides for sending log events to a database. apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/jdbc/JDBCAppender.java0000644000175000017500000002472411751454706025420 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Iterator; import org.apache.log4j.PatternLayout; import org.apache.log4j.spi.ErrorCode; import org.apache.log4j.spi.LoggingEvent; /** The JDBCAppender provides for sending log events to a database.

WARNING: This version of JDBCAppender is very likely to be completely replaced in the future. Moreoever, it does not log exceptions.

Each append call adds to an ArrayList buffer. When the buffer is filled each log event is placed in a sql statement (configurable) and executed. BufferSize, db URL, User, & Password are configurable options in the standard log4j ways.

The setSql(String sql) sets the SQL statement to be used for logging -- this statement is sent to a PatternLayout (either created automaticly by the appender or added by the user). Therefore by default all the conversion patterns in PatternLayout can be used inside of the statement. (see the test cases for examples)

Overriding the {@link #getLogStatement} method allows more explicit control of the statement used for logging.

For use as a base class:

  • Override getConnection() to pass any connection you want. Typically this is used to enable application wide connection pooling.
  • Override closeConnection(Connection con) -- if you override getConnection make sure to implement closeConnection to handle the connection you generated. Typically this would return the connection to the pool it came from.
  • Override getLogStatement(LoggingEvent event) to produce specialized or dynamic statements. The default uses the sql option value.
@author Kevin Steppe (ksteppe@pacbell.net) */ public class JDBCAppender extends org.apache.log4j.AppenderSkeleton implements org.apache.log4j.Appender { /** * URL of the DB for default connection handling */ protected String databaseURL = "jdbc:odbc:myDB"; /** * User to connect as for default connection handling */ protected String databaseUser = "me"; /** * User to use for default connection handling */ protected String databasePassword = "mypassword"; /** * Connection used by default. The connection is opened the first time it * is needed and then held open until the appender is closed (usually at * garbage collection). This behavior is best modified by creating a * sub-class and overriding the getConnection and * closeConnection methods. */ protected Connection connection = null; /** * Stores the string given to the pattern layout for conversion into a SQL * statement, eg: insert into LogTable (Thread, Class, Message) values * ("%t", "%c", "%m"). * * Be careful of quotes in your messages! * * Also see PatternLayout. */ protected String sqlStatement = ""; /** * size of LoggingEvent buffer before writting to the database. * Default is 1. */ protected int bufferSize = 1; /** * ArrayList holding the buffer of Logging Events. */ protected ArrayList buffer; /** * Helper object for clearing out the buffer */ protected ArrayList removes; private boolean locationInfo = false; public JDBCAppender() { super(); buffer = new ArrayList(bufferSize); removes = new ArrayList(bufferSize); } /** * Gets whether the location of the logging request call * should be captured. * * @since 1.2.16 * @return the current value of the LocationInfo option. */ public boolean getLocationInfo() { return locationInfo; } /** * The LocationInfo option takes a boolean value. By default, it is * set to false which means there will be no effort to extract the location * information related to the event. As a result, the event that will be * ultimately logged will likely to contain the wrong location information * (if present in the log format). *

*

* Location information extraction is comparatively very slow and should be * avoided unless performance is not a concern. *

* @since 1.2.16 * @param flag true if location information should be extracted. */ public void setLocationInfo(final boolean flag) { locationInfo = flag; } /** * Adds the event to the buffer. When full the buffer is flushed. */ public void append(LoggingEvent event) { event.getNDC(); event.getThreadName(); // Get a copy of this thread's MDC. event.getMDCCopy(); if (locationInfo) { event.getLocationInformation(); } event.getRenderedMessage(); event.getThrowableStrRep(); buffer.add(event); if (buffer.size() >= bufferSize) flushBuffer(); } /** * By default getLogStatement sends the event to the required Layout object. * The layout will format the given pattern into a workable SQL string. * * Overriding this provides direct access to the LoggingEvent * when constructing the logging statement. * */ protected String getLogStatement(LoggingEvent event) { return getLayout().format(event); } /** * * Override this to provide an alertnate method of getting * connections (such as caching). One method to fix this is to open * connections at the start of flushBuffer() and close them at the * end. I use a connection pool outside of JDBCAppender which is * accessed in an override of this method. * */ protected void execute(String sql) throws SQLException { Connection con = null; Statement stmt = null; try { con = getConnection(); stmt = con.createStatement(); stmt.executeUpdate(sql); } finally { if(stmt != null) { stmt.close(); } closeConnection(con); } //System.out.println("Execute: " + sql); } /** * Override this to return the connection to a pool, or to clean up the * resource. * * The default behavior holds a single connection open until the appender * is closed (typically when garbage collected). */ protected void closeConnection(Connection con) { } /** * Override this to link with your connection pooling system. * * By default this creates a single connection which is held open * until the object is garbage collected. */ protected Connection getConnection() throws SQLException { if (!DriverManager.getDrivers().hasMoreElements()) setDriver("sun.jdbc.odbc.JdbcOdbcDriver"); if (connection == null) { connection = DriverManager.getConnection(databaseURL, databaseUser, databasePassword); } return connection; } /** * Closes the appender, flushing the buffer first then closing the default * connection if it is open. */ public void close() { flushBuffer(); try { if (connection != null && !connection.isClosed()) connection.close(); } catch (SQLException e) { errorHandler.error("Error closing connection", e, ErrorCode.GENERIC_FAILURE); } this.closed = true; } /** * loops through the buffer of LoggingEvents, gets a * sql string from getLogStatement() and sends it to execute(). * Errors are sent to the errorHandler. * * If a statement fails the LoggingEvent stays in the buffer! */ public void flushBuffer() { //Do the actual logging removes.ensureCapacity(buffer.size()); for (Iterator i = buffer.iterator(); i.hasNext();) { LoggingEvent logEvent = (LoggingEvent)i.next(); try { String sql = getLogStatement(logEvent); execute(sql); } catch (SQLException e) { errorHandler.error("Failed to excute sql", e, ErrorCode.FLUSH_FAILURE); } finally { removes.add(logEvent); } } // remove from the buffer any events that were reported buffer.removeAll(removes); // clear the buffer of reported events removes.clear(); } /** closes the appender before disposal */ public void finalize() { close(); } /** * JDBCAppender requires a layout. * */ public boolean requiresLayout() { return true; } /** * */ public void setSql(String s) { sqlStatement = s; if (getLayout() == null) { this.setLayout(new PatternLayout(s)); } else { ((PatternLayout)getLayout()).setConversionPattern(s); } } /** * Returns pre-formated statement eg: insert into LogTable (msg) values ("%m") */ public String getSql() { return sqlStatement; } public void setUser(String user) { databaseUser = user; } public void setURL(String url) { databaseURL = url; } public void setPassword(String password) { databasePassword = password; } public void setBufferSize(int newBufferSize) { bufferSize = newBufferSize; buffer.ensureCapacity(bufferSize); removes.ensureCapacity(bufferSize); } public String getUser() { return databaseUser; } public String getURL() { return databaseURL; } public String getPassword() { return databasePassword; } public int getBufferSize() { return bufferSize; } /** * Ensures that the given driver class has been loaded for sql connection * creation. */ public void setDriver(String driverClass) { try { Class.forName(driverClass); } catch (Exception e) { errorHandler.error("Failed to load driver", e, ErrorCode.GENERIC_FAILURE); } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/DailyRollingFileAppender.java0000644000175000017500000003415411751454711027177 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import java.io.IOException; import java.io.File; import java.io.InterruptedIOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.GregorianCalendar; import java.util.Calendar; import java.util.TimeZone; import java.util.Locale; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.spi.LoggingEvent; /** DailyRollingFileAppender extends {@link FileAppender} so that the underlying file is rolled over at a user chosen frequency. DailyRollingFileAppender has been observed to exhibit synchronization issues and data loss. The log4j extras companion includes alternatives which should be considered for new deployments and which are discussed in the documentation for org.apache.log4j.rolling.RollingFileAppender.

The rolling schedule is specified by the DatePattern option. This pattern should follow the {@link SimpleDateFormat} conventions. In particular, you must escape literal text within a pair of single quotes. A formatted version of the date pattern is used as the suffix for the rolled file name.

For example, if the File option is set to /foo/bar.log and the DatePattern set to '.'yyyy-MM-dd, on 2001-02-16 at midnight, the logging file /foo/bar.log will be copied to /foo/bar.log.2001-02-16 and logging for 2001-02-17 will continue in /foo/bar.log until it rolls over the next day.

Is is possible to specify monthly, weekly, half-daily, daily, hourly, or minutely rollover schedules.

DatePattern Rollover schedule Example
'.'yyyy-MM Rollover at the beginning of each month At midnight of May 31st, 2002 /foo/bar.log will be copied to /foo/bar.log.2002-05. Logging for the month of June will be output to /foo/bar.log until it is also rolled over the next month.
'.'yyyy-ww Rollover at the first day of each week. The first day of the week depends on the locale. Assuming the first day of the week is Sunday, on Saturday midnight, June 9th 2002, the file /foo/bar.log will be copied to /foo/bar.log.2002-23. Logging for the 24th week of 2002 will be output to /foo/bar.log until it is rolled over the next week.
'.'yyyy-MM-dd Rollover at midnight each day. At midnight, on March 8th, 2002, /foo/bar.log will be copied to /foo/bar.log.2002-03-08. Logging for the 9th day of March will be output to /foo/bar.log until it is rolled over the next day.
'.'yyyy-MM-dd-a Rollover at midnight and midday of each day. At noon, on March 9th, 2002, /foo/bar.log will be copied to /foo/bar.log.2002-03-09-AM. Logging for the afternoon of the 9th will be output to /foo/bar.log until it is rolled over at midnight.
'.'yyyy-MM-dd-HH Rollover at the top of every hour. At approximately 11:00.000 o'clock on March 9th, 2002, /foo/bar.log will be copied to /foo/bar.log.2002-03-09-10. Logging for the 11th hour of the 9th of March will be output to /foo/bar.log until it is rolled over at the beginning of the next hour.
'.'yyyy-MM-dd-HH-mm Rollover at the beginning of every minute. At approximately 11:23,000, on March 9th, 2001, /foo/bar.log will be copied to /foo/bar.log.2001-03-09-10-22. Logging for the minute of 11:23 (9th of March) will be output to /foo/bar.log until it is rolled over the next minute.

Do not use the colon ":" character in anywhere in the DatePattern option. The text before the colon is interpeted as the protocol specificaion of a URL which is probably not what you want. @author Eirik Lygre @author Ceki Gülcü*/ public class DailyRollingFileAppender extends FileAppender { // The code assumes that the following constants are in a increasing // sequence. static final int TOP_OF_TROUBLE=-1; static final int TOP_OF_MINUTE = 0; static final int TOP_OF_HOUR = 1; static final int HALF_DAY = 2; static final int TOP_OF_DAY = 3; static final int TOP_OF_WEEK = 4; static final int TOP_OF_MONTH = 5; /** The date pattern. By default, the pattern is set to "'.'yyyy-MM-dd" meaning daily rollover. */ private String datePattern = "'.'yyyy-MM-dd"; /** The log file will be renamed to the value of the scheduledFilename variable when the next interval is entered. For example, if the rollover period is one hour, the log file will be renamed to the value of "scheduledFilename" at the beginning of the next hour. The precise time when a rollover occurs depends on logging activity. */ private String scheduledFilename; /** The next time we estimate a rollover should occur. */ private long nextCheck = System.currentTimeMillis () - 1; Date now = new Date(); SimpleDateFormat sdf; RollingCalendar rc = new RollingCalendar(); int checkPeriod = TOP_OF_TROUBLE; // The gmtTimeZone is used only in computeCheckPeriod() method. static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT"); /** The default constructor does nothing. */ public DailyRollingFileAppender() { } /** Instantiate a DailyRollingFileAppender and open the file designated by filename. The opened filename will become the ouput destination for this appender. */ public DailyRollingFileAppender (Layout layout, String filename, String datePattern) throws IOException { super(layout, filename, true); this.datePattern = datePattern; activateOptions(); } /** The DatePattern takes a string in the same format as expected by {@link SimpleDateFormat}. This options determines the rollover schedule. */ public void setDatePattern(String pattern) { datePattern = pattern; } /** Returns the value of the DatePattern option. */ public String getDatePattern() { return datePattern; } public void activateOptions() { super.activateOptions(); if(datePattern != null && fileName != null) { now.setTime(System.currentTimeMillis()); sdf = new SimpleDateFormat(datePattern); int type = computeCheckPeriod(); printPeriodicity(type); rc.setType(type); File file = new File(fileName); scheduledFilename = fileName+sdf.format(new Date(file.lastModified())); } else { LogLog.error("Either File or DatePattern options are not set for appender [" +name+"]."); } } void printPeriodicity(int type) { switch(type) { case TOP_OF_MINUTE: LogLog.debug("Appender ["+name+"] to be rolled every minute."); break; case TOP_OF_HOUR: LogLog.debug("Appender ["+name +"] to be rolled on top of every hour."); break; case HALF_DAY: LogLog.debug("Appender ["+name +"] to be rolled at midday and midnight."); break; case TOP_OF_DAY: LogLog.debug("Appender ["+name +"] to be rolled at midnight."); break; case TOP_OF_WEEK: LogLog.debug("Appender ["+name +"] to be rolled at start of week."); break; case TOP_OF_MONTH: LogLog.debug("Appender ["+name +"] to be rolled at start of every month."); 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 // the datePattern (supplied by the user) and r1 is the // epoch+nextMillis(i) formatted according to datePattern. All date // formatting is done in GMT and not local format because the test // logic is based on comparisons relative to 1970-01-01 00:00:00 // GMT (the epoch). int computeCheckPeriod() { RollingCalendar rollingCalendar = new RollingCalendar(gmtTimeZone, Locale.getDefault()); // set sate to 1970-01-01 00:00:00 GMT Date epoch = new Date(0); if(datePattern != null) { for(int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern); simpleDateFormat.setTimeZone(gmtTimeZone); // do all date formatting in GMT String r0 = simpleDateFormat.format(epoch); rollingCalendar.setType(i); Date next = new Date(rollingCalendar.getNextCheckMillis(epoch)); String r1 = simpleDateFormat.format(next); //System.out.println("Type = "+i+", r0 = "+r0+", r1 = "+r1); if(r0 != null && r1 != null && !r0.equals(r1)) { return i; } } } return TOP_OF_TROUBLE; // Deliberately head for trouble... } /** Rollover the current file to a new file. */ void rollOver() throws IOException { /* Compute filename, but only if datePattern is specified */ if (datePattern == null) { errorHandler.error("Missing DatePattern option in rollOver()."); return; } String datedFilename = fileName+sdf.format(now); // It is too early to roll over because we are still within the // bounds of the current interval. Rollover will occur once the // next interval is reached. if (scheduledFilename.equals(datedFilename)) { return; } // close current file, and rename it to datedFilename this.closeFile(); File target = new File(scheduledFilename); if (target.exists()) { target.delete(); } File file = new File(fileName); boolean result = file.renameTo(target); if(result) { LogLog.debug(fileName +" -> "+ scheduledFilename); } else { LogLog.error("Failed to rename ["+fileName+"] to ["+scheduledFilename+"]."); } try { // This will also close the file. This is OK since multiple // close operations are safe. this.setFile(fileName, true, this.bufferedIO, this.bufferSize); } catch(IOException e) { errorHandler.error("setFile("+fileName+", true) call failed."); } scheduledFilename = datedFilename; } /** * This method differentiates DailyRollingFileAppender from its * super class. * *

Before actually logging, this method will check whether it is * time to do a rollover. If it is, it will schedule the next * rollover time and then rollover. * */ protected void subAppend(LoggingEvent event) { long n = System.currentTimeMillis(); if (n >= nextCheck) { now.setTime(n); nextCheck = rc.getNextCheckMillis(now); try { rollOver(); } catch(IOException ioe) { if (ioe instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.error("rollOver() failed.", ioe); } } super.subAppend(event); } } /** * RollingCalendar is a helper class to DailyRollingFileAppender. * Given a periodicity type and the current time, it computes the * start of the next interval. * */ class RollingCalendar extends GregorianCalendar { private static final long serialVersionUID = -3560331770601814177L; int type = DailyRollingFileAppender.TOP_OF_TROUBLE; RollingCalendar() { super(); } RollingCalendar(TimeZone tz, Locale locale) { super(tz, locale); } void setType(int type) { this.type = type; } public long getNextCheckMillis(Date now) { return getNextCheckDate(now).getTime(); } public Date getNextCheckDate(Date now) { this.setTime(now); switch(type) { case DailyRollingFileAppender.TOP_OF_MINUTE: this.set(Calendar.SECOND, 0); this.set(Calendar.MILLISECOND, 0); this.add(Calendar.MINUTE, 1); break; case DailyRollingFileAppender.TOP_OF_HOUR: this.set(Calendar.MINUTE, 0); this.set(Calendar.SECOND, 0); this.set(Calendar.MILLISECOND, 0); this.add(Calendar.HOUR_OF_DAY, 1); break; case DailyRollingFileAppender.HALF_DAY: this.set(Calendar.MINUTE, 0); this.set(Calendar.SECOND, 0); this.set(Calendar.MILLISECOND, 0); int hour = get(Calendar.HOUR_OF_DAY); if(hour < 12) { this.set(Calendar.HOUR_OF_DAY, 12); } else { this.set(Calendar.HOUR_OF_DAY, 0); 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.SECOND, 0); this.set(Calendar.MILLISECOND, 0); this.add(Calendar.DATE, 1); break; case DailyRollingFileAppender.TOP_OF_WEEK: this.set(Calendar.DAY_OF_WEEK, getFirstDayOfWeek()); 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.WEEK_OF_YEAR, 1); break; case DailyRollingFileAppender.TOP_OF_MONTH: this.set(Calendar.DATE, 1); 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.MONTH, 1); break; default: throw new IllegalStateException("Unknown periodicity type."); } return getTime(); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/Logger.java0000644000175000017500000001516111751454711023543 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.spi.LoggerFactory; /** This is the central class in the log4j package. Most logging operations, except configuration, are done through this class. @since log4j 1.2 @author Ceki Gülcü */ public class Logger extends Category { /** The fully qualified name of the Logger class. See also the getFQCN method. */ private static final String FQCN = Logger.class.getName(); 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.

This method first checks if this category is DEBUG enabled by comparing the level of this category with the {@link Level#DEBUG DEBUG} level. If this category is DEBUG enabled, then it converts the message object (passed as parameter) to a string by invoking the appropriate {@link org.apache.log4j.or.ObjectRenderer}. It then proceeds to call all the registered appenders in this category and also higher in the hierarchy depending on the value of the additivity flag.

WARNING 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 #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(Level.DEBUG.isGreaterOrEqual(this.getChainedLevel())) { // forcedLog(FQCN, Level.DEBUG, message, null); // } //} /** Log a message object with the FINE level including the stack trace of the {@link Throwable} t passed as parameter.

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. */ //public //void fine(Object message, Throwable t) { // if(repository.isDisabled(Level.DEBUG_INT)) // return; // if(Level.DEBUG.isGreaterOrEqual(this.getChainedLevel())) // forcedLog(FQCN, Level.FINE, message, t); //} /** * Retrieve a logger named according to the value of the * name parameter. If the named logger already exists, * then the existing instance will be returned. Otherwise, a new * instance is created. * *

By default, loggers do not have a set level but inherit it * from their neareast ancestor with a set level. This is one of the * central features of log4j. * * @param name The name of the logger to retrieve. */ static public Logger getLogger(String name) { return LogManager.getLogger(name); } /** * Shorthand for getLogger(clazz.getName()). * * @param clazz The name of clazz will be used as the * name of the logger to retrieve. See {@link #getLogger(String)} * for more detailed information. */ static public Logger getLogger(Class clazz) { return LogManager.getLogger(clazz.getName()); } /** * Return the root logger for the current logger repository. *

* The {@link #getName Logger.getName()} method for the root logger always returns * string value: "root". However, calling * Logger.getLogger("root") does not retrieve the root * logger but a logger just under root named "root". *

* In other words, calling this method is the only way to retrieve the * root logger. */ public static Logger getRootLogger() { return LogManager.getRootLogger(); } /** Like {@link #getLogger(String)} except that the type of logger instantiated depends on the type returned by the {@link LoggerFactory#makeNewLoggerInstance} method of the factory parameter.

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 actually create a new Instance. @since 0.8.5 */ public static Logger getLogger(String name, LoggerFactory factory) { return LogManager.getLogger(name, factory); } /** * Log a message object with the {@link org.apache.log4j.Level#TRACE TRACE} level. * * @param message the message object to log. * @see #debug(Object) for an explanation of the logic applied. * @since 1.2.12 */ public void trace(Object message) { if (repository.isDisabled(Level.TRACE_INT)) { return; } if (Level.TRACE.isGreaterOrEqual(this.getEffectiveLevel())) { forcedLog(FQCN, Level.TRACE, message, null); } } /** * Log a message object with the TRACE level including the * stack trace of the {@link Throwable}t passed as parameter. * *

* 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. * @since 1.2.12 */ public void trace(Object message, Throwable t) { if (repository.isDisabled(Level.TRACE_INT)) { return; } if (Level.TRACE.isGreaterOrEqual(this.getEffectiveLevel())) { forcedLog(FQCN, Level.TRACE, message, t); } } /** * Check whether this category is enabled for the TRACE Level. * @since 1.2.12 * * @return boolean - true if this category is enabled for level * TRACE, false otherwise. */ public boolean isTraceEnabled() { if (repository.isDisabled(Level.TRACE_INT)) { return false; } return Level.TRACE.isGreaterOrEqual(this.getEffectiveLevel()); } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/AsyncAppender.java0000644000175000017500000003623111751454711025061 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Contibutors: Aaron Greenhouse // Thomas Tuft Muller package org.apache.log4j; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.log4j.helpers.AppenderAttachableImpl; import org.apache.log4j.spi.AppenderAttachable; import org.apache.log4j.spi.LoggingEvent; /** * The AsyncAppender lets users log events asynchronously. *

*

* 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. *

*

*

* The AsyncAppender uses a separate thread to serve the events in its buffer. *

*

* Important note: The AsyncAppender can only be script * configured using the {@link org.apache.log4j.xml.DOMConfigurator}. *

* * @author Ceki Gülcü * @author Curt Arnold * @since 0.9.1 */ public class AsyncAppender extends AppenderSkeleton implements AppenderAttachable { /** * The default buffer size is set to 128 events. */ public static final int DEFAULT_BUFFER_SIZE = 128; /** * Event buffer, also used as monitor to protect itself and * discardMap from simulatenous modifications. */ private final List buffer = new ArrayList(); /** * Map of DiscardSummary objects keyed by logger name. */ private final Map discardMap = new HashMap(); /** * Buffer size. */ private int bufferSize = DEFAULT_BUFFER_SIZE; /** Nested appenders. */ AppenderAttachableImpl aai; /** * Nested appenders. */ private final AppenderAttachableImpl appenders; /** * Dispatcher. */ private final Thread dispatcher; /** * Should location info be included in dispatched messages. */ private boolean locationInfo = false; /** * Does appender block when buffer is full. */ private boolean blocking = true; /** * Create new instance. */ public AsyncAppender() { appenders = new AppenderAttachableImpl(); // // only set for compatibility aai = appenders; dispatcher = new Thread(new Dispatcher(this, buffer, discardMap, appenders)); // It is the user's responsibility to close appenders before // exiting. dispatcher.setDaemon(true); // set the dispatcher priority to lowest possible value // dispatcher.setPriority(Thread.MIN_PRIORITY); dispatcher.setName("AsyncAppender-Dispatcher-" + dispatcher.getName()); dispatcher.start(); } /** * Add appender. * * @param newAppender appender to add, may not be null. */ public void addAppender(final Appender newAppender) { synchronized (appenders) { appenders.addAppender(newAppender); } } /** * {@inheritDoc} */ public void append(final LoggingEvent event) { // // if dispatcher thread has died then // append subsequent events synchronously // See bug 23021 if ((dispatcher == null) || !dispatcher.isAlive() || (bufferSize <= 0)) { synchronized (appenders) { appenders.appendLoopOnAppenders(event); } return; } // Set the NDC and thread name for the calling thread as these // LoggingEvent fields were not set at event creation time. event.getNDC(); event.getThreadName(); // Get a copy of this thread's MDC. event.getMDCCopy(); if (locationInfo) { event.getLocationInformation(); } event.getRenderedMessage(); event.getThrowableStrRep(); synchronized (buffer) { while (true) { int previousSize = buffer.size(); if (previousSize < bufferSize) { buffer.add(event); // // if buffer had been empty // signal all threads waiting on buffer // to check their conditions. // if (previousSize == 0) { buffer.notifyAll(); } break; } // // Following code is only reachable if buffer is full // // // if blocking and thread is not already interrupted // and not the dispatcher then // wait for a buffer notification boolean discard = true; if (blocking && !Thread.interrupted() && Thread.currentThread() != dispatcher) { try { buffer.wait(); discard = false; } catch (InterruptedException e) { // // reset interrupt status so // calling code can see interrupt on // their next wait or sleep. Thread.currentThread().interrupt(); } } // // if blocking is false or thread has been interrupted // add event to discard map. // if (discard) { String loggerName = event.getLoggerName(); DiscardSummary summary = (DiscardSummary) discardMap.get(loggerName); if (summary == null) { summary = new DiscardSummary(event); discardMap.put(loggerName, summary); } else { summary.add(event); } break; } } } } /** * Close this AsyncAppender by interrupting the dispatcher * thread which will process all pending events before exiting. */ public void close() { /** * Set closed flag and notify all threads to check their conditions. * Should result in dispatcher terminating. */ synchronized (buffer) { closed = true; buffer.notifyAll(); } try { dispatcher.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); org.apache.log4j.helpers.LogLog.error( "Got an InterruptedException while waiting for the " + "dispatcher to finish.", e); } // // close all attached appenders. // synchronized (appenders) { Enumeration iter = appenders.getAllAppenders(); if (iter != null) { while (iter.hasMoreElements()) { Object next = iter.nextElement(); if (next instanceof Appender) { ((Appender) next).close(); } } } } } /** * Get iterator over attached appenders. * @return iterator or null if no attached appenders. */ public Enumeration getAllAppenders() { synchronized (appenders) { return appenders.getAllAppenders(); } } /** * Get appender by name. * * @param name name, may not be null. * @return matching appender or null. */ public Appender getAppender(final String name) { synchronized (appenders) { return appenders.getAppender(name); } } /** * Gets whether the location of the logging request call * should be captured. * * @return the current value of the LocationInfo option. */ public boolean getLocationInfo() { return locationInfo; } /** * Determines if specified appender is attached. * @param appender appender. * @return true if attached. */ public boolean isAttached(final Appender appender) { synchronized (appenders) { return appenders.isAttached(appender); } } /** * {@inheritDoc} */ public boolean requiresLayout() { return false; } /** * Removes and closes all attached appenders. */ public void removeAllAppenders() { synchronized (appenders) { appenders.removeAllAppenders(); } } /** * Removes an appender. * @param appender appender to remove. */ public void removeAppender(final Appender appender) { synchronized (appenders) { appenders.removeAppender(appender); } } /** * Remove appender by name. * @param name name. */ public void removeAppender(final String name) { synchronized (appenders) { appenders.removeAppender(name); } } /** * The LocationInfo option takes a boolean value. By default, it is * set to false which means there will be no effort to extract the location * information related to the event. As a result, the event that will be * ultimately logged will likely to contain the wrong location information * (if present in the log format). *

*

* Location information extraction is comparatively very slow and should be * avoided unless performance is not a concern. *

* @param flag true if location information should be extracted. */ public void setLocationInfo(final boolean flag) { locationInfo = flag; } /** * Sets the number of messages allowed in the event buffer * before the calling thread is blocked (if blocking is true) * or until messages are summarized and discarded. Changing * the size will not affect messages already in the buffer. * * @param size buffer size, must be positive. */ public void setBufferSize(final int size) { // // log4j 1.2 would throw exception if size was negative // and deadlock if size was zero. // if (size < 0) { throw new java.lang.NegativeArraySizeException("size"); } synchronized (buffer) { // // don't let size be zero. // bufferSize = (size < 1) ? 1 : size; buffer.notifyAll(); } } /** * Gets the current buffer size. * @return the current value of the BufferSize option. */ public int getBufferSize() { return bufferSize; } /** * Sets whether appender should wait if there is no * space available in the event buffer or immediately return. * * @since 1.2.14 * @param value true if appender should wait until available space in buffer. */ public void setBlocking(final boolean value) { synchronized (buffer) { blocking = value; buffer.notifyAll(); } } /** * Gets whether appender should block calling thread when buffer is full. * If false, messages will be counted by logger and a summary * message appended after the contents of the buffer have been appended. * * @since 1.2.14 * @return true if calling thread will be blocked when buffer is full. */ public boolean getBlocking() { return blocking; } /** * Summary of discarded logging events for a logger. */ private static final class DiscardSummary { /** * First event of the highest severity. */ private LoggingEvent maxEvent; /** * Total count of messages discarded. */ private int count; /** * Create new instance. * * @param event event, may not be null. */ public DiscardSummary(final LoggingEvent event) { maxEvent = event; count = 1; } /** * Add discarded event to summary. * * @param event event, may not be null. */ public void add(final LoggingEvent event) { if (event.getLevel().toInt() > maxEvent.getLevel().toInt()) { maxEvent = event; } count++; } /** * Create event with summary information. * * @return new event. */ public LoggingEvent createEvent() { String msg = MessageFormat.format( "Discarded {0} messages due to full event buffer including: {1}", new Object[] { new Integer(count), maxEvent.getMessage() }); return new LoggingEvent( "org.apache.log4j.AsyncAppender.DONT_REPORT_LOCATION", Logger.getLogger(maxEvent.getLoggerName()), maxEvent.getLevel(), msg, null); } } /** * Event dispatcher. */ private static class Dispatcher implements Runnable { /** * Parent AsyncAppender. */ private final AsyncAppender parent; /** * Event buffer. */ private final List buffer; /** * Map of DiscardSummary keyed by logger name. */ private final Map discardMap; /** * Wrapped appenders. */ private final AppenderAttachableImpl appenders; /** * Create new instance of dispatcher. * * @param parent parent AsyncAppender, may not be null. * @param buffer event buffer, may not be null. * @param discardMap discard map, may not be null. * @param appenders appenders, may not be null. */ public Dispatcher( final AsyncAppender parent, final List buffer, final Map discardMap, final AppenderAttachableImpl appenders) { this.parent = parent; this.buffer = buffer; this.appenders = appenders; this.discardMap = discardMap; } /** * {@inheritDoc} */ public void run() { boolean isActive = true; // // if interrupted (unlikely), end thread // try { // // loop until the AsyncAppender is closed. // while (isActive) { LoggingEvent[] events = null; // // extract pending events while synchronized // on buffer // synchronized (buffer) { int bufferSize = buffer.size(); isActive = !parent.closed; while ((bufferSize == 0) && isActive) { buffer.wait(); bufferSize = buffer.size(); isActive = !parent.closed; } if (bufferSize > 0) { events = new LoggingEvent[bufferSize + discardMap.size()]; buffer.toArray(events); // // add events due to buffer overflow // int index = bufferSize; for ( Iterator iter = discardMap.values().iterator(); iter.hasNext();) { events[index++] = ((DiscardSummary) iter.next()).createEvent(); } // // clear buffer and discard map // buffer.clear(); discardMap.clear(); // // allow blocked appends to continue buffer.notifyAll(); } } // // process events after lock on buffer is released. // if (events != null) { for (int i = 0; i < events.length; i++) { synchronized (appenders) { appenders.appendLoopOnAppenders(events[i]); } } } } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/Level.java0000644000175000017500000001521211751454711023370 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Contributors: Kitching Simon // Nicholas Wolff package org.apache.log4j; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamException; import java.io.Serializable; /** Defines the minimum set of levels recognized by the system, that is OFF, FATAL, ERROR, WARN, INFODEBUG and ALL.

The Level class may be subclassed to define a larger level set. @author Ceki Gülcü */ public class Level extends Priority implements Serializable { /** * TRACE level integer value. * @since 1.2.12 */ public static final int TRACE_INT = 5000; /** The OFF has the highest possible rank and is intended to turn off logging. */ final static public Level OFF = new Level(OFF_INT, "OFF", 0); /** The FATAL level designates very severe error events that will presumably lead the application to abort. */ final static public Level FATAL = new Level(FATAL_INT, "FATAL", 0); /** The ERROR level designates error events that might still allow the application to continue running. */ final static public Level ERROR = new Level(ERROR_INT, "ERROR", 3); /** The WARN level designates potentially harmful situations. */ final static public Level WARN = new Level(WARN_INT, "WARN", 4); /** The INFO level designates informational messages that highlight the progress of the application at coarse-grained level. */ final static public Level INFO = new Level(INFO_INT, "INFO", 6); /** The DEBUG Level designates fine-grained informational events that are most useful to debug an application. */ final static public Level DEBUG = new Level(DEBUG_INT, "DEBUG", 7); /** * The TRACE Level designates finer-grained * informational events than the DEBUGALL has the lowest possible rank and is intended to turn on all logging. */ final static public Level ALL = new Level(ALL_INT, "ALL", 7); /** * Serialization version id. */ static final long serialVersionUID = 3491141966387921974L; /** Instantiate a Level object. */ protected Level(int level, String levelStr, int syslogEquivalent) { super(level, levelStr, syslogEquivalent); } /** Convert the string passed as argument to a level. If the conversion fails, then this method returns {@link #DEBUG}. */ public static Level toLevel(String sArg) { return (Level) toLevel(sArg, Level.DEBUG); } /** Convert an integer passed as argument to a level. If the conversion fails, then this method returns {@link #DEBUG}. */ public static Level toLevel(int val) { return (Level) toLevel(val, Level.DEBUG); } /** Convert an integer passed as argument to a level. If the conversion fails, then this method returns the specified default. */ public static Level toLevel(int val, Level defaultLevel) { switch(val) { case ALL_INT: return ALL; case DEBUG_INT: return Level.DEBUG; case INFO_INT: return Level.INFO; case WARN_INT: return Level.WARN; case ERROR_INT: return Level.ERROR; case FATAL_INT: return Level.FATAL; case OFF_INT: return OFF; case TRACE_INT: return Level.TRACE; default: return defaultLevel; } } /** Convert the string passed as argument to a level. If the conversion fails, then this method returns the value of defaultLevel. */ public static Level toLevel(String sArg, Level defaultLevel) { if(sArg == null) return defaultLevel; String s = sArg.toUpperCase(); if(s.equals("ALL")) return Level.ALL; if(s.equals("DEBUG")) return Level.DEBUG; if(s.equals("INFO")) return Level.INFO; if(s.equals("WARN")) return Level.WARN; if(s.equals("ERROR")) return Level.ERROR; if(s.equals("FATAL")) return Level.FATAL; if(s.equals("OFF")) return Level.OFF; if(s.equals("TRACE")) return Level.TRACE; // // For Turkish i problem, see bug 40937 // if(s.equals("\u0130NFO")) return Level.INFO; return defaultLevel; } /** * Custom deserialization of Level. * @param s serialization stream. * @throws IOException if IO exception. * @throws ClassNotFoundException if class not found. */ private void readObject(final ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); level = s.readInt(); syslogEquivalent = s.readInt(); levelStr = s.readUTF(); if (levelStr == null) { levelStr = ""; } } /** * Serialize level. * @param s serialization stream. * @throws IOException if exception during serialization. */ private void writeObject(final ObjectOutputStream s) throws IOException { s.defaultWriteObject(); s.writeInt(level); s.writeInt(syslogEquivalent); s.writeUTF(levelStr); } /** * Resolved deserialized level to one of the stock instances. * May be overriden in classes derived from Level. * @return resolved object. * @throws ObjectStreamException if exception during resolution. */ private Object readResolve() throws ObjectStreamException { // // if the deserizalized object is exactly an instance of Level // if (getClass() == Level.class) { return toLevel(level); } // // extension of Level can't substitute stock item // return this; } } apache-log4j1.2-1.2.17.orig/src/main/java/org/apache/log4j/EnhancedThrowableRenderer.java0000644000175000017500000001461111751454711027367 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import org.apache.log4j.spi.ThrowableRenderer; import java.io.File; import java.lang.reflect.Method; import java.net.URL; import java.security.CodeSource; import java.util.HashMap; import java.util.Map; /** * Enhanced implementation of ThrowableRenderer. Uses Throwable.getStackTrace * if running on JDK 1.4 or later and delegates to DefaultThrowableRenderer.render * on earlier virtual machines. * * @since 1.2.16 */ public final class EnhancedThrowableRenderer implements ThrowableRenderer { /** * Throwable.getStackTrace() method. */ private Method getStackTraceMethod; /** * StackTraceElement.getClassName() method. */ private Method getClassNameMethod; /** * Construct new instance. */ public EnhancedThrowableRenderer() { try { Class[] noArgs = null; getStackTraceMethod = Throwable.class.getMethod("getStackTrace", noArgs); Class ste = Class.forName("java.lang.StackTraceElement"); getClassNameMethod = ste.getMethod("getClassName", noArgs); } catch(Exception ex) { } } /** * {@inheritDoc} */ public String[] doRender(final Throwable throwable) { if (getStackTraceMethod != null) { try { Object[] noArgs = null; Object[] elements = (Object[]) getStackTraceMethod.invoke(throwable, noArgs); String[] lines = new String[elements.length + 1]; lines[0] = throwable.toString(); Map classMap = new HashMap(); for(int i = 0; i < elements.length; i++) { lines[i+1] = formatElement(elements[i], classMap); } return lines; } catch(Exception ex) { } } return DefaultThrowableRenderer.render(throwable); } /** * Format one element from stack trace. * @param element element, may not be null. * @param classMap map of class name to location. * @return string representation of element. */ private String formatElement(final Object element, final Map classMap) { StringBuffer buf = new StringBuffer("\tat "); buf.append(element); try { String className = getClassNameMethod.invoke(element, (Object[]) null).toString(); Object classDetails = classMap.get(className); if (classDetails != null) { buf.append(classDetails); } else { Class cls = findClass(className); int detailStart = buf.length(); buf.append('['); try { CodeSource source = cls.getProtectionDomain().getCodeSource(); if (source != null) { URL locationURL = source.getLocation(); if (locationURL != null) { // // if a file: URL // if ("file".equals(locationURL.getProtocol())) { String path = locationURL.getPath(); if (path != null) { // // find the last file separator character // int lastSlash = path.lastIndexOf('/'); int lastBack = path.lastIndexOf(File.separatorChar); if (lastBack > lastSlash) { lastSlash = lastBack; } // // if no separator or ends with separator (a directory) // then output the URL, otherwise just the file name. // if (lastSlash <= 0 || lastSlash == path.length() - 1) { buf.append(locationURL); } else { buf.append(path.substring(lastSlash + 1)); } } } else { buf.append(locationURL); } } } } catch(SecurityException ex) { } buf.append(':'); Package pkg = cls.getPackage(); if (pkg != null) { String implVersion = pkg.getImplementationVersion(); if (implVersion != null) { buf.append(implVersion); } } buf.append(']'); classMap.put(className, buf.substring(detailStart)); } } catch(Exception ex) { } return buf.toString(); } /** * Find class given class name. * @param className class name, may not be null. * @return class, will not be null. * @throws ClassNotFoundException thrown if class can not be found. */ private Class findClass(final String className) throws ClassNotFoundException { try { return Thread.currentThread().getContextClassLoader().loadClass(className); } catch (ClassNotFoundException e) { try { return Class.forName(className); } catch (ClassNotFoundException e1) { return getClass().getClassLoader().loadClass(className); } } } } apache-log4j1.2-1.2.17.orig/src/changes/0000755000175000017500000000000012126647422016171 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/changes/changes.xml0000644000175000017500000027607611751454713020347 0ustar tonytony Apache log4j 1.2 log4j 1.2.17 release preparation Configure from an InputStream JDBCAppender not closed due to SQL Exception while executing an SQL (thanks to Anurag Agarwal) Memoryleak - org.apache.log4j.helpers.ThreadLocalMap DOMConfigurator does not close input stream when configured based on URL. javadoc.jar was missing NOTICE and LICENSE and contained .svn entries. Wrong log levels logged with serialized LoggingEvent. Add org.apache.log4j.rewrite.RewriteAppender and org.apache.log4j.util.UtilLoggingLevel from discontinued receivers companion. log4j 1.2.16 release preparation. Create a public identifier for log4j.dtd ("-//APACHE//DTD LOG4J 1.2//EN") TelnetAppender misses messages when one of many clients disconnect. TelnetAppender throws null pointers at log time when socket couldn't be opened. ThrowableInformation.getThrowableStringRep can return null strings. log4j.dtd defines class attribute for category element, but not for logger. SMTPAppender.setSMTPUserName and others missing @since tags. Request for compile-on-Windows help file in src package. AsyncAppender failing on changing message objects. Subst-mechanism in DOMConfigurator broken. DailyRollingFileAppender may lose messages during failed rollover attempts. Fix mangled source-repository.html. Minor documentation changes. Make javamail, jmx, jms dependencies optional in pom.xml. SocketHubAppender should expose actual port in use to extending classes. SocketHubAppender in the 1.2.16 does not support a scroll back buffer or application property Give log4j threads reasonable names. LocationInfo can report wrong caller when other class names contain logger class name as substring. ErrorHandlerTestCase is not run and does not pass. Agent.java is sole dependency on jmxtools.jar with Java 5+. Eliminate compile dependency on non-redistributable JMS reference implementation. Exception in call to toString of message propagates to caller. Javadoc class index corrupted by JDBCAppender deprecation warning. Improve warning message when log4j is accessed after unload by Tomcat. NullPointerException in NDC.remove after unload by Tomcat. Configuring triggering/rolling policies should be supported through properties. More explanations when hitting WARN No appenders could be found for logger. Use Throwable.getStackTrace to obtain location when running on JDK 1.4 or later. AsyncAppender fails on changing Throwable. Extra NPE error message when using missing appender class with DOMConfigurator. org.apache.log4j.varia.NullAppender lacks static accessor to static instance. Javadoc for Appender.getName implies that the return value will be unique and not null. Weekly rotation problem in Europe. Add OSGi packaging info. InterruptedIOException ignored by log4j. HierarchyDynamicMBean missing unregister MBean Support -Dm2_repo option on Maven build for non-default Maven repository location. 2 tests for DateLayout are failing because of ill initialized DateFormat. Incorrect user mailing list URL. NTEventLogAppender.dll for 64-bit editions for Microsoft Windows. Add configuration of ThrowableRenderers and add org.apache.log4j.EnhancedThrowableRenderer. SMTPAppender does not force evaluation of message at request time Support SSL transport in SMTPAppender SMTPAppender should have a sendOnClose option Support %X layout specification to output all MDC key-value pairs Add replyTo attribute to SMTPAppender SMTPAppender does not properly encode subject or content containing non-ASCII characters. Clarify javadoc of Layout.ignoresThrowable. SyslogAppender.append throws exception if layout is not set. QuietWriter.write should check for null argument. LogFactor5 CategoryPath doesn't replace slashes with dots. LoggerDynamicMBean needs to handle a null Appender name. DOMConfigurator.configure(URL) fails on JRE 1.5.0_16. Document system properties used by log4j. log4j is susceptible to exceptions in Exception.printStackTrace. Misuse of "it's" in Javadoc for PatternLayout. Add SMTPAppender.formatBody to simplify extension. Failure when toString() of throwable performs logging in SocketAppender, SocketHubAppender and JDBCAppender. Reading configuration files from a JAR locks the JAR file PropertyConfigurator does not support configuring ErrorHandler. log4j.ignoreTCL should apply to the getResource method in addition to the loadClass method of org.apache.log4j.helpers.Loader. The QuietWriter class does not live up to its published contract. More Debug output for log4j auto-configure requested. Add MDC.clear(). NullPointerException when calling Category.removeAllAppenders(). Allow overriding of flush strategy. Add recommendation to use EnhancedPatternLayout to avoid synchronization issues in PatternLayout Source contains unnecessary imports. Add LoggingEvent.removeProperty Typo ("two three goals") in log4j FAQ Unit tests fail for system dates after 2009-12-31 Download page does not have link to KEYS file Add parameterized logging utility classes LogMF and LogSF from extras companion. Add EnhancedPatternLayout from extras companion. Links to example code broken in the JavaDocs Unused imports and variables in test code cause gcj compile warnings. Unit tests fail on Apache Harmony and gcj due to stack trace expectations. SocketServerTestCase.test8 fails on Apache Harmony. TestLogMF.testDebugDate fails on gcj. TelnetAppenderTest.testIt fails on gcj. Eclipse Java Compiler and gcj do not support -source=1.2. CachedDateFormatTest fails on Apache Harmony. Add %p{-2} pattern to EnhancedPatternLayout to drop two leading elements from name. Add %throwable{n} and {-n} pattern to EnhancedPatternLayout to print n or drop last n lines. log4j 1.2.15 release preparation. Switch to NOPLoggerRepository if application reloading nulls repositorySelector. Add 'application' property support to SocketAppender (from 1.3) Log4JEntityResolver will return null if log4j.dtd can not be found on classpath. HierarchyEventListener.removeAppenderEvent never called. XMLLayout does not escape CDATA sections within NDC or throwables. Added test to confirm that DOMConfigurator.configureAndWatch does configure. Default initialization with XML file halts program if JAXP not available. Add reset option to PropertyConfigurator and DOMConfigurator. Error message always logged to LogLog when calling close on TelnetAppender. Add configurable triggeringPolicy for SMTPAppender. NullPointerException in MDC on Tomcat reload. Notice to use UTF-8 or UTF-16 encoding added to XML and HTMLLayout javadoc. XML and HTMLLayout do not always escape special characters. Optionally render MDC content in XMLLayout Typo in log4j.dtd concerning threshold. ERFATestCase fails on some JDK's. SocketNode can leak Sockets. Migrate to Maven based build and documentation. Prepare Maven release bundles. Eclipse compiler warning cleanup. JRockit VM and java-gcj fail unit tests. SocketAppender does not use FallbackErrorHandler Enhance DOMConfigurator to delegate unrecognized elements to configured object. Add LoggingEvent accessors. InstanceAlreadyExistsException using MBean. Reduce first connection failure severity in SocketAppender SyslogAppender does not limit packets to 1024 bytes. SyslogAppender: Added "header" property which if set to true will cause the appender to produce the HEADER part (timestamp and hostname) of the syslog packet. Default value is false for compatibility with previous behavior. SyslogAppender also now sends any header from the associated layout when activateOptions is called or first logging event is sent and any footer when the appender is closed. SyslogAppender leaks descriptors SyslogAppender assumes all lines start with tab SyslogAppender does not limit packet size to 1024 bytes NTEventLogAppender: Updated NTEventLogAppender.dll which corrects missing event messages and which should work with earlier releases of log4j. NTEventLogAppender.dll also now supports registration and unregistration using regsvr32. If replacing an existing copy of NTEventLogAppender, use "regsvr32 NTDllEventLogAppender.dll" or manually remove the HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/Eventlog/Application/Log4J registry key. NTEventLogAppender.dll performs unnecessary code page conversion using code copied from book. PropertyConfigurator.configure(URL) does not close resource stream. In Turkish locale level "info" is not equivalent to "INFO" Javadoc of PatternLayout should use %n in TTCC layout examples Stacktraces of exceptions disappear occassionally Incorrect message when specified custom level class does not implement toLevel Warning when configuring inner-class logger AsyncAppender in 1.2.14 DiscardSummary events create NullPointerExceptions in layouts Add target to generate binary and source compatibility report PropertyPrinter.printOptions breaking signature change in log4j 1.2.9 RollingFileAppender may delete files during rollover XMLConfiguration of loggerFactory does not work SyslogAppender does not limit packet size to 1024 bytes Update source per new ASF Header Policy. DateLayoutTest fails if default Locale is not en_US. Stacktrace may choke on null fields. Add projects.apache.org project descriptor. Monitor deadlock in AsyncAppender. AsyncAppender: Dispatcher should run at normal prio. AsyncAppender wait forever when buffer is full. Add non-blocking option for AsyncAppender. Add SyslogPort option to SyslogAppender. Add cc and bcc addresses to SMTPAppender. Add password authentication to SMTPAppender. NullPointerException in org.apache.log4j.NDC.get. org.apache.log4j.lf5.util.DateFormatManager.setTimeZone assignment error. Monthly logs not generated at midnight with DailyRollingFileAppender. PatternLayout specifier %r is not consistent with documentation. Space after log level causes default level to be used. Bad patterns in ISO8601DateFormat and DateTimeDateFormat. SyslogAppender throws NullPointerException upon misconfiguration. FallbackErrorHandler throws NullPointerException if no loggers are set. Bad documentation for WriterAppender.encoding. NTEventLogAppender not build, tested and placed in distribution. SMTPAppender does not output newlines between stack trace lines. SMTPAppender will not run within sandbox. MDC with SMTPAppender doesn't work. Misspelling in HierarchyDynamicMBean. Additivity not exported by PropertyPrinter. RollingFileAppender, if removed, can cause NullPointerExceptions. AsyncAppender blocks on thread death. NOTICE file added to distribution and jars. Chainsaw of log4j 1.2 does not show TRACE level. TRACE level missing in short introduction to log4j. Update site generation to velocity 1.4 and remove dependency on logging/site project. Location info missing for TRACE level messages. Console appender now behaves as before to fix compatibility problem with JBoss introduced in 1.2.12 release due to fix for bug 31056. Can still be configured to detect changes in the System.out and System.err streams as needed by setting the follow property. Removed final qualifiers on member variables in org.apache.log4j.chainsaw.LoggingReceiver which would cause spurious compiler errors with JDK 1.1 and 1.2 javac compilers. Added a jndi.jar property to the build.xml. Added "release" target to build.xml. Removed references to obsolete documentation. Added protected accessors for member variables topicConnection, topicSession, and topicPublisher. SyslogAppender now checks Layout.ignoresThrowable() just like every other appender. DOMConfigurator would call LogLog.error to report XML validation errors that caused no problems in the interpretation of the configuration file. Fixed the JavaDoc links for the XML sample files. Added getNext/setNext methods to org.apache.log4j.spi.Filter and deprecated public "next" field. This mirrors the same change in the upcoming 1.3 version and, hence, provides a migration path. Added o.a.log4j.Logger.trace(), o.a.log4j.Logger.isTraceEnabled() and o.a.log4j.Level.TRACE Implemented serialization for Level. o.a.log4j.ConsoleAppender would ignore redirections of System.out and System.err that occurred after configuration. o.a.log4j.xml.DOMConfigurator would not properly interpret relative path names in external entity declarations. o.a.log4j.xml.XmlLayout would not properly escape class names that contained '<' or '>'. Use of String.intern() in o.a.log4j.CategoryKey would cause application to slow down. o.a.log4j.FileAppender would not create log file if parent directory did not exist. o.a.log4j.AsyncAppender would deadlock if a unchecked exception occurred in the attached appender causing the dispatch thread to die. Added jdiff target to build.xml. log4j would not build with a JDK 1.5 javac. Added log4j 1.1 compatibility method to o.a.l.helpers.Loader. Additional null terminating character in Windows nteventlog.cpp code. Broken links to J2SE classes in javadocs. o.a.log4j.or.jms.MessageRenderer would not be compiled in the build.jms target. Version 1.2.10 was not released following the accepted rules and process of the log4j project and Logging Services Project and was recalled and removed. Please do not use version 1.2.10, it is not an official log4j release. Log4j version 1.2.9, is identical to version 1.2.8, except that several key methods have been deprecated in preparation for version 1.3.0, the next major release of log4j. These changes are intended to enforce the rule that client code should never refer to the Category class directly, but use the Logger class instead. Similarly, client code should not refer to the Priority class but to the Level class instead. For a more detailed discussion, refer to the document entitled preparing for log4j 1.3 at: http://www.qos.ch/logging/preparingFor13.jsp XMLAppender would throw a NullPointerException if the input message was null. Many thanks to David Vandegrift for reporting the bug and to Hendrik Brummermann for supplying the patch. Various versions of Xerces would not parse log4j configuration scripts expressed in XML format. The "removes" buffer used in the flushBuffer() method of JDBCAppender is now cleared, solving the memory leak. Thanks to John Landers for reporting the bug and suggesting the fix. SocketAppender now honors ReconnectionDelay of 0. Many thanks to Scott Schram for reporting the bug and providing the fix. Log4j now searches for the file log4j.xml as well as the file log4j.properties during log4j initialization. Add of new options in JMSAppender and new command line arguments in JMSSink. Add new method getLoggerName() in LoggingEvent class. The getLoggerName is the preferred way for accessing the logger name. The public access categoryName field should not be accessed directly. Similarly, added the getLevel method which is now the preferred way of accessing the event's level. The public access level field should not be accessed directly. The javadocs now mark the categoryName and level fields as deprecated. Modified existing appenders to comply with these new directives. Log4j now will check if a system property named "log4j.ignoreTCL" is set. If it is set, then it will ignore the Thread Context ClassLoader when loading classes. This solves the irritating "appender is not assignable to Appender" messages observed when log4j.jar is loaded by multiple class loaders. The error reporting for this problem was also improved. Calling the MDC.get method with a null argument would throw a NullPointerException. Calling an AsyncAppender close method also closes the embedded appender instances. The JDBCAppender is marked as slated for replacement. Do not build critical software using it. Add LF5 documentation and examples. Further tests are required for full integration. XMLLayout can now output messages which contain embedded CDATA sections.Many thanks to Michael A. McAngus for supplying the relevant patch. The dispatcher thread associated with AsyncAppender is now marked as a deamon thread. Add missing NTEventLogAppender.dll log4j.dtd was changed so that <log4j:event> is now made of logger and level attributes instead of category and priority. Changed XMLLayout to conform to the DTD. Chainsaw was changed to adapt to the XMLLayout. Add missing LevelRangeFilter file. SyslogAppender would incorrectly compute the length of the datagram to send to the remote syslogd host. Reported by Mamoru Kadota. The stack trace of exception would not be properly printed on the Compaq tru64 Unix platform. Initially reported by Fabrice Claes and later by Espen H. Kolstad who also provided the fix. Log4j configurators take the "NULL" string value as a synonym for "INHERITED". Both of these two strings are legal level values for setting the level of a logger. Both values are case insensitive. When loading component classes, log4j will now first attempt to use the Thread Context Loader and if that fails, it will use Class.forName. In log4j 1.2 and 1.2.1, only Class.forName was used and the TCL was ignored. This change is a response to bug #9305 opened by Scott M. Stark. LoggingEvent.getMDCCopy() method now sets mdcCopyLookupRequired instead of ndcLookupRequired. This bug would cause the wrong MDC information to appear on a log server. It could only occur if the client wrapped an AsyncAppender around a SocketAppender or if the server used an AsyncAppender for its logging. A closed TelnetAppender would continue waiting for connections even if its ServerSocket was closed. This caused the TelnetSocket to sit in a loop and complain about the closed socket. AsyncAppender throws NullPointerException problem. The bug was actually in AppenderSkeleton. Add support for recursive variable substiuton as requested by Eric Chastan. SocketNode now used a BufferedInputStream as suggested by Kok Chong Fixed a problem with DailiyRollingAppender which would not correctly compute the rollover period in certain timezones. Fixed documentation bug #2726 in FAQ.html. Added a flush statement in the WriterAppender.writeFooter method. In XMLLayout, escaped the method attribute. The XMLLayout also outputs each item of a stack trace in a separate line. The LoggingEvent.getMDCCopy method now clones the MDC instead of just referencing it. The ANT build script was modified to use jar files specified in the build.properties file instead of the CLASSPATH environment variable. The build.properties file depends on local paths and is supplied by the user. The build.properties.sample file is included in the distribution. The build.sh and build.bat scripts have been removed. This is the way many other jakarta projects build their projects. The jar files in the dist/lib directory were also removed since they are no longer used. The DOMConfigurator now interprets the string after the '#' character in the value attribute within the <level> element as the fully qualified class name of a custom Level. This is consistent with the way log4j handles "level" values in other places. The class attribute is still honored. Add Oliver Burn's chainsaw tool to the core log4j distribution. Visualisation and dynamic filtering of log events is bound to be a very important area of activity in the future. Add the org.apache.log4j.jdbc.JDBCAppender which as the name indicates sends events to a database using the JDBC API. Thanks to Kevin Steppe for supplying the code. Add SocketHubAppender class as contributed by Mark Womack. This appender sends LoggingEvent objects to a set of remote a log servers. In the Category class, the getChainedPriority method has been replaced with getEffectiveLevel method. Replaced the custom class loading based on the thread context class loader with a simple Class.forName() call. This solves two allied but distinct problems encountered when using Ant with JUnit although the bug is more general. In one instance of the problem, log4j would throw java.lang.NoClassDefFoundError for org/apache/log4j/AppenderSkeleton where log4j.jar and related classes were clearly available to the Ant classloader. In another incarnation, log4j would reject a custom appender claiming that it is not assignable to a org.apache.log4j.Appender variable. This would occur when log4j.jar was available to both the Ant classloader and the system classloader. Thanks to Dave Herman for providing detailed scenarios exposing the issues involved. See http://forum.java.sun.com/thread.jsp?forum=38&thread=70946 http://forum.java.sun.com/thread.jsp?forum=38&thread=70946#479697 http://marc.theaimsgroup.com/?l=ant-user&m=101139178705895&w=2 for more details. Fixed the complaints the compiler issued when using the Logger.setLevel() method. Incorporated the performance enhancements to ISO8601DateFormat and AbsoluteTimeDateFormat classes submitted by Andrew Vajoczki. Source code written for log4j 1.1.3.jar will compile fine with log4j 1.2X. However, code compiled for log4j 1.1.3 would previously systematically throw "java.lang.NoSuchMethodError" runtime exceptions when run with log4j 1.2 - prior to beta2. This problem has been corrected in beta2. Pheew, that was a close one. Log4j 1.2 is now backward compatible in serialization of LoggingEvents. For example, a 1.1.3 SocketAppedner can write to 1.2 SocketServer. Similarly a 1.2 JMSAppender will work with 1.1.3 JMSSink. This should ease the move to log4j 1.2, especially in large deployments. The src/java/org/apache/log4j/examples/ directory moved under the top-level directory as examples/. Fixed the ArrayIndexOutOfBoundsException that was thrown by AsyncAppender if multiple threads were trying to log an event containing an exception near simultaneously. Thanks to Thomas Tuft Muller for reporting this bug. Improved error reporting in DOMConfigurator. Thanks to Thomas Tuft Muller for contributing the enhancement. Log4j is now configurable using JMX. JMX support is not of production quality. Add support for different encodings in WriterAppender. Thanks to Ben Sandee for submitting the relevant patch. Modified SMTPAppender to allow multiple email sessions. Thanks to Jon Skeet for supplying the relevant patch. The CategoryFactory class has been replaced by the LoggerFactory class. The makeNewCategoryInstance method has been renamed as makeNewLoggerInstance. This change requires subclasses of Category classes to be modified and recompiled. The Level class replaced the Priority class. Priority class now extends Level to preserve backward compatibility. The Logger class replaced the Category class. Logger class extends Category to preserve backward compatibility. We proudly mark this change with a single star for 100% compatibility. The Category.assert method has been replaced by Category.assertLog. This change was necessary because assert is a language reserved word in JDK 1.4. Removed deprecated methods setOptions and getOptionStrings defined in the org.apache.log4j.spi.OptionHandler interface. This interface is implemented by most log4j appenders and layouts. In particular, all appenders and layouts shipped with log4j contain these deprecated methods. They have become totally redundant after we moved to JavaBeans style configuration in log4j 1.1. The disable(Level) methods in Hierarchy have been removed and been replaced by threshold methods. Add buffered IO capability to FileAppender and subclasses. The location information (or stack information) was not correctly transmitted by JMSAppender. Add event reporting capability to the Hierarchy class. Add new system property "log4j.configuratorClass". This property allows the user to specify the custom configurator at the default initialization phase. This property replaces the previous interpretation of the reference part of "log4j.configuration" as the custom configurator class. This interpretation was sometimes erroneous and caused headaches. Introduced the Mapped Diagnostic Context or MDC class. This class is similar to the NDC except that the diagnostic context is based on a map instead of a stack. Moreover the MDC is automatically inherited by child threads under JDK 1.2 and above. Corrected a performance bug in the NDC class as observed by Dan Milstein and independently by Ray Millard. Removed deprecated methods disable(Priority), disableAll, disableDebug, disableInfo and enableAll in BasicConfigurator. Add supports java.io.Reader objects in the method doConfigure(), instead of only InputStream. Thanks to Mark Womack for submitting the relevant patch. Corrected the restart bug in DailyRollingFileAppender. Thanks to Jim Moore for supplying the relevant patch. Add a missing namespace declaration in the log4j:configuration element in log4j.dtd. The missing declaration caused the new generation of namespace aware parsers to barf when parsing log4j configuration files. Reduced the size of log4j-core.jar to 78KB. Minor documentation changes. Corrected a problem with the static initializer of the Category class which would use the wrong class loader to search for the default configuration file. The associated search algorithm has been also simplified. Nevertheless, the preferred method to specify the automatic configuration file is by setting the log4j.configuration system property. Documentation improvements. Added a new section to the manual explaining the default initialization procedure Enhancements to the org.apache.log4j.examples.appserver package. Corrected a bug in the way the NTEventLogAppender printed exceptions. Add missing custom priority support in PropertyConfigurator. Made a number of fields protected instead of default access in SMTPAppender. This release has the same code as 1.1b7. It differs only in a few minor documentation changes. Made BasicConfigurator disable methods static as they were in log4j 1.0.4. Thanks to Francisco Marin for reporting the bug. Corrected a two related deadlock problems introduced while fixing bug 1505. Thanks to joelr@viair.com for reporting the problem. The configureAndWatch methods in Configurators did not close the configuration file, preventing its editing. In DOMConfigurator.setParameter special character conversion now precedes variable substitution. This change was suggested by Steven Velez. The vast majority of users should be oblivious to it. The TextPaneAppender is no longer maintained and has been removed. It is still available under the contribs/ directory. This change has been discussed in the log4j mailing lists and no one objected to the removal of the TextPaneAppender class. Aaron Greenhouse from Carnegie Mellon SCS found a series of multi-threading related bugs in Category and AsyncAppender. See bug ids 1505 and 1507 in our bug database for exemplary bug reports. They are worth the detour. InvalidJarIndexException is only available in JDK 1.3. Referring to this exception type caused log4j 1.1b5 to break on earlier JDKs. We now avoid referring to it. Add PriorityRangeFilter by Simon Kitching. See the Threshold option in AppenderSkeleton for a more convenient alternative. In HTMLLayout, the Title option sets the HTML document title (<title>...<title>). Corrected an important performance bug in LocationInfo. Hein Couwet and kr@it-practice.dk have independently identified the bug. This is yet another example of the difference made by the number of eyeballs studying source code. Corrected the incorrect value returned by LocationInfo.getClassName method when running under IBM Visual Age. Thanks to Mathias Rupprecht for supplying the relevant patch. Corrected a bug where the build.sh file in the distribution would be in DOS CRLF format. Thanks to ma.darche@free.fr for reporting the problem. Corrected InvalidJarIndexException thrown in applets while searching for the default log4j configuration file. Thanks to Michael Lundahl for reporting this bug. Add missing PropertySetterException class to log4j-core.jar. Thanks to ma.darche@free.fr for reporting this bug. Mathias Bogaert observed that in version 1.1b3 the search algorithm for the resource used in automatic log4j configuration was different than in 1.0.x. Beta4 uses a more powerful mechanism which is also compatible with 1.0.x. Paul Glezen correctly observed that if log4j is deployed in a client/server mode where multiple log4j clients log to a log4j server, all hosts must be upgraded to version 1.1 in one go because the internal LoggingEvent class used in client/server communication changed in log4j 1.1. Add a RollingFileAppenderBeanInfo class that fakes the maxFileSize JavaBeans property as a String type instead of a long. This allows us to resuscitate setMaxFileSize(long) method that was removed in 1.1b2 breaking 100% backward compatibility. This addition restores 100% backward compatibility. The directory structure has changed to better suit Jakarta conventions Add a few jar files required at build time to build/lib so that it is now possible to compile log4j out of the box. Whenever a priority parameter is expected in a configuration file, one can now use a custom priority class. See OptionConverter.toPriority method for more information. Note that the <priority> element in log4j.dtd remains unaffected by this change. Add the setQuietMode(boolean) method to LogLog. In quiet mode LogLog will not output anything even in case of errors. Log4j components are now configured as JavaBeans. The setOption and getOptionString methods have been deprecated in OptionHandler interface which is implemented by most log4j components. The stack trace of a throwable passed in a logging statement is not parsed into a stack array which is serializable. This allows cascading of log4j servers to properly propagate throwable information. In XML configuration files, the <configuration> element has been deprecated and was replaced by the <log4j:configuration> element. The "log4j.configDebug" system property has been replaced with the "log4j.debug" system property although it is still available. Similarly, the "configDebug" attribute has been deprecated and replaced with the "debug" attribute in log4j.dtd. Logging can now be disabled per Hierarchy. It can also be disabled using configuration files using the "disable" directive. The "disableOverride" directive takes precedence over the "disable" directive. As a result of this change the disable family of methods in BasicConfigurator has been deprecated and replaced by the same family of methods in the Hierarchy class. The FileAppender has been split into three parts: WriterAppender, ConsoleAppender and FileAppender. ConsoleAppender takes over the console logging functionality of FileAppender. As a result support for stream and console printing has been deprecated in FileAppender. The FileAppender now correctly outputs the header and footer of its layout. This problem was reported by too many users to list here. Appenders and Layouts now get to see the raw message object in LoggingEvent not just its rendered form. The access modifiers of some LoggingEvent fields were changed so that they can be accessed in less error-prone ways. Thanks to Jim Cakalic and Anders Kristens for their valuable advice. Add getLayout(), getErrorHandler(), and getFilter() to the Appender interface. Add getOption(key) method to the OptionHandler interface and modified implementations of it as appropriate. Add the much awaited DailyRollingFileAppender. The structure of the distribution changed somewhat. The log4j.jar files can be found under dist/. The javadoc directory has been moved to docs/api/. We are now totally dependent on ANT to perform all the steps involved in creating a release, including compilation, jar file creation, generation of the javadocs, and for the creation of the distribution tar and zip files. Removed org/apache/log4j/varia/ResilientFileAppender.java which was bogus to begin with. XMLLayout will now mark some output as <![CDATA[ .. ]]> so that it does not get interpreted by the XML parser. This was suggested by Mathias Bogaert like a long list of other fixes. Corrected a bug in CyclicBuffer.resize method that would not update the next insertion point. Thanks to Ole Bulbuk for accurately reporting the bug. The LoggingEvent class now supports serialization of priorities derived from the org.apache.log4j.Priority class. Improved the search method for finding the "log4j.properties" file in the static initializer of Category class. Thanks to Calvin Chan for supplying a better method. The code handling the FCQN (formerly instanceFQN) parameter was cleaned up. There is now a well-established and simple manner for sub-classes of Category (or wrapper classes) to define the FCQN variable: just define a static variable, say FCQN, consisting of the fully qualified class name of the subclass or wrapper, supply this variable as an argument to forcedLog method if and when the sub-class or wrapper invokes that method. Made the instanceFCQN an instance variable instead of a class static in Category.java. In related move, the Category constructor now takes an additional argument setting the instanceFCQN. This makes life less miserable for Category subclasses. Corrected a bug in the OptionConverter.instantiateByClassName method that would not return the defaultValue in case of error. Thanks to Matthieu Verbert for identifying this bug. Corrected the missing stack trace in e-mails generated by the SMTPAppender when using certain Layouts. Updated the "Adding Conversion Characters to PatternLayout" document to reflect the latest changes to the code. Also added the org/apache/log4j/examples/appserver directory containing the associated example code. Add the BufferSize option to the AsyncAppender. Eliminated the SecurityExceptions thrown in Applets. Thanks Timur Zambalayev for reporting this bug. Fixed the erroneously thrown IOInterruptedException when the AsyncAppender was closed. Thanks to Tom Palmer for accurately reporting this bug. Corrected a serious bug in Hierarchy.java that would cause a NullPointerException depending on the order of instantiation of categories. Thanks to Wolfram Gewohn for reporting this bug. Corrected a bug in the getOptionsStrings method of SMTPAppender that omitted to mention the EvaluatorClass option. Thanks to Mark Balster for reporting this bug. Fixed a NullPointerException occurring in AsyncAppender after invoking Category.shutdown. Thanks to Frank-Olaf Lohmann for reporting this bug. Modified the OptionConverter.selectAndConfigure method to take an extra argument of type Hierarchy. This method is used internally and should not affect most users. Add the warn method to LogLog which is used internally by log4j to report on itself. Displaced a number of HTML files under the docs directory. The new structure is compatible with the jakarta site and results in a more consistent navigation experience. Made a few improvements in the javadocs. Add the missing build.inc file to the distribution. No code changed. This version corrects some documentation and build script bugs; code has not changed. Package hierarchy now starts at org.apache.log4j. Add the fatal() family of methods to the Category class. Moreover, the EMERG priority has been removed from the Priority class. This priority has been replaced by the FATAL priority that is more widely accepted. This change will require EMERG log statements to be replaced by FATAL log statements. Assuming EMERG log statements are rare, this should have a small but bearable impact on existing client code. Moreover, the Unix Syslog priorities ALERT, CRIT and NOTICE are no longer recognized. Support for these priorities was minimal and few users should suffer from these changes. Removed the methods setRootPriority, getRootPriority as these methods were redundant and had been previously deprecated. Removed the DOM Level 2 dependency in DOMConfigurator. This makes log4j XML configurable using Sun's parser or Apache's Xerces. The static initializer of the Category class now takes the log4j.configuration system property to search for its configuration file. The type of the configurator used to parse the configuration file depends on the value of the log4j.configuration system property. Enhanced the PropertyConfigurator and DOMConfigurator to support customisation of independent Hierarchy instances. The org.apache.log4j.net.SocketServer has been enhanced to take advantage of this functionality. The old code of SocketServer has been moved to SimpleSocketServer. Enhanced the PropertyConfigurator to support variable substitution for all options *values* (but not keys!). Categories are now aware of the Hierarchy they are linked to. This will provide a basis for several performance enhancements planned for the future. Add support for object rendering. It is now possible to register an object renderer for a given object type. When the given object needs to be logged log4j will invoke the corresponding renderer to transform the object into a String. As a result of this enhancement, all the String forms of all the printing methods such as debug(String), info(String) have been removed as they are no longer necessary. This change should be backward compatible but requires recompilation of old client code. Thanks to Michael Smith for noting the recompilation requirement. Add support for user defined category factories in the PropertyConfigurator. Thus, it is now possible to configure log4j with a properties file and still use custom Category sub-classes. The DOMConfigurator had already a finer grain support. Add the SMTPAppender that in case of an error or fatal event sends an e-mail containing latest N logging events in its buffer, where N is chosen by the user. Add the method getInstance(Class) to the Category class. Corrected a bug in configureAndWatch method of configurators that would configure log4j only after an unnecessary delay. Corrected a typo making NTEventLogAppender.dll register the wrong category message file. Thanks to Peter Hayes for accurately reporting this bug. The DOMConfigurator and PropertyConfigurator can now automatically detect modified configuration files and re-read them. Add AsyncAppender which buffers log requests and serves them at a later time. AsyncAppender can increase logging performance tremendously if logging operations are interspersed with long and blocking non CPU-intensive operations, typically I/O or network access. For CPU intensive applications, using the AsyncAppender will actualy degrade logging performance by 10 to 25 percent. The log4j.dtd has been modified to allow appenders to refer to other appenders by IDREF. The DOMConfigurator has been modified to take advantage of ID/IDREF attributes when referring to appenders. This change requires a DOM Level-2 API compliant parser. DOM Level-2 java bindings are available at http://www.w3.org/TR/1999/WD-DOM-Level-2-19990923/java-binding.html. Add the configure(String filename) method to DOMConfigurator. This method requires the presence of a JAXP compatible parser. At this time, the only DOM2 and JAXP compatible parser seems to be the Apache xerces parser. Add the PriorityMatchFilter allowing filtering by exact priority match. This was a common request by users. The configuration of a category is now an atomic operation. This ensures that log requests are not lost while configuration is in progress. Anders Kristensen was to first to observe the potential problems in non-atomic configurations. The "log4j" element has been renamed to "configuration" in the log4j DTD. This change requires that log4j configuration files written in XML be modified. Since the log4j element figures only once in the XML file, this change should take little time. ResourceBundles are now category instance specific and no longer class static. Moreover, like other properties resource bundles are inherited from the category hierarchy. The jar files log4j.jar and log4j-full.jar now contain versioning information in their respective manifest files. Corrected an inconsistency in the NTEventLogAppender which broke it. Fixed a bug where configuration files were not parsed correctely due to trailing spaces in option values as returned by java.util.Properties. Trailing spaces are now removed from option values. This bug was quite disconcerting because the trailing spaces cannot be seen without careful examination of the configuration file. Add the XMLLayout. The output of the XMLLayout consists of a series of log4j:event elements. It does not output a complete XML file. The output is designed to be included as an external entity to form a well-formed XML file. Add a new abstract class org.log4j.helpers.DateLayout. The TTCCLayout now extends DateLayout. Corrected a rather subtle performance bug in the buffer management code in PatternLayout. Thanks to Vladislav Dutov and Constantine A. Plotnikov for for insisting on the correction of this bug. Created a new package called org.log4j.spi. This new package holds classes that are hidden from the casual user but are needed to extend log4j. Add org.log4j.varia.ExternallyRolledFileAppender to handle externally triggered file rollovers. Add support for multiple hierarchy trees. PatternLayout can now be subclassed to support new conversion patterns. Extended the DOMConfigurator and the log4j DTD to properly handle sub-classing of Category and Priority classes. There have been also minor adjustments to other classes to handle sub-classing. These changes should be invisible to users. All categories except the root category can be sub-classed and also assigned priorities sub-classing org.log4j.Priority. The root category always exists and CANNOT be subclassed. The ProppertyConfigurator remains unchanged. Thus, it does not handle extensions of the Category class. Add filter support in appenders. The DOMConfigurator and the log4j.dtd have been enhanced to support filters. Add error handling support to appenders. The DOMConfigurator and the log4j.dtd have been enhanced to support filters. Add support for correct interpretation of location information in IBM's Visual Age environment. Thanks to Wolf Siberski for supplying the relevant patch. Add getAdditivity method to Category. This feature was requested by Constantin Mitran. (mitran at ecircle.de) Corrected multiple bugs in default initialization code of Category class. Thanks to Jeff Turner for identifying and supplying corrective patches. Add the %n conversion character to PatternLayout so that a line separator can be specified in a platform independent way. In 0.8.5 internal Priority integer values were decoupled from the Unix Syslog values. This broke SyslogAppedder. A new function Priority.toSyslogInt is introduced to solve this bug. Corrected a bug where the internal priority integer All log4j internal output is now prepended with the string "log4j: ". This makes is easier to differentiate log4j internal logs from messages output by other sources. Sub-classes of Category class must now specify their fully qualified name when constructing logging events. This allows the %C conversion specifier in PatternLayout to work properly even with sub-classes or wrappers of Category. Add the method disableDebug to BasicConfigurator. This method disables all print requests of debug priority regardless its category. Similar methods disableInfo, disable, disableAll and enableAll have also been added. Disable type methods can be overriden by setting the log4j.disableOverride system property. Calling BasicConfigurator.disableInfo is equivalent to the now deprecated flagAsShippedCode method. Given the above changes, the system property log4j.shippedCodeFlagOverride is no longer honored. It is now possible to sub-class Category. The sub-classes may continue to adhere to the category hierarchy. This was a frequently requested feature. Corrected a problem with the additivity flag being ignored in categories without appenders. This bug was discovered by Anders Kristensen. Add a method BasicConfigurator.resetConfiguration to reset the log4j environment. This method should be used sparingly. At the initialization of the Category class, the file log4j.properties will now be searched from the search path used to load classes. If the file can be found, then it is fed to the PropertyConfigurator.configure(java.net.URL) method. Failing to access system properties within the static initializer of BasicConfigurator class is no longer reported as an error but as a debug message. Thanks to Gilles Schlienger for reporting this problem with applets. Corrected a bug which caused infinite loops when using conversion patterns with a single element, fortunately under very rare circumstances. This bug was first reported by Igor Potraev, the author of log4p. It was independently reported by Joe Haberl from IBM Global Services. Add a mechanism to lazily remove references to dead threads in the NDC class. Indeed, in previous versions calling NDC.pop within a thread but forgetting to call to NDC.remove before exiting (that thread) resulted in a memory leak. Corrected a huge memory leak in SocketAppender. This leak was due to the ObjectOutputStream indefinitely holding a reference for each written to the stream. Thanks to Dan MacDonald for very accurately describing this bug. The log and l7dlog methods in Category no longer ignore the shipped code flag. This bug was reported by Mario Schomburg. Add missing NDC information to LoggingEvent.writeObject method. Corrected handling of SocketException in SocketNode. Thanks to Gerald Gutierez (ggutierez@emobiledata.com) for reporting this and the previous problem. Phased out custom shell scripts to build java documentation and jar files in favor of Jakarta's ANT. It was becoming a nuisance to keep the ANT build file in sync with the custom shell scripts. The NT EventViewer no longer complains about missing message 4096. Minor corrections in documentation. Add missing icons GIFs into the distribution. SocketNode now attempts to close the socket when exiting. Thanks to Moses Hohman (mmhohman@rainbow.uchicago.edu) for noting this. Removed the com.ibm.log4j from the javadoc directory. This seems to confuse VAJ. Thanks to Steve Ashcroft for reporting this problem. As a result of the infinite loop problem (see next item), added over 800 new test cases to stress-test the code in CategoryFactory class where category creation occurs. Under certain rare circumstances the Category.getInstance method entered an infinite loop. Thanks to Mario Schomburg from IBM Global Services / Hannover for identifying this problem and proposing a patch. DOMConfigurator and the log4j.dtd were out of sync on the type of the priority directive. As a result, priority directives all defaulted to DEBUG. Thanks to Peter (petervt@users.sourceforge.net) for accurately reporting this bug. Minor additions to the FAQ. Add the NumberCruncher example showing how the NDC class can be used to distinguish output from different clients. Add the %x conversion specifier to the TTCC_CONVERSION_PATTERN in the PatternLayout class. This is consistent expected output of Trivial.java example. Thanks to Jerome (schrom@users.sourceforge.net) for reporting this bug. The value of the additivity option would not be parsed properly by the ProperytConfigurator if the line containing the option contained trailing spaces. The localized logging methods (l7dlog) omitted priority based evaluation and erroneously logged all requests. The close method was added to the Appender interface allowing appender implementations to release any resources they may have allocated. The package naming scheme of changed from "com.ibm.log4j.*" to "org.log4j.*". The new naming reflects the open source nature of the project and is consistent with the URL http://www.log4j.org. Add internationalization support. See the newly introduced l7dlog methods in Category class. In the FileAppender, the File option now admits variable substitution. For example, if "java.home" system property is set to /home/xyz and the File option is given the value "%{java.home}/test.log", then File option will be interpreted as "/home/xyz/test.log". Thanks to Avy Sharell (sharell@online.fr) for contributing this feature. SocketAppender is now officially part of the package. It is capable of sending logging events to a remote SocketNode. The SocketNode logs events according to server (local) policy. For example, a client can log events to a local file and also send them to a remote server (a SocketNode). This server can log the event to any number of files, to the console, to any number of TextPaneAppenders and even re-transmit the event to another server, and so forth. This paradigm is common in most logging systems, e.g. Syslog and NT Event Log. Many thanks to Andrew Harrison for showing a way to actually implement the paradigm. The Category.callAppenders method now accepts a LoggingEvent instead of creating one itself. This was necessary to accommodate events generated at a remote client. LoggingEvent class changed slightly to support remote logging. The category field (a Category) has been replaced by the categoryName field (a String). Corrected a bug in Category.removeAppender(String) which would never remove the desired appender. Thanks to Moses Hohman for reporting this bug. Corrected a bug RollingFileAppender which would throw an uncaught exception in case output file could not be opened for writing. Thanks to Vinay Aggarwal for signaling this problem. The log4j.override key defined in BasicConfigurator has been renamed to log4j.shippedCodeFlagOverride. The getCurrentCategories method in the Category class would not return the correct value. Thanks to Timothy Potter (tpotter@agency.com) for reporting this problem. Appenders now admit a priority threshold as an option. All requests with a priority lower than the appender's threshold priority are ignored by the appender. Integrated Christopher Taylor's DOMConfigurator parsing XML configuration files. The jar file log4j-net.jar has been replaced by log4j-full.jar. It contains DOMConfigurator.class in addition to the com.ibm.log4j.net package. Add support for the ANT build tool. Thanks to Christopher Taylor for supplying the build.xml file. ANT is available form http://jakarta.apache.org. FileAppender's File option now accepts the values "System.out" or "System.err". If one these values is suppiled in a configuration file then the output is directed to the corresponding stream. Moreover, the default constructor of FileAppender no longer sets System.out as an output target nor does it define a default layout. Add caller class (C), caller file name (F), caller line number (L), caller method name (M) conversion specifiers to the PatternLayout class. The category conversion specifier now takes an optional precision modifier allowing the user to control the number of right most components in the category name that will be printed. Corrected a bug occuring when the caller file name and line number information were unavilable due to JIT compilation. In that case, the PatternLayout would not properly use the rest of the available location information. The above enhancements and bug-fixes originate from comments by Nelson Minar (nelson@monkey.org). The SimpleLayout and TTCCLayout are replaced by the PatternLayout in the log4j.jar file to keep its size small. These two layouts are still part of the package. The PatternLayout class is introduced. This new layout is configurable using a conversion pattern which is parsed at runtime. This allows the user to choose the output layout without writing any code and only at a marginal performance cost compared to the dedicated layouts such as SimpleLayout and TTCCLayout. The PatternLayout also allows the user to determine minimum and maximum field lengths. The PatternLayout was written by Jim Cakalic (jim_cakalic@na.biomerieux.com). All internal components now use LoggingEvent instances to specifiy logging information. Corrected a problem with a missing variable initialization in SyslogAppender. This caused NullPinterException to be thrown when logging exceptions. Added a default constructor to SyslogAppender. The lack of this constructor caused PropertyConfigurator to throw a java.lang.InstantiationException when the appender type was set to be SyslogAppender. Thanks to Yves Bossel (ybossel@opengets.cl) for accurately identifying these bugs. Modified some other related option handling code in SyslogAppender. Made NDC.get public access instead of default access. Thanks to Y. J. Chun (monac@softonnet.com) for reporting this problem. PropertyConfigurator now parses the additivity option for categories. Corrected the value of the ADDITIVITY_PREFIX constant to match the documented value, that is "log4j.additivity". Corrected a really bad bug where System.out would be closed when PropertyConfigurator.configure was called. Thanks to Christopher Taylor (cstaylor@pacbell.net) for tracking and reporting this bug. The PropertyConfiguator now prints debug messages if the flag "log4j.configDebug" is defined in the configuration file. Previously, only if the system property "log4j.configDebug" was set would debug messages be printed. A question by Shawn Kircher (skircher@vninet.com) induced this change. In AbsoluteTimeDateFormat, DateTimeDateFormat and ISO8601DateFormat the separator between the seconds and milliseconds has been changed to comma from full stop, in order to be compliant with ISO8601's preferred sign. Thanks to Jim Cakalic (jim_cakalic@na.biomerieux.com) for pointing out this discrepancy with the standard. Corrected a bug where RollingFileAppender would not work properly on Windows systems. Thanks to Heinz Richter (heinz.richter@ecmwf.int) for noting this problem. Core classes are now independent of the format of the options file. Configurable core classes implement the OptionHandler interface. OptionHandlers allows configurators to learn the relevant option names. The configurator feeds option values to the OptionHandler which configures itself. As a result of these changes, the Init class has been broken down to two separate classes: the BasicConfigurator and the PropertiesConfigurator. An XML configurator for 0.8.0 has been already written by Christopher Taylor (cstaylor@pacbell.net). Add multiple appender support per category. The appenders follow the category hierarchy, i.e. a child category inherits the appenders of its parents. Add an assert() method to the Category class. Steven Marcus (srnm@awaretechnologies.com) requested this addition. Automatic stack printing is no longer supported. This was an unused and unreliable feature which unnecessarily complicated the code. log4j now emits a single warning message when no appender to write to could be found. This is typically the case when the user forgets to configure the log4j environment. This change was suggested by Jim Cakalic (jim_cakalic@na.biomerieux.com). RollingFileAppender adds file roll over capability-implemented by Heinz Richter (heinz.richter@ecmwf.int). Corrected a bug where a java.lang.NoClassDefFoundError would be thrown because com.ibm.log4j.helpers.SyslogTracerPrintWriter was not included in log4j.jar. Thanks to Jim Cakalic (jim_cakalic@na.biomerieux.com) for signaling this bug. There has been an important API changes. The Log, NOPLog and ILog classes have been removed. Their functionality has been migrated to the Category class. In this release, instead of writing ILog.debug(CAT, "Some message."); one will write CAT.debug("Some message."); Arndt Schoenewald <arndt@ibm23093i821.mc.schoenewald.de> observed that one could use the Category objects directly for logging. It is no longer possible to instantiate Category objects directly. Instead, one would use the factory method Category.getInstance(String name). [***] There category instantiation code was moved to CateogryFactory class. This class has package visibility and remains hidden from the user. This stylistic improvement was suggested by Luke Blanshard (luke@quiq.com). The Init class offers methods to initialize the log4j environment. The Init.flagAsShippedCode method replaces the NOPLog class. Changes in the documentation to reflect the API changes. The NDC.cloneStack and inherit methods now tolerate null-stacks. TTCCLayout now takes a java.text.DateFormat object as a parameter. The task of formatting the date is delegated to this object. Added four classes extending the java.text.DateFormat class. These are RelativeTimeDateFormat, AbsoluteTimeDateFormat, DateTimeDateFormat and ISO8601DateFormat classes. Thanks to Arndt Schoenewald <arndt@ibm23093i821.mc.schoenewald.de> for suggesting the ISO8601 date format. These four classes can be parametrized with a particular TimeZone. The TTCCLayout class now accepts a new configuration file option called "TimeZone". These four DateFormats are less malleable than the java.text.SimpleDateFormat but they are also much faster. As a consequence of these changes, the setRelativeTime, setDatePrinting methods in TTCCLayout have been removed along with the associated configuration file options RelativeTime, DatePrinting and TimePrinting. The current code is inspired by code contributed by Heinz Richter (heinz.richter@ecmwf.int). The Log.emerg method has been deprecated. If you use statements of EMERG priority, please use the Log.log form instead. Add getDepth and setMaxdepth methods to the NDC class. This makes it easier to manage the nested context depth especially when callees push but forget to pop. Moved the documentation in com/ibm/log4j/package.html to com/ibm/log4j/overview.html. Many users were failing to read the com/ibm/log4j/package.html description due to the unfortunate layout of the text. Hopefully more people will read the package overview in its present location. Add the com.ibm.log4j.net package for doing remote logging using TCP sockets. This is still experimental code. Add new debug, .., emerg methods that do not require a category parameter. They assume the "root" category, that is the decision to whether print or not is made by comparing the statement's priority with the default priority. Add a new ILog.init method accepting an Appender and a configuration file as parameters. FileAppender's setWriter and setFile methods where not instantiating a new tracer. This caused stack traces to be lost! SyslogAppender had a similar problem. The FileAppender and SyslogAppender where not calling the layout's readConfig method to set layout specific options. Thanks to Heinz Richter (heinz.richter@ecmwf.int) for reporting this bug. Corrected a bug in Log.log() method where the appender was always called with Priority.DEBUG. Thanks to Oliver Boehm (Oliver.Boehm@abaxx.de) for reporting this bug. Add Syslog compatibility. One can now choose (at runtime) between remote syslog logging or file logging. Syslog logging performance, although not appalling, is significantly slower than file logging. Priority class was enriched with the previously missing priorities NOTICE, ALERT and CRIT. The internal constants were also aligned with the syslog counterparts. Add the Log.log method to support the new priorities. TracerPrintWriter is now an independent class instead of being a nested top-level class in Tracer. A number of writers, namely the SyslogWriter, SyslogQuietWriter, SyslogTracerPrintWriter, were added to the helper package. Log.force method was removed. The various Appender.doAppend implementations take over its functionality. FileAppender and SyslogAppender now use QuietWriter. QuietWriter is a FilterWriter which hides exceptions and instead emits a single warning message to System.err. The layout is now an initialization parameter to the appender type. Previously, the layout and the appender where independent parameters to the Log constructor. Many small improvements and corrections in the documentation. Syslog related documentation remains sparse. ILog.init() and ILog.init(String configFile) have been changed to call ILog.init(,,,) with "com.ibm.log4j.Log.class" as the first parameter. This makes it easier for people to get familiar with log4j. Add missing files to the make directory. These files are useful for those wishing to use the log4j make environment. Thanks to "Lee Hall" <LHall@JavaFoundry.com> for reporting this omission. Until recently the make environment failed to compile RMI stubs in a single run. This nagging problem has been corrected thanks to help from Thomas Eirich (IBM Zurich Research Lab). Some users have been rightly complaining about the verbosity TTCCLayout's date output. The full date output is now shortened to "dd MMM YYYY HH:mm:ss.SSS" for example, "06 Nov 1994 08:49:37.459" In addition, users may now choose to print only time information, as in "08:49:37.459". The package now uses Writer instead of OutputStream as its output target. This makes the log4j code smaller and easier to understand at the cost of a slight performance degradation. As a result of this change a few method names in FileAppender class were changed. Preliminary experiments with SyslogAppedner and SyslogLayout show that syslog compatibility is not far away. The difficultly is adding syslog compatibility without making radical changes to the current log4j architecture. Corrected a bug in the NOPLog.createInstance method which always created a Log singleton even if the system property "log4j.logType" was set to NOPLog. Thanks to Robert Gottofrey (Robert.Gottofrey@wdr.com) for reporting this bug and the associated test case. Removed the inconsistent "Layout" configuration option in Log.readConfig(). This change should be transparent to most users. The LogCreationManager class has been removed. Its functionality has been transfered to the createInstance and getInstance methods in the Log and NOPLog classes. The new way of creating instances is both simpler and less error prone although just as flexible. As a result of these changes, the init family of methods in the ILog class have been adjusted to the new way of creating the log singleton. The Appender interface has been introduced. The method of writing a log statement into an output stream can now be varied by using a different Appender. The new FileAppender offers the same functionality that was previously part of the Log class. Changed the time format used in TTCCLayout to be of the form "Day, dd MMM YYYY HH:mm:ss.SSS GMT" for example, "Sun, 06 Nov 1994 22:49:37.459 GMT". This format is almost the same as the format specified in RFC 1123 and also the format recommended in RFC 2616. The only difference is the additional milliseconds information. The layout specific options were not read from the configuration file due to a missing instruction. Many thanks to Vikram Sridharan (Vikram.Sridharan@alysis.com) to patiently pointing out this omission to an unbelieving maintainer. Version 0.7.0 and above will be distributed under the IBM Public License (IPL). The IPL is an approved open source license (see http://www.opensource.org/licenses/ for a list). It grants similar rights to the previous ALPHAWORKS license agreement, in particular, the right to redistribute and to modify the package. The Log class can now be parameterized with a Layout object. Layouts determine the format of what is printed, where as the Log class decides when to print and to where. As a result of this modularization, the CGULog and NOPCGULog classes no longer exists. CGULog class has been replaced with the TTCCLayout (Time Thread Context Category). This should make it easier to create new log output formats. Some time in the near future, the Log class will be further broken down to allow different strategies for writing to output streams. Renamed com.ibm.util.log hierarchy to to com.ibm.log4j. I wanted to do this for some time. I feel release 0.7.0 was the last opportunity to do so. I am sorry for the the trouble caused by this change. New NDC class. This class implements nested diagnostic contexts as suggested by Neil Harrison in the article "Patterns for Logging Diagnostic Messages" part of the book "Pattern Languages of Program Design 3" edited by Martin et al. Nested diagnostic contexts is a nifty feature that was missing up to now. The StressNDC test class seems to break JDK 1.2.2 beta on AIX. On Linux and NT using sun's JDK 1.2.2 it seem to work OK. In any case, tests done with StressNDC and associated perl script seem to indicate that the NDC class is bug-free. Corrected a date formatting bug in CGULog class where on some environments the wrong month was printed. Thanks to Christopher Williams (Christopher_Williams@mail.northgrum.com) for signaling this bug. Also changed the month format from a number to a three letter abbreviation such as "Jan", "Feb", ..., "Dec". The new format is unambiguous regardless of local date format. Clearer documentation with still much room for improvement. Corrected a bug in the Tracer class which always used the Unix line separator instead of the system specific separator. Thanks to Vikram Sridharan (Vikram.Sridharan@alysis.com) for singaling this bug. Corrected a runaway comment which gulped the CGULog.readConfig method. Add the init family of methods to the ILog class to ease the setup of a basic logging environment. Thanks to Mark Donszelmann (Mark.Donszelmann@cern.ch) for this enhancement. Just an hour after releasing version 0.6.1 detected and corrected a bug where the Tracer class would correctly print Exception stack trace but not the type of the Exception. Replaced the distribution on www.zurich.ibm.com without changing the version number. I hope nobody is using the intermediary (and buggy) release of 0.6.1. Better documentation with still much room for improvement. For consistence sake, added setDefaultPriority and getDefaultPriority methods to the Category class and deprecated setDefaultPriority in the Log.class. Corrected a major bug where if two categories were homonyms the second instance would not be properly initialized. Increased the speed of Exception logging from about 4000 microseconds to about 1000. It seems that for some people Exception logging is performance critical. Improved implementation is a variant of Nocolai's (XNH@crisplant.com) implementation. Release of log4j 0.6.0 with incomplete documentation. Add a stress test program to debug the new Category class. It turns out that the test program was as hard to get right as the Category class. Given the favorable results of the stress test I am quite confident that the new class is now bug free. This assumption has been proven to be wrong. See above. Created a new class called Category to manipulate categories instead of plain Strings. The new class is just as easy to use. However, the evaluation of whether to log or not to log is at least 10 times faster. The NOP class performance remain unaffected by the change. (You can't improve on the performance of an empty function call.) Many thanks to Alex Blewitt "Alex.Blewitt@ioshq.com" for his valuable comments. He was the first to observe that finding Strings in a hash table was an expensive operation. This change will require some recoding on your part. See the FAQ for more details. Modified the force in Log and CGULog method to use a byte[] buffer instead of a StringBuffer. The old code was clearer but the new one is at least 25% faster. Add regression testing. We now enforce a policy where the OutputStream set by setOutputStream is a user managed resource whereas the OutputStream opened using setLogFile is the Log class' responsibility. The setLogFile method now closes any previous OutputStream if only if opened through setLogFile. If the previous OutputStream was opened by the user and set through setOutputStream the previous OutputStream is untouched. Similarly, setOutputStream will close any previous OutputStream if and only if it was opened using setLogFile. Add a new method logOutputStreamExists to the Log class allowing the programmer to check if there is already an opened stream before trying to set a new one. A stream can be opened as a byproduct of reading the configuration file. Changed the behavior of the (private) Log.Append method in case of failure to write to the OutputStream. Previously, in case of failure, we reverted to System.err. Now, we emit a warning message and discard all future log messages. The new behavior is consistent with our current unreliable logging semantics. The change prevents an otherwise functional program from failing because the terminal is flooded with logging messages. Renamed the iLog to ILog to remain consistent with our class naming scheme. The initial intention was to add ILog and deprecate iLog. However, I am running CVS on a fat16 partition, causing serious problems when files differ only in case. Corrected a bug where the LogFileName was not remembered. Thanks to Jens for signaling this bug. Now the programmer can choose to truncate the log file instead of always appending to it. This functionality was first requested and intially implemented by "Jens Uwe Pipka" jens.pipka@gmx.de. setLogFile now opens the requested file instead of having the Append function open it later. Cleaned up some related code in the Append function. Although nobody has requested it, there is still no method to close the log file. This is harder to implement reliably than it sounds. Simplified setLogOutputStream so that it does no longer return the previously set OutputStream. Joe Walker (joe@eireneh.com) observed that the LogCreationManager.getSingleton mechanism was cumbersome. There is now a new class iLog (indirect Log) which hides the need to call getSingleton. Performance testing on my 233Mhz Thinkpad shows that this indirection has small performance impact on non-logged calls in the order of 40 nanoseconds. The impact on logged calls is negligible. Add a jar file to the distribution. The jar file contains only the files you would need to use log but not other classes needed for testing nor examples. Corrected a bug where CGUNOPLog was not integrated to the Makefile. Add new public methods isDebugEnabled and isInfoEnabled to allow programmers to check whether a debug/info statement will be logged without incurring the cost of message parameter construction. This addition was suggested by Luke Blanshard Luke@quiq.com. Renamed the private method evaluate to isEnabled. Also made it final with no apparent speed gains. In addition, made the Log.force method public. New syntactic sugar debug, ..., emerg, methods to log objects. Modified the interface to deal with Throwables and not just Exceptions. My thanks to Luke Blanshard for signaling this "bug". Add more tests to the LogPerformance class. In particular, to test the influence of indirect debug calls. Add a "make" mini-tutorial for those who want to modify the code. License updated to standard alphaWorks license allowing modifications to source code. However, this license explicitly requires that modifications be communicated back to alphaWorks. Initial availability on alphaWorks. Refer to the FAQ for the lineage of the package. apache-log4j1.2-1.2.17.orig/src/performance/0000755000175000017500000000000011751454703017063 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/performance/java/0000755000175000017500000000000011751454703020004 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/performance/java/org/0000755000175000017500000000000011751454703020573 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/0000755000175000017500000000000011751454703022014 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/0000755000175000017500000000000011751454703023033 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/0000755000175000017500000000000012126647422025333 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/package.html0000644000175000017500000000232611751454704027621 0ustar tonytony

Package to measure the performance of the different log4j components.

The org.apache.log4j.performance package is intended for internal use only. Consequently, the classes in this package are not included in the log4j.jar file.

apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/NOPWriter.java0000644000175000017500000000351011751454704030030 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.performance; import java.io.Writer; import java.io.IOException; /** *

Extends {@link Writer} with methods that return immediately * without doing anything. This class is used to measure the cost of * constructing a log message but not actually writing to any device. *

*

The * org.apache.log4j.performance.NOPWriter class is * intended for internal use only. Consequently, it is not * included in the log4j.jar file.

* * @author Ceki Gülcü * */ public class NOPWriter extends Writer { public void write(char[] cbuf) throws IOException {} public void write(char[] cbuf, int off, int len) throws IOException {} public void write(int b) throws IOException {} public void write(String s) throws IOException {} public void write(String s, int off, int len) throws IOException {} public void flush() throws IOException { } public void close() throws IOException { System.err.println("Close called."); } } apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/NullAppender.java0000644000175000017500000000347111751454704030576 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.performance; import org.apache.log4j.Layout; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.AppenderSkeleton; /** * A bogus appender which calls the format method of its layout object * but does not write the result anywhere. * *

The * org.apache.log4j.performance.NullAppender class is * intended for internal use only. Consequently, it is not * included in the log4j.jar file.

* */ public class NullAppender extends AppenderSkeleton { public static String s; public String t; public NullAppender() {} public NullAppender(Layout layout) { this.layout = layout; } public void close() {} public void doAppend(LoggingEvent event) { if(layout != null) { t = layout.format(event); s = t; } } public void append(LoggingEvent event) { } /** This is a bogus appender but it still uses a layout. */ public boolean requiresLayout() { return true; } } apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/NewVsSetLen.java0000644000175000017500000001337511751454704030366 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.performance; /** This program compares the cost of creating a new StringBuffer and converting it to a String versus keeping the same StringBuffer, setting its size to zero and then converting it to String.

The table below gives some figures.

Total Message length 0 1 2 4 8
New Buffer setLength New Buffer setLength New Buffer setLength New Buffer setLength New Buffer setLength
256 33 22 34 22 34 22 34 22 33 23
1024 58 41 59 45 59 48 59 51 60 44
4096 146 132 138 132 144 126 142 132 136 132
16384 617 593 593 609 601 617 601 632 593 632
65536 3218 3281 3093 3125 3125 3156 3125 3281 3062 3562
262144 14750 15125 14000 15500 14000 16125 14000 18000 14000 21375
1048576 87500 80000 60500 82000 57000 93000 57500 118500 57500 168500
Performance comparisons of new buffer creation versus setLength(0) approach for various message sizes and secondary loop lengths.

The tests copy a message to a destination string buffer and then copy a 256 character buffer to another buffer the number of times as specified by the secondary loop length.

The setLength(0) method is usually faster. However, after copying a large string it becomes slow even when copying small strings.

This is due to a peculiarity in the copy method in StringBuffer class which creates a character array of the same length as the old buffer even if the vast majority of those characters are unused.

The tests were performed on Linux using IBM's JDK 1.1.8.

The test script is a crude model of what might happen in reality. If you remain unconvinced of its results, then please send your alternative measurement scenario. */ public class NewVsSetLen { static String s; static int BIGBUF_LEN = 1048576; static int SBUF_LEN = 256; static int RUN_LENGTH = BIGBUF_LEN/4; static char[] sbuf = new char[SBUF_LEN]; static char[] bigbuf = new char[BIGBUF_LEN]; { for(int i = 0; i < SBUF_LEN; i++) { sbuf[i] = (char) (i); } for(int i = 0; i < BIGBUF_LEN; i++) { bigbuf[i] = (char) (i); } } static public void main(String[] args) { int t; for(int len = SBUF_LEN; len <= BIGBUF_LEN; len*=4, RUN_LENGTH /= 4) { System.out.println(""+len+"\n"); for(int second = 0; second < 16;) { System.out.println("SECOND loop="+second +", RUN_LENGTH=" +RUN_LENGTH+", len="+len); t = (int)newBuffer(len, second); System.out.print("" + t); t = (int)setLen(len, second); System.out.println(" " + t + " \n"); if(second == 0) { second = 1; } else { second *= 2; } } } } static double newBuffer(int size, int second) { long before = System.currentTimeMillis(); for(int i = 0; i < RUN_LENGTH; i++) { StringBuffer buf = new StringBuffer(SBUF_LEN); buf.append(sbuf, 0, sbuf.length); buf.append(bigbuf, 0, size); s = buf.toString(); } for(int x = 0; x < second; x++) { StringBuffer buf = new StringBuffer(SBUF_LEN); buf.append(sbuf, 0, SBUF_LEN); s = buf.toString(); } return (System.currentTimeMillis() - before)*1000.0/RUN_LENGTH; } static double setLen(int size, int second) { long before = System.currentTimeMillis(); StringBuffer buf = new StringBuffer(SBUF_LEN); for(int i = 0; i < RUN_LENGTH; i++) { buf.append(sbuf, 0, sbuf.length); buf.append(bigbuf, 0, size); s = buf.toString(); buf.setLength(0); } for(int x = 0; x < second; x++) { buf.append(sbuf, 0, SBUF_LEN); s = buf.toString(); buf.setLength(0); } return (System.currentTimeMillis() - before)*1000.0/RUN_LENGTH; } } apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/ListVsVector.java0000644000175000017500000000471511751454704030616 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.performance; import java.util.Vector; /** Compares the performance of looping through a list versus a Vector. Chain looping is *20* times faster than vector access on JDK 1.1.7B on NT */ public class ListVsVector { static int RUN_LENGTH = 1000000; static Vector v = new Vector(); static Chain head; static String tmp; static public void main(String[] args) { v.addElement("aaa"); v.addElement("bbb"); v.addElement("ccc"); v.addElement("ddd"); v.addElement("eee"); Chain c = new Chain("aaa"); head = c; c.next = new Chain("bbb"); c = c.next; c.next = new Chain("ccc"); c = c.next; c.next = new Chain("ddd"); c = c.next; c.next = new Chain("eee"); double t; t = loopChain(); System.out.println("Looping thourgh the chain took " + t); t = loopVector(); System.out.println("Looping thourgh the vector took " + t); } static double loopChain() { long before = System.currentTimeMillis(); Chain c; for(int i = 0; i < RUN_LENGTH; i++) { c = head; while(c != null) { tmp = c.s; c = c.next; } } return (System.currentTimeMillis() - before)*1000.0/RUN_LENGTH; } static double loopVector() { long before = System.currentTimeMillis(); int size = v.size(); for(int i = 0; i < RUN_LENGTH; i++) { for(int j = 0; j < size; j++) tmp = (String) v.elementAt(j); } return (System.currentTimeMillis() - before)*1000.0/RUN_LENGTH; } static class Chain { public String s; public Chain next; Chain(String s) { this.s = s; } void setNext(Chain c) { next = c; } } } apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/0000755000175000017500000000000012126647422026133 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging305.xml0000644000175000017500000000322311751454703030534 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging13.xml0000644000175000017500000000322711751454703030454 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging8.xml0000644000175000017500000000324611751454703030401 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging207.xml0000644000175000017500000000267111751454703030543 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging101.xml0000644000175000017500000000271211751454703030530 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging205.xml0000644000175000017500000000272411751454703030540 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging10.xml0000644000175000017500000000327511751454703030454 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging206.xml0000644000175000017500000000274411751454703030543 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging104.xml0000644000175000017500000000267611751454703030544 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging302.xml0000644000175000017500000000304111751454703030527 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging102.xml0000644000175000017500000000265111751454703030533 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging220.xml0000644000175000017500000000265211751454703030535 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging1.xml0000644000175000017500000000264111751454703030370 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging301.xml0000644000175000017500000000317211751454703030533 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging203.xml0000644000175000017500000000270711751454703030537 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging225.xml0000644000175000017500000000300011751454703030526 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging9.xml0000644000175000017500000000313711751454703030401 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging107.xml0000644000175000017500000000271211751454703030536 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging226.xml0000644000175000017500000000302011751454703030531 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging204.xml0000644000175000017500000000265711751454703030544 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging2.xml0000644000175000017500000000316611751454703030374 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging12.xml0000644000175000017500000000321311751454703030446 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging103.xml0000644000175000017500000000272711751454703030540 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging307.xml0000644000175000017500000000317211751454703030541 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging1000.xml0000644000175000017500000000256111751454703030611 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging300.xml0000644000175000017500000000304111751454703030525 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging100.xml0000644000175000017500000000256111751454703030531 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging306.xml0000644000175000017500000000324411751454703030540 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging11.xml0000644000175000017500000000333611751454703030453 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging6.xml0000644000175000017500000000326211751454703030375 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging303.xml0000644000175000017500000000320711751454703030534 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging222.xml0000644000175000017500000000273211751454703030536 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging202.xml0000644000175000017500000000265611751454703030541 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging200.xml0000644000175000017500000000265011751454703030531 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging227.xml0000644000175000017500000000274511751454703030547 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging304.xml0000644000175000017500000000315611751454703030540 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging201.xml0000644000175000017500000000267211751454703030536 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging7.xml0000644000175000017500000000326211751454703030376 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging105.xml0000644000175000017500000000274311751454703030540 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging106.xml0000644000175000017500000000276311751454703030543 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging221.xml0000644000175000017500000000274611751454703030542 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging224.xml0000644000175000017500000000273311751454703030541 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging5.xml0000644000175000017500000000326211751454703030374 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging223.xml0000644000175000017500000000276311751454703030543 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging3.xml0000644000175000017500000000317211751454703030372 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/xml/logging4.xml0000644000175000017500000000253011751454703030370 0ustar tonytony apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/history/0000755000175000017500000000000012126647422027034 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/history/GIL.logging0000644000175000017500000000405311751454704031023 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ GIL is a AMD Duron running at 800 MHz running W2000 and Sun's JDK 1.3. NullAppender: 4 SimpleLayout 4 PatternLayout "%p - %m%n" 4 PatternLayout "%-5p - %m%n" 10 TTCCLayout/RELATIVE 10 PatternLayout "%r [%t] %-5p %c{2} %x - %m%n" 10 PatternLayout "%r [%t] %-5p %.10c %x - %m%n" 10 PatternLayout "%r [%t] %-5p %.20c %x - %m%n" 9 PatternLayout "%r [%t] %-5p %c - %m%n" 25 TTCCLayout/ISO8601 28 PatternLayout "%d{ISO8601} [%t] %-5p %c %x - %m%n" 58 PatternLayout "%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %-5p %c %x - %m%n" 1309 PatternLayout "%l - %m%n" 1379 PatternLayout "%C.%M.%L - %m%n" FileAppender: 26 SimpleLayout 28 PatternLayout "%p - %m%n" 47 TTCC/RELATIVE 46 PatternLayout "%r [%t] %-5p %c %x - %m%n" 70 TTCCLayout/ISO8601 75 PatternLayout "%d{ISO8601} [%t] %-5p %c %x - %m%n" 99 PatternLayout "%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %-5p %c %x - %m%n" 1524 PatternLayout "%l - %m%n" FileAppender: (ImmediateFlush=false) 20 SimpleLayout 21 PatternLayout "%p - %m%n" 38 TTCC/RELATIVE 38 PatternLayout "%r [%t] %-5p %c %x - %m%n" 62 TTCCLayout/ISO8601 67 PatternLayout "%d{ISO8601} [%t] %-5p %c %x - %m%n" 86 PatternLayout "%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %-5p %c %x - %m%n" Notice the small but noticable performance gain when forgoing immediate flush. ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootapache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/history/FALKNIS.loggingapache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/history/FALKNIS.loggin0000644000175000017500000001314511751454704031332 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ All tests done with java version "1.2.2" Classic VM (J2RE 1.2.2 IBM build cadev-19991008 (JIT enabled: jitc)) -------------- Wed Dec 8 20:55:19 MET 1999 --------------- Logging to a real file. Results: 516 525 - average 520 (basic) Results: 657 655 - average 656 (cgu) Logging to a null (nop) output stream. Results: 63 61 - average 62 (basic) Results: 155 144 - average 149 (cgu) Logging with stack info to a regular file. Results: 2991 2999 - average 2995 (basic) Results: 5174 5260 - average 5217 (cgu) Logging with stack info to a null (nop) output stream. Results: 779 780 - average 779 (basic) Results: 2716 2876 - average 2796 (cgu) Result with the DateFormat line in CGULog.java: static private final java.text.DateFormat __DATETIME_FORMAT = new java.text.SimpleDateFormat("[HH:mm:ss:SSS z] dd.MM.yy"); -------------- Wed Dec 8 20:59:25 MET 1999 --------------- Logging to a real file. Results: 517 526 - average 521 (basic) Results: 720 656 - average 688 (cgu) Logging to a null (nop) output stream. Results: 61 63 - average 62 (basic) Results: 173 171 - average 172 (cgu) Logging with stack info to a regular file. Results: 3034 3048 - average 3041 (basic) Results: 5125 4603 - average 4864 (cgu) Logging with stack info to a null (nop) output stream. Results: 793 929 - average 861 (basic) -------------- Mon Jan 3 17:17:53 MET 2000 --------------- Logging to Writer instead of OutputStrem Logging to a real file. Results: 453 433 432 440 433 436 438 437 437 471 - average 441 (simple) Results: 611 588 587 619 595 585 596 590 639 600 - average 601 (ttcc) Logging to a null (nop) output stream. Results: 34 29 29 27 29 28 30 27 29 28 - average 29 (simple) Results: 87 112 89 87 86 87 86 87 86 86 - average 89 (ttcc) Logging with stack info to a regular file. Results: 1806 1786 1808 1807 1816 1862 1818 1808 1825 - average 1816 (simple) Results: 2391 2196 2170 2229 2206 2191 2183 2181 2244 - average 2221 (ttcc) Logging with stack info to a null (nop) output stream. Results: 763 767 806 772 769 758 756 756 768 - average 768 (simple) Results: 1046 1067 1095 1042 1037 1034 1058 1082 1057 - average 1058 (ttcc) -------------- Thu Jan 13 15:08:27 MET 2000 --------------- Using 0.7.3 style appender.doAppend method Logging to a real file. Results: 436 484 438 443 449 448 440 444 - average 447 (simple) Results: 665 616 598 596 604 588 603 593 - average 607 (ttcc) Logging to a null (nop) output stream. Results: 24 24 24 23 24 24 27 24 - average 24 (simple) Results: 81 83 81 81 82 80 80 81 - average 81 (ttcc) Logging with stack info to a regular file. Results: 1434 1392 1578 1430 1413 1409 1410 1409 - average 1434 (simple) Results: 1769 1801 1886 1783 1790 1754 1763 1771 - average 1789 (ttcc) Logging with stack info to a null (nop) output stream. Results: 726 710 721 695 707 699 707 710 - average 709 (simple) Results: 961 963 966 933 932 930 932 945 - average 945 (ttcc) -------------- Fri Jan 21 19:05:34 MET 2000 --------------- 0.7.4 performance, JDK 1.2.2 GA Logging to a real file. Results: 436 432 479 451 457 454 436 434 - average 447 simple Results: 597 632 585 589 587 593 586 593 - average 595 ttcc/RelTime Results: 729 745 744 738 782 748 730 765 - average 747 ttcc/AbsTime Results: 765 832 767 772 763 762 778 770 - average 776 ttcc/Date Logging to a NOPWriter. Results: 17 18 18 17 17 18 18 17 - average 17 simple Results: 71 80 68 68 68 69 71 68 - average 70 ttcc/RelTime Results: 165 166 166 168 167 163 164 167 - average 165 ttcc/AbsTime Results: 176 179 175 178 179 180 175 176 - average 177 ttcc/Date Logging with stack info to a regular file. Results: 1403 1408 1399 1405 1406 1390 1399 1515 - average 1415 simple Results: 1697 1811 1676 1591 1631 1599 1616 1613 - average 1654 ttcc/RelTime Logging with stack info to a NOPWriter. Results: 599 597 604 595 605 596 597 616 - average 601 simple Results: 780 764 767 775 765 758 752 765 - average 765 ttcc/RelTime -------------- Fri Jan 21 19:29:31 MET 2000 --------------- static Date object Logging to a real file. Results: 467 437 442 442 433 453 438 435 - average 443 simple Results: 580 583 588 621 586 579 592 585 - average 589 ttcc/RelTime Results: 737 773 731 734 732 740 762 734 - average 742 ttcc/AbsTime Results: 755 755 760 805 757 752 770 766 - average 765 ttcc/Date Logging to a NOPWriter. Results: 11 11 12 12 11 11 11 11 - average 11 simple Results: 51 53 51 52 51 52 51 51 - average 51 ttcc/RelTime Results: 97 95 95 95 97 98 98 96 - average 96 ttcc/AbsTime Results: 113 112 113 113 113 110 114 115 - average 112 ttcc/Date Logging with stack info to a regular file. Results: 1391 1426 1410 1403 1454 1471 1475 1470 - average 1437 simple Results: 1620 1627 1631 1615 1601 1606 1598 1802 - average 1637 ttcc/RelTime Logging with stack info to a NOPWriter. Results: 598 629 609 605 595 602 599 608 - average 605 simple Results: 759 765 743 757 758 747 773 756 - average 757 ttcc/RelTime apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/history/NAPOLI.logging0000644000175000017500000002421011751454704031367 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ All tests are done using Suns's 1.1.7U JDK on NT -------------- Sometime in 1999 --------------- Using OutputStream. Results: - average 79 (simple) Results: - average 164 (ttcc) Logging to a null (nop) output stream. Results: - average 56 (simple) Results: - average 131 (ttcc) Logging with stack info to a regular file. Results: - average 1064 (simple) Results: - average 1355 (ttcc) Logging with stack info to a null (nop) output stream. Results: - average 1002 (simple) Results: - average 1272 (ttcc) -------------- Mon Jan 3 17:30:21 2000 --------------- Using Writer instead of OutputStream. Results: 111 98 97 101 106 107 117 100 146 116 - average 109 (simple) Results: 200 175 175 169 206 214 185 172 173 196 - average 186 (ttcc) Logging to a null (nop) output stream. Results: 23 23 25 28 24 23 23 23 23 23 - average 23 (simple) Results: 67 66 64 65 75 65 66 64 65 64 - average 66 (ttcc) Logging with stack info to a regular file. Results: 981 986 1051 1021 1016 986 976 991 976 1021 - average 1000 (simple) Results: 1136 1136 1126 1131 1136 1151 1131 1126 1136 1137 - average 1134 Logging with stack info to a null (nop) output stream. Results: 791 786 821 781 776 791 776 776 781 781 - average 786 (simple) Results: 911 901 901 896 906 943 906 966 901 906 - average 913 (ttcc) -------------- Thu Jan 13 18:31:46 2000 --------------- Using v0.7.3 FileAppender.doAppend Results: 105 95 91 93 92 94 96 96 - average 95 (simple) Results: 172 200 165 174 182 168 165 165 - average 173 (ttcc) Logging to a null (nop) output stream. Results: 22 22 26 22 22 21 24 22 - average 22 (simple) Results: 65 64 66 64 64 64 65 65 - average 64 (ttcc) Logging with stack info to a regular file. Results: 831 921 836 841 836 831 831 841 - average 846 (simple) Results: 1051 981 981 976 981 991 981 1026 - average 996 (ttcc) Logging with stack info to a null (nop) output stream. Results: 726 721 716 721 716 721 716 791 - average 728 (simple) Results: 841 841 841 841 841 841 841 841 - average 841 (ttcc) -------------- Fri Jan 14 15:12:11 2000 --------------- Using v0.7.3 FileAppender.doAppend and the FilterWriter based architecture Logging to a real file. Results: 96 94 96 95 99 96 92 94 - average 95 (simple) Results: 178 168 167 205 168 174 172 173 - average 175 (ttcc) Logging to a null (nop) output stream. Results: 28 22 21 22 25 21 22 24 - average 23 (simple) Results: 67 73 65 64 64 64 64 64 - average 65 (ttcc) Logging with stack info to a regular file. Results: 961 831 846 831 841 831 836 866 - average 855 (simple) Results: 981 976 1001 971 1242 981 1051 981 - average 1023 (ttcc) Logging with stack info to a null (nop) output stream. Results: 726 716 716 716 716 716 741 731 - average 722 (simple) Results: 846 841 841 841 841 866 841 841 - average 844 (ttcc) Note: only stack printing performance is affected. -------------- Fri Jan 21 20:42:03 2000 --------------- release 0.7.4 Logging to a real file. Results: 90 94 92 90 92 91 88 92 - average 91 simple Results: 172 161 162 166 165 165 179 164 - average 166 ttcc/RelTime Results: 206 207 211 212 221 214 225 206 - average 212 ttcc/AbsTime Results: 228 236 239 234 233 231 229 240 - average 233 ttcc/Date Logging to a NOPWriter. Results: 21 21 20 20 20 20 20 20 - average 20 simple Results: 60 60 60 60 60 60 60 60 - average 60 ttcc/RelTime Results: 96 96 96 96 96 96 96 96 - average 96 ttcc/AbsTime Results: 111 111 112 111 112 108 111 112 - average 111 ttcc/Date Logging with stack info to a regular file. Results: 1091 1106 1092 1096 1096 1086 1106 1091 - average 1095 simple Results: 1256 1242 1257 1251 1246 1267 1251 1256 - average 1253 ttcc/RelTime Logging with stack info to a NOPWriter. Results: 866 871 856 856 846 851 846 846 - average 854 simple Results: 996 986 991 986 996 996 991 986 - average 991 ttcc/RelTime -------------- Fri Jan 21 20:26:43 2000 --------------- 0.7.4 + static Date Logging to a real file. Results: 93 97 92 91 100 91 95 95 - average 94 simple Results: 170 177 179 195 214 176 188 167 - average 183 ttcc/RelTime Results: 215 214 218 212 211 215 217 224 - average 215 ttcc/AbsTime Results: 296 274 234 235 230 237 232 231 - average 246 ttcc/Date Logging to a NOPWriter. Results: 21 21 20 20 22 20 20 20 - average 20 simple Results: 60 60 60 60 60 60 60 60 - average 60 ttcc/RelTime Results: 94 93 94 93 93 94 93 93 - average 93 ttcc/AbsTime Results: 106 105 106 106 106 106 106 105 - average 105 ttcc/Date Logging with stack info to a regular file. Results: 1096 1091 1096 1087 1106 1091 1101 1091 - average 1094 simple Results: 1211 1216 1212 1217 1211 1221 1216 1217 - average 1215 ttcc/RelTime Logging with stack info to a NOPWriter. Results: 866 866 861 851 846 856 851 856 - average 856 simple Results: 956 981 966 966 956 961 961 961 - average 963 ttcc/RelTime The static date version is faster by at least 3 microsecs. -------------- Sat Jan 22 16:54:35 2000 --------------- static Date in DateFormat and static StringBuffer in TTCCLayout Logging to a real file. Results: 92 90 92 93 93 91 89 97 - average 92 simple Results: 159 161 167 160 159 161 164 159 - average 161 ttcc/RelTime Results: 206 205 205 203 213 207 224 204 - average 208 ttcc/AbsTime Results: 220 232 229 231 236 228 231 231 - average 229 ttcc/Date Logging to a NOPWriter. Results: 21 21 20 20 20 20 20 20 - average 20 simple Results: 55 55 55 55 55 55 55 55 - average 55 ttcc/RelTime Results: 88 88 87 89 88 92 90 87 - average 88 ttcc/AbsTime Results: 101 102 101 101 102 102 106 106 - average 102 ttcc/Date Logging with stack info to a regular file. Results: 1101 1096 1111 1106 1112 1097 1101 1101 - average 1103 simple Results: 1217 1212 1221 1271 1227 1217 1226 1216 - average 1225 ttcc/RelTime Logging with stack info to a NOPWriter. Results: 876 866 866 846 856 851 851 851 - average 857 simple Results: 961 961 961 956 961 961 951 961 - average 959 ttcc/RelTime ------------------------------------------------------- 227 using sockets and byte buffers -------------- Sat Jan 29 14:34:19 2000 --------------- Using DateFormat extensions in TTCCLayout. Logging to a real file. Results: 177 170 173 171 185 188 176 176 - average 177 ttcc/RelTime Results: 206 200 202 203 207 208 201 202 - average 203 ttcc/AbsTime Results: 234 240 245 236 238 236 246 269 - average 243 ttcc/DateTime Logging to a NOPWriter. Results: 57 57 57 57 - average 57 ttcc/RelTime Results: 86 84 85 85 - average 85 ttcc/AbsTime Results: 113 112 112 112 - average 112 ttcc/DateTime Logging with stack info to a regular file. Results: 1111 1116 1116 1157 - average 1125 simple Results: 1592 1592 1597 1597 - average 1594 ttcc/RelTime Logging with stack info to a NOPWriter. Results: 866 886 876 866 - average 873 simple Results: 1312 1312 1302 1302 - average 1307 ttcc/RelTime A noticable slowdown in RelTime printing, but sull faster than 0.7.4. -------------- Thu Feb 3 21:04:35 2000 --------------- Release 0.7.5 Logging to a real file. Results: 91 92 95 100 120 91 95 92 - average 97 simple Results: 178 176 192 183 176 179 174 181 - average 179 ttcc/RelTime Results: 211 201 203 203 206 220 210 216 - average 208 ttcc/AbsTime Results: 238 237 245 233 239 237 239 241 - average 238 ttcc/DateTime Logging to a NOPWriter. Results: 21 21 21 20 - average 20 simple Results: 58 58 58 58 - average 58 ttcc/RelTime Results: 87 87 86 86 - average 86 ttcc/AbsTime Results: 114 113 114 114 - average 113 ttcc/DateTime Logging with stack info to a regular file. Results: 1121 1121 1111 1126 - average 1119 simple Results: 1622 1617 1597 1622 - average 1614 ttcc/RelTime Logging with stack info to a NOPWriter. Results: 886 881 876 866 - average 877 simple Results: 1317 1317 1316 1317 - average 1316 ttcc/RelTime -------------- Tue Mar 21 16:57:01 2000 --------------- Release 0.8.2 code Results: 30 30 31 31 - average 30 NullAppender/SimpleLayout Results: 32 32 32 32 - average 32 NullAppender/PatternLayout "%p - %m\n" Results: 31 31 31 31 - average 31 NullAppender/PatternLayout "%-5p - %m\n" Results: 65 65 65 65 - average 65 NullAppender/TTCCLayout/RELATIVE Results: 64 65 64 64 - average 64 NullAppender/PatternLayout "%r [%t] %-5p %c %x - %m\n" Results: 64 64 64 64 - average 64 NullAppender/PatternLayout "%r [%t] %-5p %.10c %x - %m\n" Results: 64 65 64 64 - average 64 NullAppender/PatternLayout "%r [%t] %-5p %.20c %x - %m\n" Results: 58 58 60 58 - average 58 NullAppender/PatternLayout "%r [%t] %-5p %c - %m\n" Results: 122 124 121 122 - average 122 NullAppender/TTCCLayout/ISO8601 Results: 152 152 152 152 - average 152 NullAppender/PatternLayout "%d{ISO8601} [%t] %-5p %c %x - %m\n" Results: 405 405 404 405 - average 404 NullAppender/PatternLayout "%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %-5p %c %x - %m\n" Results: 111 112 113 110 110 111 114 120 - average 112 FileAppender/SimpleLayout Results: 127 124 125 129 140 121 121 123 - average 126 FileAppender/PatternLayout "%p - %m\n" Results: 196 195 186 183 186 190 182 189 - average 188 FileAppender/TTCC/RELATIVE Results: 188 184 186 195 195 214 193 191 - average 193 FileAppender/PatternLayout "%r [%t] %-5p %c %x - %m\n" Results: 257 265 300 252 - average 268 FileAppender/TTCCLayout/ISO8601 Results: 289 332 320 338 308 290 288 290 - average 306 FileAppender/PatternLayout "%d{ISO8601} [%t] %-5p %c %x - %m\n" Results: 574 577 580 572 573 577 576 589 - average 577 FileAppender/PatternLayout "%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %-5p %c %x - %m\n" Notice the good performance of PatternLayout compared to dedicated SimpleLayout and TTCCLayout except when SimpleDateFormat is used. apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/history/TORINO.logging0000644000175000017500000002227011751454704031423 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ -------------- Fri Nov 5 23:52:59 CET 1999 --------------- Append based logging Each ttcc log operation took about 342.3 microsec. Each simple log operation took about 181.9 microsec. -------------- Sat Nov 6 13:35:44 CET 1999 --------------- Configuration file: LogFile=test FileAppend=false DefaultPriority=INFO RelativeTime=true ecCategoriesFile=logging.cat Defined Categories: A0123456789=INFO Results: 173 172 168 172 170 171 178 170 169 171 - average 171 (simple) Results: 337 332 347 333 335 335 342 333 335 336 - average 336 (ttcc) Results: 141 147 145 145 143 144 143 139 145 149 - average 144 (simple) Results: 294 291 292 279 294 292 292 293 292 304 - average 292 (ttcc) APPENDING to construct the log message Second result logs to NOPOutputStream -------------- Sat Nov 6 18:08:05 CET 1999 --------------- Without the cost of evaluating - Buffer optimized Results: 82 84 85 82 88 83 84 85 83 82 - average 83 (simple) Results: 271 273 275 259 271 270 272 272 275 273 - average 271 (ttcc) Results: 54 53 58 70 55 56 55 54 57 55 - average 56 (simple) Results: 240 236 234 236 233 239 238 236 234 235 - average 236 (ttcc) Conclusion cost of evaluation about 20 micros -------------- Sat Nov 6 13:47:41 CET 1999 --------------- Results: 100 100 103 100 102 102 100 100 103 100 - average 101 (simple) Results: 300 298 300 300 310 294 307 299 299 304 - average 301 (ttcc) Results: 80 79 78 80 78 79 78 79 77 78 - average 78 (simple) Results: 259 266 263 267 265 264 263 266 265 269 - average 264 (ttcc) buffering to construct the log message Second result logs to NOPOutputStream Conclusion buffering saves ~70 microsecs, or about 70% savings. -------------- Sat Nov 6 18:19:57 CET 1999 --------------- Removed " [" and " ]" from theadStr Results: 266 273 264 260 268 266 263 264 265 266 - average 265 (ttcc) Results: 242 242 237 245 242 239 239 245 227 235 - average 239 (ttcc) -------------- Sat Nov 6 18:27:09 CET 1999 --------------- Results: 266 273 265 265 266 268 265 267 268 266 - average 266 (ttcc) Results: 231 221 225 245 234 227 240 225 225 227 - average 230 (ttcc) Optimized " [" + thread.getName() + " ]" -------------- Thu Nov 11 00:55:20 CET 1999 --------------- Results: 100 84 84 83 85 85 84 84 84 81 - average 85 (simple) Results: 206 206 204 209 216 204 199 204 212 206 - average 206 (ttcc) Results: 56 55 56 56 56 55 56 56 56 56 - average 55 (simple) Results: 179 190 171 184 186 186 185 185 184 170 - average 182 (ttcc) Using Category class. -------------- Fri Nov 12 22:02:16 CET 1999 --------------- Starting tests, this make take a few seconds.... StackInfoThreshold=INFO Results: 3890 3815 3842 3777 3845 -------------- Fri Nov 12 22:07:01 CET 1999 --------------- StackInfoThreshold=INFO Results: 3779 3979 3938 3989 3929 3757 3791 3986 3792 3772 - average 3871 (ttcc) Results: 3892 3749 3734 3709 3744 3758 3810 3859 3805 3742 - average 3780 (ttcc) -------------- Fri Nov 12 22:27:24 CET 1999 --------------- StackInfoThreshold=INFO Results: 3178 3201 3175 3183 3363 3205 3397 3206 3213 3212 - average 3233 (ttcc) Results: 3204 3232 3105 3183 3127 3236 3221 3124 3138 3182 - average 3175 (ttcc) Avoiding try and catch. Conclusion the try and catch costs a whopping 600 millis or about 1/5 of total time. -------------- Mon Nov 15 22:14:54 CET 1999 --------------- StackInfoThreshold=INFO Results: 1497 1463 1514 1445 1472 1498 1476 1471 1508 1503 - average 1484 (ttcc) Results: 1403 1483 1494 1399 1453 1463 1444 1430 1436 1406 - average 1441 (ttcc) New code based on internal TracerPrintStream class. -------------- Mon Nov 15 22:53:34 CET 1999 --------------- Results: 84 86 86 85 90 86 86 86 85 85 - average 85 (simple) Results: 219 211 203 205 206 202 203 203 215 204 - average 207 (ttcc) Results: 58 58 66 58 56 60 64 59 58 57 - average 59 (simple) Results: 174 188 177 170 173 185 171 172 171 175 - average 175 (ttcc) Results: 733 742 745 743 766 744 748 754 750 756 - average 748 (bas) Results: 1462 1481 1475 1515 1462 1479 1517 1497 1479 1555 - average 1492 (ttcc) Results: 624 628 622 616 618 612 618 605 606 618 - average 616 (bas) Results: 1353 1371 1374 1338 1374 1318 1360 1336 1329 1342 - average 1349 (ttcc) -------------- Mon Dec 13 21:49:49 CET 1999 --------------- No Layout indirection in Log. NDC in TTCCLog. Results: 82 84 86 83 87 87 88 84 84 81 - average 84 (simple) Results: 225 221 211 221 220 220 221 221 216 211 - average 218 (ttcc) Results: 60 58 60 54 60 56 55 59 55 56 - average 57 (simple) Results: 185 183 189 190 190 188 187 189 187 192 - average 188 (ttcc) Results: 725 723 737 733 731 738 756 728 755 738 - average 736 (simple) Results: 1166 1156 1170 1177 1184 1157 1172 1185 1177 1190 - average 1173 (ttcc) Results: 607 606 604 616 602 583 602 603 603 605 - average 603 (simple) Results: 1050 1021 1014 1023 1050 1019 1038 1034 1025 1012 - average 1028 (ttcc) -------------- Mon Dec 13 23:30:18 CET 1999 --------------- Layout indirection in Log. NDC in TTCCLayout Results: 85 87 86 91 89 86 89 87 84 88 - average 87 (simple) Results: 214 221 214 212 219 213 224 222 210 210 - average 215 (ttcc) Results: 66 71 70 70 82 70 66 65 64 68 - average 69 (simple) Results: 192 193 194 182 195 186 184 193 191 199 - average 190 (ttcc) Results: 758 761 743 755 750 778 748 758 737 756 - average 754 (simple) Results: 1139 1169 1112 1129 1161 1146 1121 1145 1140 1134 - average 1139 (ttcc) Results: 667 684 699 699 717 700 681 693 680 692 - average 691 (simple) Results: 1115 1119 1103 1127 1106 1116 1100 1121 1096 1131 - average 1113 (ttcc) -------------- Tue Dec 28 20:35:17 CET 1999 --------------- v 0.7.1 using Suns JDK 1.2.2 Results: 54 55 55 54 55 55 56 54 55 55 - average 54 (simple) Results: 123 123 125 122 128 122 122 123 124 123 - average 123 (ttcc) Results: 41 41 42 42 41 41 42 41 56 41 - average 42 (simple) Results: 102 102 102 102 102 102 102 101 103 102 - average 102 (ttcc) Results: 496 494 491 491 503 505 497 491 495 496 - average 495 (simple) Results: 609 601 613 607 638 606 610 608 610 607 - average 610 (ttcc) Results: 449 451 452 476 450 450 444 455 446 447 - average 452 (simple) Results: 563 548 555 555 556 545 557 551 545 559 - average 553 (ttcc) -------------- Tue Dec 28 23:44:36 CET 1999 --------------- Writer based log4j Results: 65 65 65 64 64 65 66 67 65 65 - average 65 (simple) Results: 122 121 121 121 121 122 122 122 122 121 - average 121 (ttcc) Results: 18 18 18 18 18 18 18 18 18 18 - average 18 (simple) Results: 60 72 59 59 60 60 60 60 60 60 - average 61 (ttcc) Results: 521 523 518 524 529 526 533 530 524 528 - average 525 (simple) Results: 619 629 621 622 626 622 625 624 616 624 - average 622 (ttcc) Results: 412 405 400 404 417 402 409 399 416 402 - average 406 (simple) Results: 496 492 480 488 482 488 487 492 489 488 - average 488 (ttcc) -------------- Wed Jan 12 00:05:48 CET 2000 --------------- 0.7.2 code Starting tests, this make take a few seconds.... Logging to a real file. Results: 64 63 65 64 63 63 64 64 - average 63 (simple) Results: 124 123 122 125 123 126 122 122 - average 123 (ttcc) Logging to a null (nop) output stream. Results: 17 18 17 18 17 18 17 17 - average 17 (simple) Results: 60 60 59 59 61 60 60 60 - average 59 (ttcc) Logging with stack info to a regular file. Results: 533 526 535 533 533 534 535 528 - average 532 (simple) Results: 633 630 633 628 639 619 638 630 - average 631 (ttcc) Logging with stack info to a null (nop) output stream. Results: 407 406 413 402 404 412 426 415 - average 410 (simple) Results: 491 499 494 495 487 504 497 493 - average 495 (ttcc) -------------- Sun Jul 9 21:55:09 CEST 2000 --------------- IBM JDK 1.1.8, log4j 0.8.5 with NDC NullAppender: 12 SimpleLayout 21 PatternLayout "%p - %m\n" 22 PatternLayout "%-5p - %m\n" 39 TTCCLayout/RELATIVE 39 PatternLayout "%r [%t] %-5p %c{2} %x - %m\n" 37 PatternLayout "%r [%t] %-5p %.10c %x - %m\n" 37 PatternLayout "%r [%t] %-5p %.20c %x - %m\n" 32 PatternLayout "%r [%t] %-5p %c - %m\n" 62 TTCCLayout/ISO8601 69 PatternLayout "%d{ISO8601} [%t] %-5p %c %x - %m\n" 222 PatternLayout "%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %-5p %c %x - %m\n" 1172 PatternLayout "%l - %m\n" 1313 PatternLayout "%C.%M.%L - %m\n" FileAppender: 44 SimpleLayout 56 PatternLayout "%p - %m\n" 87 TTCC/RELATIVE 95 PatternLayout "%r [%t] %-5p %c %x - %m\n" 126 TTCCLayout/ISO8601 147 PatternLayout "%d{ISO8601} [%t] %-5p %c %x - %m\n" 288 PatternLayout "%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %-5p %c %x - %m\n" 447 PatternLayout "%l - %m\n" apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/SystemTime.java0000644000175000017500000000400611751454704030303 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.performance; /** Measures the time required to make a System.currentTimeMillis() and Thread.currentThread().getName() calls.

On an 233Mhz NT machine (JDK 1.1.7B) the System.currentTimeMillis() call takes under half a microsecond to complete whereas the Thread.currentThread().getName() call takes about 4 micro-seconds. */ public class SystemTime { static int RUN_LENGTH = 1000000; static public void main(String[] args) { double t = systemCurrentTimeLoop(); System.out.println("Average System.currentTimeMillis() call took " + t); t = currentThreadNameloop(); System.out.println("Average Thread.currentThread().getName() call took " + t); } static double systemCurrentTimeLoop() { long before = System.currentTimeMillis(); for(int i = 0; i < RUN_LENGTH; i++) { System.currentTimeMillis(); } return (System.currentTimeMillis() - before)*1000.0/RUN_LENGTH; } static double currentThreadNameloop() { long before = System.currentTimeMillis(); for(int i = 0; i < RUN_LENGTH; i++) { Thread.currentThread().getName(); } return (System.currentTimeMillis() - before)*1000.0/RUN_LENGTH; } } apache-log4j1.2-1.2.17.orig/src/performance/java/org/apache/log4j/performance/logging0000644000175000017500000002224011751454704026706 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Test the performance of logging # Set the variable REMOTE_HOST to the appropriate value for the # to perform SocketAppender measurements. LCF=logging.lcf TARGET_FILE=test DELAY=1000 PORT=12345 # The results are somehow RUN_LENGTH dependent. Keep RUN_LENGTH the # same to be able to compare results LONGRUN=100000 SHORTRUN=5000 #LONGRUN=1 #SHORTRUN=2 declare -i start=$1 #D=-Dlog4j.configDebug # ------------------------------------------------------------- function multiRun() { lcf=$1 loopLength=$2 msg=$3 runLength=$4 echo -n "Results: " declare -i total declare -i i i=0 total=0 while [ $i -lt $loopLength ] do i=$i+1 x=$(java $D org.apache.log4j.performance.Logging $lcf $runLength $5) if [ $x -lt 100 ]; then echo -n " " fi echo -n "$x " total=$total+$x done while [ $i -lt 8 ] do i=$i+1 echo -n " " done average=$[ $total / $loopLength ] echo "- average $average $msg" } # ============================================= # Echo to $LCF # ============================================= function lecho { echo $* >> $LCF } # ============================================= echo "--------------" $(date) "---------------" echo echo "Starting performance measures. This make take a few minutes...." declare -i TEST echo; echo "NullAppender:"; echo TEST=1 if [ $TEST -ge $start ]; then multiRun xml/logging$TEST.xml 4 "SimpleLayout" $LONGRUN fi TEST=2 if [ $TEST -ge $start ]; then format="%p - %m%n" multiRun xml/logging$TEST.xml 4 "PatternLayout \"$format\"" $LONGRUN fi TEST=3 if [ $TEST -ge $start ]; then format="%-5p - %m%n" multiRun xml/logging$TEST.xml 4 "PatternLayout \"$format\"" $LONGRUN fi TEST=4 if [ $TEST -ge $start ]; then multiRun xml/logging$TEST.xml 4 "TTCCLayout/RELATIVE" $LONGRUN fi TEST=5 if [ $TEST -ge $start ]; then format="%r [%t] %-5p %c{2} %x - %m%n" multiRun xml/logging$TEST.xml 4 "PatternLayout \"$format\"" $LONGRUN fi TEST=6 if [ $TEST -ge $start ]; then format="%r [%t] %-5p %.10c %x - %m%n" multiRun xml/logging$TEST.xml 4 "PatternLayout \"$format\"" $LONGRUN fi TEST=7 if [ $TEST -ge $start ]; then format="%r [%t] %-5p %.20c %x - %m%n" multiRun xml/logging$TEST.xml 4 "PatternLayout \"$format\"" $LONGRUN fi TEST=8 if [ $TEST -ge $start ]; then format="%r [%t] %-5p %c - %m%n" multiRun xml/logging$TEST.xml 4 "PatternLayout \"$format\"" $LONGRUN fi TEST=9 if [ $TEST -ge $start ]; then multiRun xml/logging$TEST.xml 4 "TTCCLayout/ISO8601" $LONGRUN fi TEST=10 if [ $TEST -ge $start ]; then format="%d{ISO8601} [%t] %-5p %c %x - %m%n" multiRun xml/logging$TEST.xml 4 "PatternLayout \"$format\"" $LONGRUN fi TEST=11 if [ $TEST -ge $start ]; then format="%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %-5p %c %x - %m%n" multiRun xml/logging$TEST.xml 4 "PatternLayout \"$format\"" $LONGRUN fi TEST=12 if [ $TEST -ge $start ]; then format="%l - %m%n" multiRun xml/logging$TEST.xml 4 "PatternLayout \"$format\"" $SHORTRUN fi TEST=13 if [ $TEST -ge $start ]; then format="%C.%M.%L - %m%n" multiRun xml/logging$TEST.xml 4 "PatternLayout \"$format\"" $SHORTRUN fi echo echo "FileAppender: " echo TEST=100 if [ $TEST -ge $start ]; then multiRun xml/logging$TEST.xml 8 "SimpleLayout" $LONGRUN fi TEST=101 if [ $TEST -ge $start ]; then format="%p - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $LONGRUN fi TEST=102 if [ $TEST -ge $start ]; then multiRun xml/logging$TEST.xml 8 "TTCC/RELATIVE" $LONGRUN fi TEST=103 if [ $TEST -ge $start ]; then format="%r [%t] %-5p %c - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $LONGRUN fi TEST=104 if [ $TEST -ge $start ]; then multiRun xml/logging$TEST.xml 8 "TTCCLayout/ISO8601" $LONGRUN fi TEST=105 if [ $TEST -ge $start ]; then format="%d{ISO8601} [%t] %-5p %c %x - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $LONGRUN fi TEST=106 if [ $TEST -ge $start ]; then format="%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %-5p %c %x - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $LONGRUN fi echo ================== 107 =============================== TEST=107 if [ $TEST -ge $start ]; then format="%l - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $SHORTRUN fi echo ------------------------------------- echo "FileAppender: ImmediateFlush=false" echo ------------------------------------- TEST=200 if [ $TEST -ge $start ]; then multiRun xml/logging$TEST.xml 8 "SimpleLayout" $LONGRUN fi TEST=201 if [ $TEST -ge $start ]; then format="%p - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $LONGRUN fi TEST=202 if [ $TEST -ge $start ]; then multiRun xml/logging$TEST.xml 8 "TTCC/RELATIVE" $LONGRUN fi TEST=203 if [ $TEST -ge $start ]; then format="%r [%t] %-5p %c - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $LONGRUN fi TEST=204 if [ $TEST -ge $start ]; then multiRun xml/logging$TEST.xml 8 "TTCCLayout/ISO8601" $LONGRUN fi TEST=205 if [ $TEST -ge $start ]; then format="%d{ISO8601} [%t] %-5p %c %x - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $LONGRUN fi TEST=206 if [ $TEST -ge $start ]; then format="%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %-5p %c %x - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $LONGRUN fi TEST=207 if [ $TEST -ge $start ]; then format="%l - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $SHORTRUN fi echo ------------------------------------- echo "FileAppender: BufferedIO=true" echo ------------------------------------- TEST=220 if [ $TEST -ge $start ]; then multiRun xml/logging$TEST.xml 8 "SimpleLayout" $LONGRUN fi TEST=221 if [ $TEST -ge $start ]; then format="%p - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $LONGRUN fi TEST=222 if [ $TEST -ge $start ]; then multiRun xml/logging$TEST.xml 8 "TTCC/RELATIVE" $LONGRUN fi TEST=223 if [ $TEST -ge $start ]; then format="%r [%t] %-5p %c - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $LONGRUN fi TEST=224 if [ $TEST -ge $start ]; then multiRun xml/logging$TEST.xml 8 "TTCCLayout/ISO8601" $LONGRUN fi TEST=225 if [ $TEST -ge $start ]; then format="%d{ISO8601} [%t] %-5p %c %x - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $LONGRUN fi TEST=226 if [ $TEST -ge $start ]; then format="%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %-5p %c %x - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $LONGRUN fi TEST=227 if [ $TEST -ge $start ]; then format="%l - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $SHORTRUN fi echo ================================== echo Async appender echo ================================== TEST=300 if [ $TEST -ge $start ]; then multiRun xml/logging$TEST.xml 8 "SimpleLayout" $LONGRUN fi TEST=301 if [ $TEST -ge $start ]; then format="%p - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $LONGRUN fi TEST=302 if [ $TEST -ge $start ]; then multiRun xml/logging$TEST.xml 8 "TTCCLayout/RELATIVE" $LONGRUN fi TEST=303 if [ $TEST -ge $start ]; then format="%r [%t] %-5p %c - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $LONGRUN fi TEST=304 if [ $TEST -ge $start ]; then multiRun xml/logging$TEST.xml 8 "TTCCLayout/ISO8601" $LONGRUN fi TEST=305 if [ $TEST -ge $start ]; then format="%d{ISO8601} [%t] %-5p %c %x - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $LONGRUN fi TEST=306 if [ $TEST -ge $start ]; then format="%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %-5p %c %x - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $LONGRUN fi TEST=307 if [ $TEST -ge $start ]; then format="%l - %m%n" multiRun xml/logging$TEST.xml 8 "PatternLayout \"$format\"" $SHORTRUN fi # =============================================================== # Remote logging # =============================================================== TEST=1000 #RL=1000 RL=10000 if [ $TEST -ge $start ]; then java org.apache.log4j.performance.Logging xml/logging$TEST.xml $RL 100 100 #multiRun 4 "SocketAppender" $SHORTRUN $DELAY fi TEST=1001 #RL=1000 RL=30000 if [ $TEST -ge $start ]; then java org.apache.log4j.performance.Logging xml/logging$TEST.xml $RL #multiRun 4 "SocketAppender" $SHORTRUN $DELAY fi apache-log4j1.2-1.2.17.orig/src/assembly/0000755000175000017500000000000012126647422016400 5ustar tonytonyapache-log4j1.2-1.2.17.orig/src/assembly/bin.xml0000644000175000017500000000443311751454703017677 0ustar tonytony bin zip tar.gz apache-log4j-${project.version} true *.txt *.sample *.xml INSTALL KEYS LICENSE NOTICE contribs/** examples/** src/assembly/** src/changes/** src/main/** src/ntdll/* src/performance/** src/site/** tests/README tests/*.xml tests/*.sample tests/*.bat tests/input/** tests/resources/** tests/src/** tests/witness/** target/log4j-${project.version}.jar target/NTEventLogAppender.dll 0755 NTEventLogAppender.amd64.dll 0755 apache-log4j1.2-1.2.17.orig/INSTALL0000644000175000017500000000730411751454714015032 0ustar tonytony Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========== Using log4j =========== 1) First untar or unzip the distribution file. 2) Assuming you chose to extract the distribution in to the PATH_OF_YOUR_CHOICE, untarring the distribution file should create a logging-log4j-VERSION directory, where VERSION is the log4j version number, under PATH_OF_YOUR_CHOICE. We will refer to the directory PATH_OF_YOUR_CHOICE/apache-log4j-VERSION/ as $LOG4J_HOME/. 3) Add $LOG4J_HOME/log4j-VERSION.jar to your CLASSPATH, 4) You can now test your installation by first compiling the following simple program. import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator; public class Hello { private static final Logger logger = Logger.getLogger(Hello.class); public static void main(String argv[]) { BasicConfigurator.configure(); logger.debug("Hello world."); logger.info("What a beatiful day."); } } After compilation, try it out by issuing the command java Hello You should see log statements appearing on the console. 5) Refer to the javadoc documentation and the user manual on how to include log statements in your own code. ========= JAR files ========= The log4j distribution comes with one jar file: log4j-VERSION.jar under the LOG4J_HOME directory. This jar file contains all the class files of the log4j project, except test cases and classes from the "examples" and "org.apache.log4j.performance" packages. ============== Building log4j ============== log4j (as of 1.2.15) is built with Maven 2. To rebuild log4j, place Maven 2 on the PATH and execute "mvn package". The resulting jar will be placed in the target subdirectory. If building with JDK 1.4, one dependency will need to be manually installed since its license does not allow it to be placed in the online maven repositories. If not already installed, a build attempt will describe where to download and how to install the dependency. To install the dependency: Download JMX 1.2.1 from http://java.sun.com/products/JavaManagement/download.html. $ jar xf jmx-1_2_1-ri.zip $ mvn install:install-file -DgroupId=com.sun.jmx -DartifactId=jmxri \ -Dversion=1.2.1 -Dpackaging=jar -Dfile=jmx-1_2_1-bin/lib/jmxri.jar The build script will attempt to build NTEventLogAppender.dll if MinGW is available on the path. If the unit tests are run on Windows without NTEventLogAppender.dll, many warnings of the missing DLL will be generated. An installer for MinGW on Windows is available for download at http://sourceforge.net/project/showfiles.php?group_id=2435. MinGW is also available through the package managers of many Linux distributions. In case of problems send an e-mail note to log4j-user@logging.apache.org. Please do not directly e-mail any log4j developers. The answer to your question might be useful to other users. Moreover, there are many knowledgeable users on the log4j-user mailing lists who can quickly answer your questions. apache-log4j1.2-1.2.17.orig/pom.xml0000644000175000017500000005236111751454714015321 0ustar tonytony 4.0.0 log4j log4j bundle Apache Log4j 1.2.17 Apache Log4j 1.2 http://logging.apache.org/log4j/1.2/ Bugzilla https://issues.apache.org/bugzilla/describecomponents.cgi?product=Log4j Gump http://vmgump.apache.org/gump/public/logging-log4j-12/logging-log4j-12/index.html 1999 log4j-user log4j-user-subscribe@logging.apache.org log4j-user-unsubscribe@logging.apache.org log4j-user@logging.apache.org http://mail-archives.apache.org/mod_mbox/logging-log4j-user/ http://marc.info/?l=log4j-user http://dir.gmane.org/gmane.comp.jakarta.log4j.user log4j-dev log4j-dev-subscribe@logging.apache.org log4j-dev-unsubscribe@logging.apache.org log4j-dev@logging.apache.org http://mail-archives.apache.org/mod_mbox/logging-log4j-dev/ http://marc.info/?l=log4j-dev http://dir.gmane.org/gmane.comp.jakarta.log4j.devel The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo scm:svn:http://svn.apache.org/repos/asf/logging/log4j/tags/v1_2_17_rc3 scm:svn:https://svn.apache.org/repos/asf/logging/log4j/tags/v1_2_17_rc3 http://svn.apache.org/viewvc/logging/log4j/tags/v1_2_17_rc3 Apache Software Foundation http://www.apache.org org.apache.maven.plugins maven-resources-plugin UTF-8 maven-surefire-plugin 2.5 tests plain pertest true org/apache/log4j/LevelTest.java org/apache/log4j/PriorityTest.java org/apache/log4j/CategoryTest.java org/apache/log4j/FileAppenderTest.java org/apache/log4j/LogManagerTest.java org/apache/log4j/helpers.LogLogTest.java org/apache/log4j/LayoutTest.java org/apache/log4j/helpers.DateLayoutTest.java org/apache/log4j/TTCCLayoutTest.java org/apache/log4j/xml.XMLLayoutTest.java org/apache/log4j/HTMLLayoutTest.java org/apache/log4j/PatternLayoutTest.java org/apache/log4j/spi.LoggingEventTest.java org/apache/log4j/spi.ThrowableInformationTest.java org/apache/log4j/spi.LocationInfoTest.java org/apache/log4j/PropertyConfiguratorTest.java org/apache/log4j/MinimumTestCase.java org/apache/log4j/LoggerTestCase.java org/apache/log4j/PatternLayoutTestCase.java org/apache/log4j/HierarchyThresholdTestCase.java org/apache/log4j/xml/DOMTestCase.java org/apache/log4j/xml/CustomLevelTestCase.java org/apache/log4j/customLogger/XLoggerTestCase.java org/apache/log4j/xml/XMLLayoutTestCase.java org/apache/log4j/xml/AsyncAppenderTestCase.java org/apache/log4j/varia/LevelMatchFilterTestCase.java org/apache/log4j/helpers/BoundedFIFOTestCase.java org/apache/log4j/helpers/CyclicBufferTestCase.java org/apache/log4j/helpers/PatternParserTestCase.java org/apache/log4j/or/ORTestCase.java org/apache/log4j/DRFATestCase.java org/apache/log4j/RFATestCase.java org/apache/log4j/varia/ERFATestCase.java org/apache/log4j/net/SyslogAppenderTest org/apache/log4j/nt/NTEventLogAppenderTest org/apache/log4j/net/SocketAppenderTest maven-compiler-plugin 2.1 1.4 1.4 UTF-8 maven-jar-plugin 2.3 org.apache.log4j * log4j ${project.version} "Apache Software Foundation" maven-antrun-plugin 1.2 process-classes ntdll run test-compile mkdir_tests_output run clean rmdir_tests_output run test runAll run site untag-site run post-site post-site run site-deploy site-deploy run javadoc.resources generate-sources run ant ant-nodeps 1.6.5 ant-contrib ant-contrib 1.0b2 ant ant-junit 1.6.5 junit junit 3.8.1 compile sun.jdk tools 1.4.2 system ${tools.jar} maven-assembly-plugin 2.2-beta-5 src/assembly/bin.xml false assembly maven-javadoc-plugin 2.7 true .svn UTF-8 UTF-8 jar javadoc site pre-site javadoc maven-release-plugin 2.0-beta-9 package site-deploy assembly:attached deploy maven-source-plugin 2.1.1 jar org.codehaus.mojo clirr-maven-plugin 2.2.2 1.2.15 org.codehaus.mojo rat-maven-plugin 1.0-alpha-3 tests/witness/** tests/output/** tests/classes/** org.apache.felix maven-bundle-plugin 2.1.0 true !org.apache.log4j.lf5.*, !org.apache.log4j.chainsaw.*, org.apache.log4j.*;version=1.2.17;-noimport:=true !javax.swing.*, !com.ibm.uvm.tools.*, !com.sun.jdmk.comm.*, javax.jmdns.*;resolution:=optional, javax.jms.*;resolution:=optional, javax.mail.*;resolution:=optional, * http://logging.apache.org/log4j/1.2 maven-site-plugin 3.1 ${basedir}/src/site/maven-site.vm true package site tests/src/java tests/resources maven-project-info-reports-plugin 2.4 scm dependencies cim issue-tracking mailing-list license maven-jxr-plugin 2.1 maven-changes-plugin 2.7 changes-report mac mac ${java.home}/../Classes/classes.jar ${user.home}/.m2/repository build default true ${java.home}/../lib/tools.jar ${user.home}/.m2/repository build maven2-repository.dev.java.net Java.net Repository for Maven http://download.java.net/maven/2/ default javax.mail mail 1.4.3 true org.apache.openejb javaee-api 5.0-2 jar provided oro oro 2.0.8 test junit junit 3.8.2 test org.apache.geronimo.specs geronimo-jms_1.1_spec 1.0 true logging.repo scp://people.apache.org/www/people.apache.org/builds/logging/repo/ logging.site scp://localhost/${user.dir}/target/site-deploy apache-log4j1.2-1.2.17.orig/contribs/0000755000175000017500000000000012126647422015615 5ustar tonytonyapache-log4j1.2-1.2.17.orig/contribs/KevinSteppe/0000755000175000017500000000000012126647422020052 5ustar tonytonyapache-log4j1.2-1.2.17.orig/contribs/KevinSteppe/mail-2002-03-27.txt0000644000175000017500000000772311751454702022575 0ustar tonytony Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Received: (qmail 12476 invoked from network); 28 Mar 2002 06:19:49 -0000 Date: Wed, 27 Mar 2002 22:28:58 -0800 From: Kevin Steppe Subject: Re: RollingFileAppender and DailyRollingFileAppender To: Log4J Users List Reply-To: ksteppe@pacbell.net Message-id: <3CA2B82A.5C366593@pacbell.net> MIME-version: 1.0 X-Mailer: Mozilla 4.7 [en] (WinNT; I) Content-type: multipart/mixed; boundary="Boundary_(ID_TnKsnil+d0oYB9TV0P+fgA)" X-Accept-Language: en References: <8DAB344CC3F3FE42A51FA1A8E295F8682ACD14@tepg-server2.tepgsyd.tycoint.com.au> X-Spam-Rating: daedalus.apache.org 1.6.2 0/1000/N I wrote a CompositeRollingAppender last August to do that. I'm attaching that code and some example config files to you separately. Ceki... Could you please put these files in the log4j/contribs/KevinSteppe folder of the available releases? This seems to be coming up occasionally and it would be more convenient to just point people there. Thanks, Kevin Janusz Dalecki wrote: > Is there a way of having the mixture of both RollingFileAppender and > DailyRollingFileAppender options?. I have a requirement to log daily and > delete old files weekly. > Thanks, > Janusz > > -- > To unsubscribe, e-mail: > For additional commands, e-mail: #Config file for CompositeRollingAppender #This is an example config to use CompositeRollingAppender in Size based Backups only log4j.rootCategory=debug, R log4j.appender.R=org.apache.log4j.CompositeRollingAppender #How to perform rolling -- 1 = By Size #Note -- this is the only difference from RollingFileAppender! log4j.appender.R.RollingStyle=1 #file to log to log4j.appender.R.File=example.log #Size Rolling params log4j.appender.R.MaxFileSize=10MB log4j.appender.R.MaxSizeRollBackups=10 #layout options log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n #Config file for CompositeRollingAppender #This is an example config to use CompositeRollingAppender in Time based Backups only log4j.rootCategory=debug, R log4j.appender.R=org.apache.log4j.CompositeRollingAppender #How to perform rolling -- 2 = By Time #Note -- this is the only difference from DailyRollingFileAppender! log4j.appender.R.RollingStyle=2 #file to log to log4j.appender.R.File=example.log #Date Rolling params log4j.appender.R.datePattern='.'yyyy-MM-dd #layout options log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n #Default Config file for CompositeRollingAppender log4j.rootCategory=debug, R log4j.appender.R=org.apache.log4j.CompositeRollingAppender #How to perform rolling -- Composite is the default log4j.appender.R.RollingStyle=3 #Use same file name for all inprocess logging? log4j.appender.R.staticLogFileName=true log4j.appender.R.File=example.log #Size Rolling params log4j.appender.R.CountDirection=-1 log4j.appender.R.MaxFileSize=5KB log4j.appender.R.MaxSizeRollBackups=10 #Date Rolling params log4j.appender.R.datePattern='.'yyyy-MM-dd #layout options log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n apache-log4j1.2-1.2.17.orig/contribs/KevinSteppe/JDBCTest.java0000644000175000017500000000561711751454702022270 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.varia.test; import org.apache.log4j.varia.JDBCAppender; import org.apache.log4j.*; public class JDBCTest { public static void main (String argv[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (Exception e) { e.printStackTrace(); System.out.println(e.toString()); } Category rootLog = Category.getRoot(); Layout layout = new PatternLayout("%p [%t] %c - %m%n"); JDBCAppender appender = new JDBCAppender(); appender.setLayout(layout); appender.setOption(JDBCAppender.URL_OPTION, "jdbc:odbc:someDB"); appender.setOption(JDBCAppender.USER_OPTION, "auser"); appender.setOption(JDBCAppender.PASSWORD_OPTION, "thepassword"); rootLog.addAppender(appender); try { Category log = Category.getInstance("main"); log.debug("Debug 1"); Thread.sleep(500); log.info("info 1"); Thread.sleep(500); log.warn("warn 1"); Thread.sleep(500); log.error("error 1"); Thread.sleep(500); log.fatal("fatal 1"); Thread.sleep(500); appender.setOption(JDBCAppender.BUFFER_OPTION, "5"); log.debug("Debug 2"); Thread.sleep(500); log.info("info 2"); Thread.sleep(500); log.warn("warn 2"); Thread.sleep(500); log.error("error 2"); Thread.sleep(500); log.fatal("fatal 2"); Thread.sleep(500); appender.setOption(JDBCAppender.BUFFER_OPTION, "2"); appender.setThreshold(Priority.WARN); log.debug("Debug 3"); Thread.sleep(500); log.info("info 3"); Thread.sleep(500); log.warn("warn 3"); Thread.sleep(500); log.error("error 3"); Thread.sleep(500); log.fatal("fatal 3"); } catch (InterruptedException e) { System.out.println("Interrupted"); } } } apache-log4j1.2-1.2.17.orig/contribs/KevinSteppe/CompositeRollingAppender.java0000644000175000017500000005421111751454702025670 0ustar tonytonypackage org.apache.log4j; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.log4j.RollingCalendar; 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 java.util.Date; import java.io.IOException; import java.io.Writer; import java.text.SimpleDateFormat; import java.io.File; import java.io.FilenameFilter; /** *

CompositeRollingAppender combines RollingFileAppender and DailyRollingFileAppender
* It can function as either or do both at the same time (making size * based rolling files like RollingFileAppender until a data/time boundary * is crossed at which time it rolls all of those files as per the DailyRollingFileAppender) * based on the setting for rollingStyle.
*
* To use CompositeRollingAppender to roll log files as they reach a certain * size (like RollingFileAppender), set rollingStyle=1 (@see config.size)
* To use CompositeRollingAppender to roll log files at certain time intervals * (daily for example), set rollingStyle=2 and a datePattern (@see config.time)
* To have CompositeRollingAppender roll log files at a certain size AND rename those * according to time intervals, set rollingStyle=3 (@see config.composite)
* *

A of few additional optional features have been added:
* -- Attach date pattern for current log file (@see staticLogFileName)
* -- Backup number increments for newer files (@see countDirection)
* -- Infinite number of backups by file size (@see maxSizeRollBackups)
*
*

A few notes and warnings: For large or infinite number of backups * countDirection > 0 is highly recommended, with staticLogFileName = false if * time based rolling is also used -- this will reduce the number of file renamings * to few or none. Changing staticLogFileName or countDirection without clearing * the directory could have nasty side effects. If Date/Time based rolling * is enabled, CompositeRollingAppender will attempt to roll existing files * in the directory without a date/time tag based on the last modified date * of the base log files last modification.
*
*

A maximum number of backups based on date/time boundries would be nice * but is not yet implemented.
* * @author Kevin Steppe * @author Heinz Richter * @author Eirik Lygre * @author Ceki Gülcü */ public class CompositeRollingAppender extends org.apache.log4j.FileAppender { // The code assumes that the following 'time' constants are in a increasing // sequence. static final int TOP_OF_TROUBLE=-1; static final int TOP_OF_MINUTE = 0; static final int TOP_OF_HOUR = 1; static final int HALF_DAY = 2; static final int TOP_OF_DAY = 3; static final int TOP_OF_WEEK = 4; static final int TOP_OF_MONTH = 5; /** Style of rolling to use */ static final int BY_SIZE = 1; static final int BY_DATE = 2; static final int BY_COMPOSITE = 3; //Not currently used static final String S_BY_SIZE = "Size"; static final String S_BY_DATE = "Date"; static final String S_BY_COMPOSITE = "Composite"; /** The date pattern. By default, the pattern is set to "'.'yyyy-MM-dd" meaning daily rollover. */ private String datePattern = "'.'yyyy-MM-dd"; /** The actual formatted filename that is currently being written to or will be the file transferred to on roll over (based on staticLogFileName). */ private String scheduledFilename = null; /** The timestamp when we shall next recompute the filename. */ private long nextCheck = System.currentTimeMillis () - 1; /** Holds date of last roll over */ Date now = new Date(); SimpleDateFormat sdf; /** Helper class to determine next rollover time */ RollingCalendar rc = new RollingCalendar(); /** Current period for roll overs */ int checkPeriod = TOP_OF_TROUBLE; /** The default maximum file size is 10MB. */ protected long maxFileSize = 10*1024*1024; /** There is zero backup files by default. */ protected int maxSizeRollBackups = 0; /** How many sized based backups have been made so far */ protected int curSizeRollBackups = 0; /** not yet implemented */ protected int maxTimeRollBackups = -1; protected int curTimeRollBackups = 0; /** By default newer files have lower numbers. (countDirection < 0) * ie. log.1 is most recent, log.5 is the 5th backup, etc... * countDirection > 0 does the opposite ie. * log.1 is the first backup made, log.5 is the 5th backup made, etc. * For infinite backups use countDirection > 0 to reduce rollOver costs. */ protected int countDirection = -1; /** Style of rolling to Use. BY_SIZE (1), BY_DATE(2), BY COMPOSITE(3) */ protected int rollingStyle = BY_COMPOSITE; protected boolean rollDate = true; protected boolean rollSize = true; /** By default file.log is always the current file. Optionally * file.log.yyyy-mm-dd for current formated datePattern can by the currently * logging file (or file.log.curSizeRollBackup or even * file.log.yyyy-mm-dd.curSizeRollBackup) This will make time based roll * overs with a large number of backups much faster -- it won't have to * rename all the backups! */ protected boolean staticLogFileName = true; /** FileName provided in configuration. Used for rolling properly */ protected String baseFileName; /** The default constructor does nothing. */ public CompositeRollingAppender() { } /** Instantiate a CompositeRollingAppender and open the file designated by filename. The opened filename will become the ouput destination for this appender. */ public CompositeRollingAppender (Layout layout, String filename, String datePattern) throws IOException { this(layout, filename, datePattern, true); } /** Instantiate a CompositeRollingAppender and open the file designated by filename. The opened filename will become the ouput destination for this appender.

If the append parameter is true, the file will be appended to. Otherwise, the file desginated by filename will be truncated before being opened. */ public CompositeRollingAppender(Layout layout, String filename, boolean append) throws IOException { super(layout, filename, append); } /** Instantiate a CompositeRollingAppender and open the file designated by filename. The opened filename will become the ouput destination for this appender. */ public CompositeRollingAppender (Layout layout, String filename, String datePattern, boolean append) throws IOException { super(layout, filename, append); this.datePattern = datePattern; activateOptions(); } /** Instantiate a CompositeRollingAppender and open the file designated by filename. The opened filename will become the output destination for this appender.

The file will be appended to. DatePattern is default. */ public CompositeRollingAppender(Layout layout, String filename) throws IOException { super(layout, filename); } /** The DatePattern takes a string in the same format as expected by {@link SimpleDateFormat}. This options determines the rollover schedule. */ public void setDatePattern(String pattern) { datePattern = pattern; } /** Returns the value of the DatePattern option. */ public String getDatePattern() { return datePattern; } /** Returns the value of the maxSizeRollBackups option. */ public int getMaxSizeRollBackups() { return maxSizeRollBackups; } /** Get the maximum size that the output file is allowed to reach before being rolled over to backup files. @since 1.1 */ public long getMaximumFileSize() { return maxFileSize; } /**

Set the maximum number of backup files to keep around based on file size.

The MaxSizeRollBackups option determines how many backup files are kept before the oldest is erased. This option takes an integer value. If set to zero, then there will be no backup files and the log file will be truncated when it reaches MaxFileSize. If a negative number is supplied then no deletions will be made. Note that this could result in very slow performance as a large number of files are rolled over unless {@link #setCountDirection} up is used.

The maximum applys to -each- time based group of files and -not- the total. Using a daily roll the maximum total files would be (#days run) * (maxSizeRollBackups) */ public void setMaxSizeRollBackups(int maxBackups) { maxSizeRollBackups = maxBackups; } /** Set the maximum size that the output file is allowed to reach before being rolled over to backup files.

This method is equivalent to {@link #setMaxFileSize} except that it is required for differentiating the setter taking a long argument from the setter taking a String argument by the JavaBeans {@link java.beans.Introspector Introspector}. @see #setMaxFileSize(String) */ public void setMaxFileSize(long maxFileSize) { this.maxFileSize = maxFileSize; } /** Set the maximum size that the output file is allowed to reach before being rolled over to backup files.

This method is equivalent to {@link #setMaxFileSize} except that it is required for differentiating the setter taking a long argument from the setter taking a String argument by the JavaBeans {@link java.beans.Introspector Introspector}. @see #setMaxFileSize(String) */ public void setMaximumFileSize(long maxFileSize) { this.maxFileSize = maxFileSize; } /** Set the maximum size that the output file is allowed to reach before being rolled over to backup files.

In configuration files, the MaxFileSize 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 interpreted being expressed respectively in kilobytes, megabytes or gigabytes. For example, the value "10KB" will be interpreted as 10240. */ public void setMaxFileSize(String value) { maxFileSize = OptionConverter.toFileSize(value, maxFileSize + 1); } protected void setQWForFiles(Writer writer) { qw = new CountingQuietWriter(writer, errorHandler); } //Taken verbatum from DailyRollingFileAppender int computeCheckPeriod() { RollingCalendar c = new RollingCalendar(); // set sate to 1970-01-01 00:00:00 GMT Date epoch = new Date(0); if(datePattern != null) { for(int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) { String r0 = sdf.format(epoch); c.setType(i); Date next = new Date(c.getNextCheckMillis(epoch)); String r1 = sdf.format(next); //LogLog.debug("Type = "+i+", r0 = "+r0+", r1 = "+r1); if(r0 != null && r1 != null && !r0.equals(r1)) { return i; } } } return TOP_OF_TROUBLE; // Deliberately head for trouble... } //Now for the new stuff /** * Handles append time behavior for CompositeRollingAppender. This checks * if a roll over either by date (checked first) or time (checked second) * is need and then appends to the file last. */ protected void subAppend(LoggingEvent event) { if (rollDate) { long n = System.currentTimeMillis(); if (n >= nextCheck) { now.setTime(n); nextCheck = rc.getNextCheckMillis(now); rollOverTime(); } } if (rollSize) { if ((fileName != null) && ((CountingQuietWriter) qw).getCount() >= maxFileSize) { rollOverSize(); } } super.subAppend(event); } public void setFile(String file) { baseFileName = file.trim(); fileName = file.trim(); } /** * Creates and opens the file for logging. If staticLogFileName * is false then the fully qualified name is determined and used. */ public synchronized void setFile(String fileName, boolean append) throws IOException { if (!staticLogFileName) { scheduledFilename = fileName = fileName.trim() + sdf.format(now); if (countDirection > 0) { scheduledFilename = fileName = fileName + '.' + (++curSizeRollBackups); } } super.setFile(fileName, append); if(append) { File f = new File(fileName); ((CountingQuietWriter) qw).setCount(f.length()); } } public int getCountDirection() { return countDirection; } public void setCountDirection(int direction) { countDirection = direction; } public int getRollingStyle () { return rollingStyle; } public void setRollingStyle(int style) { rollingStyle = style; switch (rollingStyle) { case BY_SIZE: rollDate = false; rollSize = true; break; case BY_DATE: rollDate = true; rollSize = false; break; case BY_COMPOSITE: rollDate = true; rollSize = true; break; default: errorHandler.error("Invalid rolling Style, use 1 (by size only), 2 (by date only) or 3 (both)"); } } /* public void setRollingStyle(String style) { if (style == S_BY_SIZE) { rollingStyle = BY_SIZE; } else if (style == S_BY_DATE) { rollingStyle = BY_DATE; } else if (style == S_BY_COMPOSITE) { rollingStyle = BY_COMPOSITE; } } */ public boolean getStaticLogFileName() { return staticLogFileName; } public void setStaticLogFileName(boolean s) { staticLogFileName = s; } public void setStaticLogFileName(String value) { setStaticLogFileName(OptionConverter.toBoolean(value, true)); } /** * Initializes based on exisiting conditions at time of * activateOptions. The following is done:
*
* A) determine curSizeRollBackups
* B) determine curTimeRollBackups (not implemented)
* C) initiates a roll over if needed for crossing a date boundary since * the last run. */ protected void existingInit() { curSizeRollBackups = 0; curTimeRollBackups = 0; //part A starts here String filter; if (staticLogFileName || !rollDate) { filter = baseFileName + ".*"; } else { filter = scheduledFilename + ".*"; } File f = new File(baseFileName); f = f.getParentFile(); if (f == null) f = new File("."); LogLog.debug("Searching for existing files in: " + f); String[] files = f.list(); if (files != null) { for (int i = 0; i < files.length; i++) { if (!files[i].startsWith(baseFileName)) continue; int index = files[i].lastIndexOf("."); if (staticLogFileName) { int endLength = files[i].length() - index; if (baseFileName.length() + endLength != files[i].length()) { //file is probably scheduledFilename + .x so I don't care continue; } } try { int backup = Integer.parseInt(files[i].substring(index + 1, files[i].length())); LogLog.debug("From file: " + files[i] + " -> " + backup); if (backup > curSizeRollBackups) curSizeRollBackups = backup; } catch (Exception e) { //this happens when file.log -> file.log.yyyy-mm-dd which is normal //when staticLogFileName == false LogLog.debug("Encountered a backup file not ending in .x " + files[i]); } } } LogLog.debug("curSizeRollBackups starts at: " + curSizeRollBackups); //part A ends here //part B not yet implemented //part C if (staticLogFileName && rollDate) { File old = new File(baseFileName); if (old.exists()) { Date last = new Date(old.lastModified()); if (!(sdf.format(last).equals(sdf.format(now)))) { scheduledFilename = baseFileName + sdf.format(last); LogLog.debug("Initial roll over to: " + scheduledFilename); rollOverTime(); } } } LogLog.debug("curSizeRollBackups after rollOver at: " + curSizeRollBackups); //part C ends here } /** * Sets initial conditions including date/time roll over information, first check, * scheduledFilename, and calls existingInit to initialize * the current # of backups. */ public void activateOptions() { //REMOVE removed rollDate from boolean to enable Alex's change if(datePattern != null) { now.setTime(System.currentTimeMillis()); sdf = new SimpleDateFormat(datePattern); int type = computeCheckPeriod(); //printPeriodicity(type); rc.setType(type); //next line added as this removes the name check in rollOver nextCheck = rc.getNextCheckMillis(now); } else { if (rollDate) LogLog.error("Either DatePattern or rollingStyle options are not set for ["+ name+"]."); } existingInit(); super.activateOptions(); if (rollDate && fileName != null && scheduledFilename == null) scheduledFilename = fileName + sdf.format(now); } /** Rollover the file(s) to date/time tagged file(s). Opens the new file (through setFile) and resets curSizeRollBackups. */ protected void rollOverTime() { curTimeRollBackups++; //delete the old stuff here if (staticLogFileName) { /* Compute filename, but only if datePattern is specified */ if (datePattern == null) { errorHandler.error("Missing DatePattern option in rollOver()."); return; } //is the new file name equivalent to the 'current' one //something has gone wrong if we hit this -- we should only //roll over if the new file will be different from the old String dateFormat = sdf.format(now); if (scheduledFilename.equals(fileName + dateFormat)) { errorHandler.error("Compare " + scheduledFilename + " : " + fileName + dateFormat); return; } // close current file, and rename it to datedFilename this.closeFile(); //we may have to roll over a large number of backups here String from, to; for (int i = 1; i <= curSizeRollBackups; i++) { from = fileName + '.' + i; to = scheduledFilename + '.' + i; rollFile(from, to); } rollFile(fileName, scheduledFilename); } try { // This will also close the file. This is OK since multiple // close operations are safe. curSizeRollBackups = 0; //We're cleared out the old date and are ready for the new //new scheduled name scheduledFilename = fileName + sdf.format(now); this.setFile(baseFileName, false); } catch(IOException e) { errorHandler.error("setFile("+fileName+", false) call failed."); } } /** Renames file from to file to. It * also checks for existence of target file and deletes if it does. */ protected static void rollFile(String from, String to) { File target = new File(to); if (target.exists()) { LogLog.debug("deleting existing target file: " + target); target.delete(); } File file = new File(from); file.renameTo(target); LogLog.debug(from +" -> "+ to); } /** Delete's the specified file if it exists */ protected static void deleteFile(String fileName) { File file = new File(fileName); if (file.exists()) { file.delete(); } } /** Implements roll overs base on file size.

If the maximum number of size based backups is reached (curSizeRollBackups == maxSizeRollBackups If countDirection < 0, then files {File.1, ..., File.curSizeRollBackups -1} are renamed to {File.2, ..., File.curSizeRollBackups}. Moreover, File is renamed File.1 and closed.
A new file is created to receive further log output.

If maxSizeRollBackups is equal to zero, then the File is truncated with no backup files created.

If maxSizeRollBackups < 0, then File is renamed if needed and no files are deleted. */ // synchronization not necessary since doAppend is alreasy synched protected void rollOverSize() { File file; this.closeFile(); // keep windows happy. LogLog.debug("rolling over count=" + ((CountingQuietWriter) qw).getCount()); LogLog.debug("maxSizeRollBackups = " + maxSizeRollBackups); LogLog.debug("curSizeRollBackups = " + curSizeRollBackups); LogLog.debug("countDirection = " + countDirection); // If maxBackups <= 0, then there is no file renaming to be done. if (maxSizeRollBackups != 0) { if (countDirection < 0) { // Delete the oldest file, to keep Windows happy. if (curSizeRollBackups == maxSizeRollBackups) { deleteFile(fileName + '.' + maxSizeRollBackups); curSizeRollBackups--; } // Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2} for (int i = curSizeRollBackups; i >= 1; i--) { rollFile((fileName + "." + i), (fileName + '.' + (i + 1))); } curSizeRollBackups++; // Rename fileName to fileName.1 rollFile(fileName, fileName + ".1"); } //REMOVE This code branching for Alexander Cerna's request else if (countDirection == 0) { //rollFile based on date pattern curSizeRollBackups++; now.setTime(System.currentTimeMillis()); scheduledFilename = fileName + sdf.format(now); rollFile(fileName, scheduledFilename); } else { //countDirection > 0 if (curSizeRollBackups >= maxSizeRollBackups && maxSizeRollBackups > 0) { //delete the first and keep counting up. int oldestFileIndex = curSizeRollBackups - maxSizeRollBackups + 1; deleteFile(fileName + '.' + oldestFileIndex); } if (staticLogFileName) { curSizeRollBackups++; rollFile(fileName, fileName + '.' + curSizeRollBackups); } } } try { // This will also close the file. This is OK since multiple // close operations are safe. this.setFile(baseFileName, false); } catch(IOException e) { LogLog.error("setFile("+fileName+", false) call failed.", e); } } }apache-log4j1.2-1.2.17.orig/contribs/KevinSteppe/mail-2001-02-010000644000175000017500000003501611751454702021741 0ustar tonytony Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Delivered-To: urba-cgu@urbanet.ch Mailing-List: contact log4j-user-help@jakarta.apache.org; run by ezmlm List-Post: List-Help: List-Unsubscribe: List-Subscribe: Reply-To: "LOG4J Users Mailing List" Delivered-To: mailing list log4j-user@jakarta.apache.org Date: Thu, 01 Feb 2001 14:26:34 -0800 From: Kevin Steppe X-Mailer: Mozilla 4.76 [en] (Windows NT 5.0; U) X-Accept-Language: en To: LOG4J Users Mailing List Subject: JDBC Appender X-Spam-Rating: h31.sny.collab.net 1.6.2 0/1000/N Ok, here it is. Since there will be differences in database schemas and connection/execution methods, I wrote this with the intention that those parts would be overriden by subclasses (that's what I'm doing for my company), however it will work as is if you have a stored procedure spLog @msg. I'm sure there are optimizations which could be done. The code for org.apache.log4j.varia.JDBCAppender and org.apache.log4j.varia.test.JDBCTest follow and files attached. At the bottem is the SQL I used to test this on M$ SQL-Server. I help this proves useful, Kevin package org.apache.log4j.varia; import org.apache.log4j.*; import org.apache.log4j.spi.*; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.sql.DriverManager; import java.sql.Connection; import java.sql.Statement; import java.sql.SQLException; /** * Contribution from MD Data Direct. * * Implements an ArrayList buffer before storing messages to the DB. * Override getSQL to fit your database schema (or implement spLog msg on your DB) * Override executeSQL to modify how DB connection and SQL execution is made. * * @author: Kevin Steppe */ public class JDBCAppender extends org.apache.log4j.AppenderSkeleton implements org.apache.log4j.Appender { protected String databaseURL = "jdbc:odbc:myDB"; protected String databaseUser = "me"; protected String databasePassword = "mypassword"; public static final String URL_OPTION = "URL"; public static final String USER_OPTION = "User"; public static final String PASSWORD_OPTION = "Password"; public static final String BUFFER_OPTION = "Buffer"; protected int bufferSize = 1; protected List buffer; public JDBCAppender() { super(); buffer = new ArrayList(); } public void append(LoggingEvent event) { buffer.add(event); if (buffer.size() >= bufferSize) flushBuffer(); } public void close() { flushBuffer(); this.closed = true; } public void setOption(String key, String value) { super.setOption(key, value); if (key.equalsIgnoreCase(URL_OPTION)) databaseURL = value; else if (key.equalsIgnoreCase(USER_OPTION)) databaseUser = value; else if (key.equalsIgnoreCase(PASSWORD_OPTION)) databasePassword = value; else if (key.equalsIgnoreCase(BUFFER_OPTION)) bufferSize = Integer.parseInt(value); } /** * Override this to create the SQL needed for your DB schema */ protected String getSQL(LoggingEvent event) { String msg = this.layout.format(event); String sql = "spLog '" + msg + "'"; return sql; } /** * Override this to provide an alertnate method of getting connections (such as caching) * This implementation creates a new connection and statement for every execution which * is very wastefull. One method to fix this is to open connections at the start of * flushBuffer() and close them at the end. MD Data uses a connection pool outside * of JDBCAppender which is accessed in the override of this method. */ protected void executeSQL(String sql) throws SQLException { Connection con = null; Statement stmt = null; try { con = DriverManager.getConnection(databaseURL, databaseUser, databasePassword); stmt = con.createStatement(); stmt.executeUpdate(sql); } catch (SQLException e) { if (con != null) con.close(); if (stmt != null) stmt.close(); throw e; } stmt.close(); con.close(); } public void flushBuffer() { //Do the actual logging for (Iterator i = buffer.iterator(); i.hasNext();) { try { String sql = getSQL((LoggingEvent)i.next()); executeSQL(sql); } catch (SQLException e) { errorHandler.error("Failed to excute sql", e, ErrorCode.FLUSH_FAILURE); } } buffer.clear(); } public void finalize() { close(); } public boolean requiresLayout() { return true; } } package org.apache.log4j.varia.test; import org.apache.log4j.varia.JDBCAppender; import org.apache.log4j.*; public class JDBCTest { public static void main (String argv[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (Exception e) { e.printStackTrace(); System.out.println(e.toString()); } Category rootLog = Category.getRoot(); Layout layout = new PatternLayout("%p [%t] %c - %m%n"); JDBCAppender appender = new JDBCAppender(); appender.setLayout(layout); appender.setOption(JDBCAppender.URL_OPTION, "jdbc:odbc:someDB"); appender.setOption(JDBCAppender.USER_OPTION, "auser"); appender.setOption(JDBCAppender.PASSWORD_OPTION, "thepassword"); rootLog.addAppender(appender); try { Category log = Category.getInstance("main"); log.debug("Debug 1"); Thread.sleep(500); log.info("info 1"); Thread.sleep(500); log.warn("warn 1"); Thread.sleep(500); log.error("error 1"); Thread.sleep(500); log.fatal("fatal 1"); Thread.sleep(500); appender.setOption(JDBCAppender.BUFFER_OPTION, "5"); log.debug("Debug 2"); Thread.sleep(500); log.info("info 2"); Thread.sleep(500); log.warn("warn 2"); Thread.sleep(500); log.error("error 2"); Thread.sleep(500); log.fatal("fatal 2"); Thread.sleep(500); appender.setOption(JDBCAppender.BUFFER_OPTION, "2"); appender.setThreshold(Priority.WARN); log.debug("Debug 3"); Thread.sleep(500); log.info("info 3"); Thread.sleep(500); log.warn("warn 3"); Thread.sleep(500); log.error("error 3"); Thread.sleep(500); log.fatal("fatal 3"); } catch (InterruptedException e) { System.out.println("Interrupted"); } } } drop table JDBCAppenderTest go create table JDBCAppenderTest (EventID int identity, entrytime datetime, message varchar(255)) drop procedure spLog go create procedure spLog (@msg varchar(255)) as insert into JDBCAppenderTest (message, entrytime) values (@msg, getdate()) select * from JDBCAppenderTest drop table JDBCAppenderTest go create table JDBCAppenderTest (EventID int identity, entrytime datetime, message varchar(255)) drop procedure spLog go create procedure spLog (@msg varchar(255)) as insert into JDBCAppenderTest (message, entrytime) values (@msg, getdate()) select * from JDBCAppenderTest package org.apache.log4j.varia; import org.apache.log4j.*; import org.apache.log4j.spi.*; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.sql.DriverManager; import java.sql.Connection; import java.sql.Statement; import java.sql.SQLException; /** * Contribution from MD Data Direct. * * Implements an ArrayList buffer before storing messages to the DB. * Override getSQL to fit your database schema (or implement spLog msg on your DB) * Override executeSQL to modify how DB connection and SQL execution is made. * * @author: Kevin Steppe */ public class JDBCAppender extends org.apache.log4j.AppenderSkeleton implements org.apache.log4j.Appender { protected String databaseURL = "jdbc:odbc:myDB"; protected String databaseUser = "me"; protected String databasePassword = "mypassword"; public static final String URL_OPTION = "URL"; public static final String USER_OPTION = "User"; public static final String PASSWORD_OPTION = "Password"; public static final String BUFFER_OPTION = "Buffer"; protected int bufferSize = 1; protected List buffer; public JDBCAppender() { super(); buffer = new ArrayList(); } public void append(LoggingEvent event) { buffer.add(event); if (buffer.size() >= bufferSize) flushBuffer(); } public void close() { flushBuffer(); this.closed = true; } public void setOption(String key, String value) { super.setOption(key, value); if (key.equalsIgnoreCase(URL_OPTION)) databaseURL = value; else if (key.equalsIgnoreCase(USER_OPTION)) databaseUser = value; else if (key.equalsIgnoreCase(PASSWORD_OPTION)) databasePassword = value; else if (key.equalsIgnoreCase(BUFFER_OPTION)) bufferSize = Integer.parseInt(value); } /** * Override this to create the SQL needed for your DB schema */ protected String getSQL(LoggingEvent event) { String msg = this.layout.format(event); String sql = "spLog '" + msg + "'"; System.out.println(sql); //DEBUG return sql; } /** * Override this to provide an alertnate method of getting connections (such as caching) * This implementation creates a new connection and statement for every execution which * is very wastefull. One method to fix this is to open connections at the start of * flushBuffer() and close them at the end. MD Data uses a connection pool outside * of JDBCAppender which is accessed in the override of this method. */ protected void executeSQL(String sql) throws SQLException { Connection con = null; Statement stmt = null; try { con = DriverManager.getConnection(databaseURL, databaseUser, databasePassword); stmt = con.createStatement(); stmt.executeUpdate(sql); } catch (SQLException e) { if (con != null) con.close(); if (stmt != null) stmt.close(); throw e; } stmt.close(); con.close(); } public void flushBuffer() { //Do the actual logging for (Iterator i = buffer.iterator(); i.hasNext();) { try { String sql = getSQL((LoggingEvent)i.next()); executeSQL(sql); } catch (SQLException e) { errorHandler.error("Failed to excute sql", e, ErrorCode.FLUSH_FAILURE); } } buffer.clear(); } public void finalize() { close(); } public boolean requiresLayout() { return true; } }package org.apache.log4j.varia.test; import org.apache.log4j.varia.JDBCAppender; import org.apache.log4j.*; public class JDBCTest { public static void main (String argv[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (Exception e) { e.printStackTrace(); System.out.println(e.toString()); } Category rootLog = Category.getRoot(); Layout layout = new PatternLayout("%p [%t] %c - %m%n"); JDBCAppender appender = new JDBCAppender(); appender.setLayout(layout); appender.setOption(JDBCAppender.URL_OPTION, "jdbc:odbc:someDB"); appender.setOption(JDBCAppender.USER_OPTION, "auser"); appender.setOption(JDBCAppender.PASSWORD_OPTION, "thepassword"); rootLog.addAppender(appender); try { Category log = Category.getInstance("main"); log.debug("Debug 1"); Thread.sleep(500); log.info("info 1"); Thread.sleep(500); log.warn("warn 1"); Thread.sleep(500); log.error("error 1"); Thread.sleep(500); log.fatal("fatal 1"); Thread.sleep(500); appender.setOption(JDBCAppender.BUFFER_OPTION, "5"); log.debug("Debug 2"); Thread.sleep(500); log.info("info 2"); Thread.sleep(500); log.warn("warn 2"); Thread.sleep(500); log.error("error 2"); Thread.sleep(500); log.fatal("fatal 2"); Thread.sleep(500); appender.setOption(JDBCAppender.BUFFER_OPTION, "2"); appender.setThreshold(Priority.WARN); log.debug("Debug 3"); Thread.sleep(500); log.info("info 3"); Thread.sleep(500); log.warn("warn 3"); Thread.sleep(500); log.error("error 3"); Thread.sleep(500); log.fatal("fatal 3"); } catch (InterruptedException e) { System.out.println("Interrupted"); } } } apache-log4j1.2-1.2.17.orig/contribs/MarkDouglas/0000755000175000017500000000000012126647422020026 5ustar tonytonyapache-log4j1.2-1.2.17.orig/contribs/MarkDouglas/SocketServer2.java0000644000175000017500000000502111751454675023401 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.systemsunion.LoggingServer; 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.NDC; /** A simple {@link SocketNode} based server.

	 Usage: java org.apache.log4j.net.SocketServer port configFile

	 where port is a part number where the server listens and
	 configFile is a configuration file fed to the {@link
	 PropertyConfigurator}.
   
@author Ceki Gülcü @since 0.8.4 */ public class SocketServer2 { static Category cat = Category.getInstance(SocketServer2.class.getName()); static int port; public static void main(String argv[]) { if(argv.length == 2) init(argv[0], argv[1]); else usage("Wrong number of arguments."); try { cat.info("Listening on port " + port); ServerSocket serverSocket = new ServerSocket(port); while(true) { 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 SocketNode2(socket)).start(); } } catch(Exception e) { e.printStackTrace(); } } static void usage(String msg) { System.err.println(msg); System.err.println( "Usage: java " + SocketServer2.class.getName() + " port configFile"); System.exit(1); } static void init(String portStr, String configFile) { try { port = Integer.parseInt(portStr); } catch(java.lang.NumberFormatException e) { e.printStackTrace(); usage("Could not interpret port number ["+ portStr +"]."); } PropertyConfigurator.configure(configFile); NDC.push("Server"); } } apache-log4j1.2-1.2.17.orig/contribs/MarkDouglas/mail-2001-01-170000644000175000017500000000440511751454675021732 0ustar tonytony Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Delivered-To: urba-cgu@urbanet.ch From: Mark Douglas To: "'cgu@urbanet.ch'" Subject: Enhanced SocketServer and SocketNode classes Date: Wed, 17 Jan 2001 09:57:38 -0000 X-Mailer: Internet Mail Service (5.5.2650.21) Hi Ceki, I have made small changes to SocketServer and SockerNode to allow the client machine name to be displayed in the logging output. This is important for us as we are using a single logging server with several clients. The new SocketServer2 and SocketNode2 classes (couldn't think of better names) prepends the NDC string with the clients Host Name (or IP address if the HostName can not be found). I thought the NDC string was a good place to add this information, but you may have a better place? I have created an NDC entry for the server such that server logging messages can easily be identified. I have included the two new source files plus a short example of the output. The output was generated with the following layout: %-6p (%9x:%-10t) %-40c{3} - %m%n <> <> <> Note: I have changed the package names for the two classes to fit with our package names - sorry. Also, I find it difficult to follow the coding style, so again, sorry. If you think this may be useful to others, please feel free to include it as an addition in the next release or change the current SocketServer and SocketNode objects to include this new behaviour by default. Mark Douglas Systems Union Group plc apache-log4j1.2-1.2.17.orig/contribs/MarkDouglas/Log.txt0000644000175000017500000000616211751454675021326 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ INFO ( Server:main ) systemsunion.LoggingServer.SocketServer2 - Connected to client at RDDSOWE2/129.153.78.195 INFO ( Server:main ) systemsunion.LoggingServer.SocketServer2 - Starting new socket node. INFO ( Server:main ) systemsunion.LoggingServer.SocketServer2 - Waiting to accept a new client. INFO ( RDDSOWE2:main ) systemsunion.SSTS.system - ClosedownController: starting INFO ( Server:main ) systemsunion.LoggingServer.SocketServer2 - Connected to client at RDDSOWE2/129.153.78.195 INFO ( Server:main ) systemsunion.LoggingServer.SocketServer2 - Starting new socket node. INFO ( Server:main ) systemsunion.LoggingServer.SocketServer2 - Waiting to accept a new client. INFO ( RDDSOWE2:main ) systemsunion.SSTS.system - ClosedownController: starting INFO ( RDDSOWE2:AWT-EventQueue-0) systemsunion.SSTS.components - Packing component Operator INFO ( RDDSOWE2:AWT-EventQueue-0) systemsunion.SSTS.components - Packing class file d:/SSDev/SSTS/components\Operator\Operator.class for component Operator INFO ( RDDSOWE2:AWT-EventQueue-0) systemsunion.SSTS.components - Packing class file d:/SSDev/SSTS/components\Operator\Operator.class for component Operator INFO ( RDDSOWE2:AWT-EventQueue-0) systemsunion.SSTS.components - Packing proxy class file d:/SSDev/SSTS/components\Operator\OperatorProxy.class for component Operator INFO ( RDDSOWE2:AWT-EventQueue-0) systemsunion.SSTS.components - Packing class file d:/SSDev/SSTS/components\Operator\OperatorProxy.class for component Operator INFO ( RDDSOWE2:AWT-EventQueue-0) systemsunion.SSTS.components - Packing test XML page file d:/SSDev/SSTS/components\Operator\Operator.XML for component Operator INFO ( RDDSOWE2:AWT-EventQueue-0) systemsunion.SSTS.components - Packing class file d:/SSDev/SSTS/components\Operator\Operator.XML for component Operator INFO ( RDDSOWE2:AWT-EventQueue-0) systemsunion.SSTS.components - Packing descriptor file d:/SSDev/SSTS/components\Operator\OperatorDeploymentDescriptor.XML for component Operator INFO ( RDDSOWE2:AWT-EventQueue-0) systemsunion.SSTS.components - Packing class file d:/SSDev/SSTS/components\Operator\OperatorDeploymentDescriptor.XML for component Operator apache-log4j1.2-1.2.17.orig/contribs/MarkDouglas/SocketNode2.java0000644000175000017500000000606611751454675023032 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.systemsunion.LoggingServer; import java.net.InetAddress; import java.net.Socket; import java.net.ServerSocket; import java.io.InputStream; import java.io.IOException; import java.io.ObjectInputStream; import org.apache.log4j.Category; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.Priority; import org.apache.log4j.NDC; // Contributors: Moses Hohman /** Read {@link LoggingEvent} objects sent from a remote client using Sockets (TCP). These logging events are logged according to local policy, as if they were generated locally.

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 SocketNode2 implements Runnable { Socket socket; ObjectInputStream ois; static Category cat = Category.getInstance(SocketNode2.class.getName()); public SocketNode2(Socket socket) { this.socket = socket; try { ois = new ObjectInputStream(socket.getInputStream()); } catch(Exception e) { cat.error("Could not open ObjectInputStream to "+socket, e); } } //public //void finalize() { //System.err.println("-------------------------Finalize called"); // System.err.flush(); //} public void run() { LoggingEvent event; Category remoteCategory; String strClientName; // Get the client name. InetAddress addr = socket.getInetAddress(); strClientName = addr.getHostName(); if(strClientName == null || strClientName.length() == 0) { strClientName = addr.getHostAddress(); } try { while(true) { event = (LoggingEvent) ois.readObject(); if(event.ndc != null) { event.ndc = strClientName + ":" + event.ndc; } else { event.ndc = strClientName; } remoteCategory = Category.getInstance(event.categoryName); remoteCategory.callAppenders(event); } } catch(java.io.EOFException e) { cat.info("Caught java.io.EOFException will close conneciton.", e); } catch(java.net.SocketException e) { cat.info("Caught java.net.SocketException, will close conneciton.", e); } catch(Exception e) { cat.error("Unexpected exception. Closing conneciton.", e); } try { ois.close(); } catch(Exception e) { cat.info("Could not close connection.", e); } } } apache-log4j1.2-1.2.17.orig/contribs/JimMoore/0000755000175000017500000000000012126647422017336 5ustar tonytonyapache-log4j1.2-1.2.17.orig/contribs/JimMoore/LoggingOutputStream.java0000644000175000017500000001346511751454673024204 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.*; import org.apache.log4j.*; /** * An OutputStream that flushes out to a Category.

* * Note that no data is written out to the Category until the stream is * flushed or closed.

* * Example:

 * // make sure everything sent to System.err is logged
 * System.setErr(new PrintStream(new LoggingOutputStream(Category.getRoot(), Priority.WARN), true));
 * 
 * // make sure everything sent to System.out is also logged
 * System.setOut(new PrintStream(new LoggingOutputStream(Category.getRoot(), Priority.INFO), true));
 * 
* * @author Jim Moore * @see Category */ public class LoggingOutputStream extends OutputStream { protected static final String LINE_SEPERATOR = System.getProperty("line.separator"); /** * Used to maintain the contract of {@link #close()}. */ protected boolean hasBeenClosed = false; /** * The internal buffer where data is stored. */ protected byte[] buf; /** * The number of valid bytes in the buffer. This value is always * in the range 0 through buf.length; elements * buf[0] through buf[count-1] contain valid * byte data. */ protected int count; /** * Remembers the size of the buffer for speed. */ private int bufLength; /** * The default number of bytes in the buffer. =2048 */ public static final int DEFAULT_BUFFER_LENGTH = 2048; /** * The category to write to. */ protected Category category; /** * The priority to use when writing to the Category. */ protected Priority priority; private LoggingOutputStream() { // illegal } /** * Creates the LoggingOutputStream to flush to the given Category. * * @param cat the Category to write to * * @param priority the Priority to use when writing to the Category * * @exception IllegalArgumentException * if cat == null or priority == null */ public LoggingOutputStream(Category cat, Priority priority) throws IllegalArgumentException { if (cat == null) { throw new IllegalArgumentException("cat == null"); } if (priority == null) { throw new IllegalArgumentException("priority == null"); } this.priority = priority; category = cat; bufLength = DEFAULT_BUFFER_LENGTH; buf = new byte[DEFAULT_BUFFER_LENGTH]; count = 0; } /** * Closes this output stream and releases any system resources * associated with this stream. The general contract of close * is that it closes the output stream. A closed stream cannot perform * output operations and cannot be reopened. */ public void close() { flush(); hasBeenClosed = true; } /** * Writes the specified byte to this output stream. The general * contract for write is that one byte is written * to the output stream. The byte to be written is the eight * low-order bits of the argument b. The 24 * high-order bits of b are ignored. * * @param b the byte to write * * @exception IOException * if an I/O error occurs. In particular, * an IOException may be thrown if the * output stream has been closed. */ public void write(final int b) throws IOException { if (hasBeenClosed) { throw new IOException("The stream has been closed."); } // don't log nulls if (b == 0) { return; } // would this be writing past the buffer? if (count == bufLength) { // grow the buffer final int newBufLength = bufLength+DEFAULT_BUFFER_LENGTH; final byte[] newBuf = new byte[newBufLength]; System.arraycopy(buf, 0, newBuf, 0, bufLength); buf = newBuf; bufLength = newBufLength; } buf[count] = (byte)b; count++; } /** * Flushes this output stream and forces any buffered output bytes * to be written out. The general contract of flush is * that calling it is an indication that, if any bytes previously * written have been buffered by the implementation of the output * stream, such bytes should immediately be written to their * intended destination. */ public void flush() { if (count == 0) { return; } // don't print out blank lines; flushing from PrintStream puts out these if (count == LINE_SEPERATOR.length()) { if ( ((char)buf[0]) == LINE_SEPERATOR.charAt(0) && ( ( count == 1 ) || // <- Unix & Mac, -> Windows ( (count == 2) && ((char)buf[1]) == LINE_SEPERATOR.charAt(1) ) ) ) { reset(); return; } } final byte[] theBytes = new byte[count]; System.arraycopy(buf, 0, theBytes, 0, count); category.log(priority, new String(theBytes)); reset(); } private void reset() { // not resetting the buffer -- assuming that if it grew that it // will likely grow similarly again count = 0; } } apache-log4j1.2-1.2.17.orig/contribs/JimMoore/mail-2001-03-13T06460000644000175000017500000001733311751454673021706 0ustar tonytony Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Copied from http://www.mail-archive.com/log4j-user@jakarta.apache.org/msg00445.html -------------------------------------------------------------------------------- RE: diverting System.stderr/stdout into log4j -------------------------------------------------------------------------------- From: Michael Smith Subject: RE: diverting System.stderr/stdout into log4j Date: Tue, 13 Mar 2001 06:46:04 -0800 -------------------------------------------------------------------------------- There is another way! In LogLog, completely ignore System.err. Instead, use the following to get the standard error stream: PrintStream err = new PrintStream(new FileOutputStream(FileDescriptor.err)); When you use System.setErr, it changes System.err, but not FileDescriptor.err, which maintains a descriptor for the original error stream. michael For a sample program to test this, see below: import java.io.*; public class Stderr { public static void main(String[] args) { // create a print stream to represent a redirect PrintStream nonStandardErr = new PrintStream(new ByteArrayOutputStream()); // Redirect standard out and standard err System.setOut(nonStandardErr); System.setErr(nonStandardErr); // attempt to print something System.err.println("You should *not* see this on the console!"); // the stuff that would appear in LogLog PrintStream logLogOut = new PrintStream(new FileOutputStream(FileDescriptor.err)); // attempt to print something logLogOut.println("You *should* see this on the console!"); } } > -----Original Message----- > From: Ceki Gülcü [mailto:cgu@qos.ch] > Sent: Monday, March 12, 2001 7:18 PM > To: LOG4J Users Mailing List > Subject: RE: diverting System.stderr/stdout into log4j > > > > Hate to follow up on myself, but the System.setErr method > reassigns the System.err variable. This can be deduced without > experimentation because the user calls the System.err variable > directly to print to the console, whatever it might be. Thus, the > reference itself must change to allow the System.err variable to > point to the new target stream. > > The funny part is that the err variable is declared 'public > final' in the JDK source code. The setErr method makes a call to > setErr0 which is declared as being 'native'. It looks like the > native part is circumventing the JDK restrictions. I find this > quite entertaining. Ceki > > At 00:58 13.03.2001 +0100, Ceki Gülcü wrote: > > >Running the risk of disappointing you here, although not full of > bugs, log4j is not bug-free as bugs creep out regularly. They > just get corrected quickly before many people are affected by them. > > > >The PrintStream se = System.err; LogLog.setPrintStream(see); > combination is simple and rather bright. I initially overlooked > the PrintStream se = System.err; part, making me think that a > lot of code needed to be modified to cater for the redirected > console case. The remedy looked worse than the illness. My fears > are largely unfounded and the solution should work quite well if > one is careful. > > > >Regards, Ceki > > > >ps: I wonder if System.err always refers to the real STDERR or > if really gets reassigned with the setErr call. It's easy to find out... > > > >At 23:20 12.03.2001 +0000, Joseph Panico wrote: > >>Of course log4j is completely bug free, but that doesn't > preclude user error. For instance, I neglected to add appenders > in my config file (actually I intentionally left them out, > thinking that would simply turn off logging) and then log4j went > into an infinite loop. The setPrintStream makes sense to me. > >> > >>joe > >> > >> > >>>From: Jim Moore > >>>Reply-To: "LOG4J Users Mailing List" > >>>To: 'LOG4J Users Mailing List' > >>>Subject: RE: diverting System.stderr/stdout into log4j > >>>Date: Mon, 12 Mar 2001 18:10:37 -0500 > >>> > >>>It doesn't. I haven't worried about it, since log4j doesn't > contain any > >>>bugs and therefore it would never happen... :) > >>> > >>>Probably the best way to handle it is to add a > >>>LogLog.setPrintStream(PrintStream) method, so you can do > something like: > >>> > >>>// remember STDERR > >>>PrintStream se = System.err; > >>> > >>>// make sure everything sent to System.err is logged > >>>System.setErr(new PrintStream(new > LoggingOutputStream(Category.getRoot(), > >>> Priority.WARN), true)); > >>> > >>>// make sure everything sent to System.out is also logged > >>>System.setOut(new PrintStream(new > LoggingOutputStream(Category.getRoot(), > >>> Priority.INFO), true)); > >>> > >>>// prevent infinate recursion in LogLog > >>>LogLog.setPrintStream(se); > >>> > >>> > >>>I can't think of any other way to do it in the current version besides > >>>getting extremely kludgey by checking the stack to see if it's > being called > >>>from LogLog and logging out the the "real" STDERR then in the > >>>LoggingOutputStream. It can be done on the theory that LogLog > wouldn't be > >>>called very often, but still... > >>> > >>>-Jim Moore > >>> > >>> > >>>-----Original Message----- > >>>From: Ceki Gülcü [mailto:cgu@qos.ch] > >>>Sent: Monday, March 12, 2001 5:15 PM > >>>To: LOG4J Users Mailing List > >>>Subject: RE: diverting System.stderr/stdout into log4j > >>> > >>> > >>>Jim, Joseph, > >>> > >>>Here is a link containing Jim's code: > >>> > >>>http://marc.theaimsgroup.com/?l=log4j-user&m=98097669218571&w=2 > >>> > >>>How does this code handle the infinite recursion problem mentioned by > >>>Joseph? Ceki > >>> > >>>At 17:03 12.03.2001 -0500, Jim Moore wrote: > >>>>Go to the mailing list archives (theAimsGroup.com is the > best) and search > >>>>for the thread with the subject of "Capturing System.err" > >>>> > >>>>-Jim Moore > >>>>"I think so, Brain; but if we gave peas a chance, won't the > lima beans get > >>>>jealous?" - Pinky > >>>> > >>>> > >>>>-----Original Message----- > >>>>From: Joseph Panico [mailto:joe_panico@hotmail.com] > >>>>Sent: Monday, March 12, 2001 4:43 PM > >>>>To: log4j-user@jakarta.apache.org > >>>>Subject: diverting System.stderr/stdout into log4j > >>>> > >>>> > >>>>Folks, > >>>> > >>>>We use a number of third-party packages that do > stderr.print... at various > >>>>random places in their code. I'm finding it quite useful to > divert these > >>>>messages into our log4j heirarchy. I do this by replacing > stderr/stdout > >>>with > >>>> > >>>>my own PrintStreams that log the lines to a special log4j > Category-- as > >>>>suggested on this list a while back. The only > fly-in-the-ointment with this > >>> > >>>>scheme is LogLog. If there is a problem with log4j such that > it cannot log > >>>>for some reason, then log4j internals use LogLog to attempt > to print an > >>>>error message. This obviously leads to an infinite recursion. > Has anyone > >>>>else been bothered by this? Would it make sense to add > interface to LogLog > >>>>which would set the PrintStream it uses to log its error messages to? > >>>> > >>>>thanks for any ideas > >>>> > >>>>joe apache-log4j1.2-1.2.17.orig/contribs/JimMoore/mail-2001-03-12T13260000644000175000017500000000451411751454673021676 0ustar tonytony Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Copied from: http://www.mail-archive.com/log4j-user@jakarta.apache.org/msg00430.html -------------------------------------------------------------------------------- diverting System.stderr/stdout into log4j -------------------------------------------------------------------------------- From: Joseph Panico Subject: diverting System.stderr/stdout into log4j Date: Mon, 12 Mar 2001 13:26:41 -0800 -------------------------------------------------------------------------------- Folks, We use a number of third-party packages that do stderr.print... at various random places in their code. I'm finding it quite useful to divert these messages into our log4j heirarchy. I do this by replacing stderr/stdout with my own PrintStreams that log the lines to a special log4j Category-- as suggested on this list a while back. The only fly-in-the-ointment with this scheme is LogLog. If there is a problem with log4j such that it cannot log for some reason, then log4j internals use LogLog to attempt to print an error message. This obviously leads to an infinite recursion. Has anyone else been bothered by this? Would it make sense to add interface to LogLog which would set the PrintStream it uses to log its error messages to? thanks for any ideas joe _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com --------------------------------------------------------------------- To unsubscribe, e-mail: log4j-user-unsubscribe@jakarta.apache.org For additional commands, e-mail: log4j-user-help@jakarta.apache.org apache-log4j1.2-1.2.17.orig/contribs/JimMoore/mail-2001-03-12T14540000644000175000017500000001066411751454673021703 0ustar tonytony Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Copied from: http://www.mail-archive.com/log4j-user@jakarta.apache.org/msg00433.html -------------------------------------------------------------------------------- RE: diverting System.stderr/stdout into log4j -------------------------------------------------------------------------------- From: Jim Moore Subject: RE: diverting System.stderr/stdout into log4j Date: Mon, 12 Mar 2001 14:54:13 -0800 -------------------------------------------------------------------------------- It doesn't. I haven't worried about it, since log4j doesn't contain any bugs and therefore it would never happen... :) Probably the best way to handle it is to add a LogLog.setPrintStream(PrintStream) method, so you can do something like: // remember STDERR PrintStream se = System.err; // make sure everything sent to System.err is logged System.setErr(new PrintStream(new LoggingOutputStream(Category.getRoot(), Priority.WARN), true)); // make sure everything sent to System.out is also logged System.setOut(new PrintStream(new LoggingOutputStream(Category.getRoot(), Priority.INFO), true)); // prevent infinate recursion in LogLog LogLog.setPrintStream(se); I can't think of any other way to do it in the current version besides getting extremely kludgey by checking the stack to see if it's being called from LogLog and logging out the the "real" STDERR then in the LoggingOutputStream. It can be done on the theory that LogLog wouldn't be called very often, but still... -Jim Moore -----Original Message----- From: Ceki Gülcü [mailto:cgu@qos.ch] Sent: Monday, March 12, 2001 5:15 PM To: LOG4J Users Mailing List Subject: RE: diverting System.stderr/stdout into log4j Jim, Joseph, Here is a link containing Jim's code: http://marc.theaimsgroup.com/?l=log4j-user&m=98097669218571&w=2 How does this code handle the infinite recursion problem mentioned by Joseph? Ceki At 17:03 12.03.2001 -0500, Jim Moore wrote: >Go to the mailing list archives (theAimsGroup.com is the best) and search >for the thread with the subject of "Capturing System.err" > >-Jim Moore >"I think so, Brain; but if we gave peas a chance, won't the lima beans get >jealous?" - Pinky > > >-----Original Message----- >From: Joseph Panico [mailto:joe_panico@hotmail.com] >Sent: Monday, March 12, 2001 4:43 PM >To: log4j-user@jakarta.apache.org >Subject: diverting System.stderr/stdout into log4j > > >Folks, > >We use a number of third-party packages that do stderr.print... at various >random places in their code. I'm finding it quite useful to divert these >messages into our log4j heirarchy. I do this by replacing stderr/stdout with > >my own PrintStreams that log the lines to a special log4j Category-- as >suggested on this list a while back. The only fly-in-the-ointment with this >scheme is LogLog. If there is a problem with log4j such that it cannot log >for some reason, then log4j internals use LogLog to attempt to print an >error message. This obviously leads to an infinite recursion. Has anyone >else been bothered by this? Would it make sense to add interface to LogLog >which would set the PrintStream it uses to log its error messages to? > >thanks for any ideas > >joe I hope to see you at my ApacheCon 2001 presentation entitled "Log4j, A Logging Package for Java". See http://ApacheCon.Com/2001/US/ for more details. ---- Ceki Gülcü Web: http://qos.ch av. de Rumine 5 email: cgu@qos.ch (preferred) CH-1005 Lausanne ceki_gulcu@yahoo.com Switzerland Tel: ++41 21 351 23 15 --------------------------------------------------------------------- To unsubscribe, e-mail: log4j-user-unsubscribe@jakarta.apache.org For additional commands, e-mail: log4j-user-help@jakarta.apache.org apache-log4j1.2-1.2.17.orig/contribs/KitchingSimon/0000755000175000017500000000000012126647422020363 5ustar tonytonyapache-log4j1.2-1.2.17.orig/contribs/KitchingSimon/DatagramStringWriter.java0000644000175000017500000001146511751454675025352 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.net; import java.io.Writer; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.DatagramPacket; import java.net.UnknownHostException; import java.net.SocketException; import java.io.IOException; import org.apache.log4j.helpers.LogLog; /** * DatagramStringWriter is a wrapper around the java.net.DatagramSocket class * so that it behaves like a java.io.Writer. */ public class DatagramStringWriter extends Writer { static final int SYSLOG_PORT = 514; private int port; private String host; private String encoding; private String prefix; private InetAddress address; private DatagramSocket ds; /** * This constructor assumes that it is sending to a remote syslog daemon * on the normal syslog port (514), and uses the default platform character * encoding when converting the message string to a byte sequence. */ public DatagramStringWriter(String host) { this(host, SYSLOG_PORT, null, null); } /** * This constructor sends messages to the specified host and port, and * uses the default platform character encoding when converting the message * string to a byte sequence. */ public DatagramStringWriter(String host, int port) { this(host, port, null, null); } /** * This constructor sends messages to the specified host and port, and * uses the specified character encoding when converting the message * string to a byte sequence. */ public DatagramStringWriter(String host, int port, String encoding) { this(host, port, null, null); } /** * This constructor sends messages to the specified host and port, and * uses the specified character encoding when converting the message * string to a byte sequence; the specified prefix (which may be null) * is prepended to each message. */ public DatagramStringWriter(String host, int port, String encoding, String prefix) { this.host = host; this.port = port; this.encoding = encoding; this.prefix = prefix; try { this.address = InetAddress.getByName(host); } catch (UnknownHostException e) { LogLog.error("Could not find " + host + ". All logging will FAIL.", e); } try { this.ds = new DatagramSocket(); } catch (SocketException e) { e.printStackTrace(); LogLog.error("Could not instantiate DatagramSocket to " + host + ". All logging will FAIL.", e); } } public void write(char[] buf, int off, int len) throws IOException { this.write(new String(buf, off, len)); } public void write(String string) throws IOException { if (prefix != null) { string = prefix + string; } byte[] rawData; if (this.encoding == null) { // convert to byte sequence using platform's default encoding rawData = string.getBytes(); } else { // convert to specified encoding - which may be sequence of // 8-bit chars, or multi-byte encodings like UTF-8 or UTF-16. // The receiving end had better be expecting whatever encoding // is used here on the sending end! rawData = string.getBytes(encoding); } DatagramPacket packet = new DatagramPacket( rawData, rawData.length, address, port); if(this.ds != null) { ds.send(packet); } else { LogLog.error( "write: failed to create DatagramPacket"); } } public void flush() {} public void close() {} /** * Set a string to be prefixed to every message sent by this Writer. * For example, this method could be used to prepend a syslog * facility/priority code on the front of each message. *

* Note that this method is not synchronised, so should not be called in * a situation where other threads may be logging messages at the same * moment. *

* @param prefix may be a prefix string, or null which indicates no * prefix should be added. */ public void setPrefix(String prefix){ this.prefix = prefix; } } apache-log4j1.2-1.2.17.orig/contribs/KitchingSimon/mail-2001-02-070000644000175000017500000000672411751454675022275 0ustar tonytony Delivered-To: urba-cgu@urbanet.ch Mailing-List: contact log4j-dev-help@jakarta.apache.org; run by ezmlm List-Post: List-Help: List-Unsubscribe: List-Subscribe: Reply-To: "LOG4J Developers Mailing List" Delivered-To: mailing list log4j-dev@jakarta.apache.org From: Kitching Simon To: "'log4j-dev@jakarta.apache.org'" Subject: PATCH: New classes: DatagramStreamAppender & friends Date: Wed, 7 Feb 2001 12:41:54 +0100 X-Mailer: Internet Mail Service (5.5.2650.21) X-Spam-Rating: h31.sny.collab.net 1.6.2 0/1000/N Hi log4j developers.... Here, for your consideration, is a set of files that implement an Appender which sends messages to a remote host/port via UDP (datagram). There was brief discussion of this Appender on the log4j-user group, about a week ago. Ceki suggested that the Appender send serialized log event objects over UDP; while this approach has a number of advantages, I have decided to instead perform the message formatting at the client end, mainly so that: (a) the UDP server application does not have to be in java (b) non-java clients can send messages to the same UDP server. The appender has been named "DatagramStringAppender" to allow someone to write a serialization-based version at some later time, if desired, without any name confusion. ------------------------------ Notes: DatagramStringAppender is based on SyslogAppender, but with a fair number of changes. DatagramStringWriter is based on SyslogWriter, with a few changes. In particular, it takes an "encoding" parameter, so that the character encoding used can be specified, and a "port". SingleLineTracerPrintWriter is almost identical to SyslogTracerPrintWriter; just the name & some comments have changed. [I didn't want to call a class called SyslogXXX from the DatagramStreamAppender classes] ------------------------------ If this patch is accepted, then it may be worth rewriting SyslogAppender to use the DatagramStringWriter and SingleLineTracerPrintWriter classes. These classes should be compatible with SyslogAppender, as they implement the same functionality, or a superset of the Syslog functionality, and have more "general" names. ------------------------------ <> <> <> -------------------------------- And here's a simple perl UDP server, and an xml config file for testing the appender. <> <> Regards, Simon apache-log4j1.2-1.2.17.orig/contribs/KitchingSimon/DatagramStringAppender.java0000644000175000017500000002300111751454675025621 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 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.Priority; import org.apache.log4j.Layout; import org.apache.log4j.helpers.SingleLineTracerPrintWriter; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.helpers.QuietWriter; /** Use DatagramStringAppender to send log messages to a remote daemon which accepts Datagram (UDP) messages.

The benefits of UDP are that the client is guarunteed not to slow down if the network or remote log daemon is slow, and that no permanent TCP connection between client and server exists.

The disadvantages are that log messages can be lost if the network or remote daemon are under excessive load.

This class builts the final message string before sending the UDP packet, hence the "string" component in the class name. This means that the receiving application can be written in any language. The data is transmitted in whatever encoding is specified in the configuration file; this may be an 8-bit encoding (eg ISO-8859-1, also known as LATIN-1) or a larger encoding, eg UTF-16.

An alternative to building the message string within DatagramStringAppender would be to serialize & send the complete logging event object (perhaps such a class could be called a DatagramSerialAppender??). The receiving end could then be configured with appropriate Layout objects to generate the actual logged messages. This would ensure that the logging of messages from different sources is done in a consistent format, and give a central place to configure that format. It would ensure (by transmitting messages as unicode) that the receiving end could control the encoding in which the output is generated. It also would possibly allow he receiving end to use the full log4j flexibility to pass the event to different appenders at the receiving end, as the category information is retained, etc. However, this does require that the receiving end is in java, and that all clients of the logging daemon are java applications. In contrast, this DatagramStringAppender can send mesages to a log daemon that accepts messages from a variety of sources. @author Simon Kitching */ public class DatagramStringAppender extends AppenderSkeleton { /** A string constant used in naming the option for setting the destination server for messages. Current value of this string constant is DatagramHost. */ public static final String DATAGRAM_HOST_OPTION = "DatagramHost"; /** A string constant used in naming the option for setting the destination port for messages. Current value of this string constant is DatagramPort. */ public static final String DATAGRAM_PORT_OPTION = "DatagramPort"; /** A string constant used in naming the option for setting the character encoding used when generating the log message. Current value of this string constant is DatagramEncoding. */ public static final String DATAGRAM_ENCODING_OPTION = "DatagramEncoding"; /** The default value for the "host" attribute, ie the machine to which messages are sent. Current value of this string constant is localhost. */ public static final String DEFAULT_HOST = "localhost"; /** The default value for the "port" attribute, ie the UDP port to which messages are sent. Current value of this integer constant is 8200. This value was chosen for no particular reason. */ public static final int DEFAULT_PORT = 8200; /** The default value for the "encoding" attribute, ie the way in which unicode message strings are converted into a stream of bytes before their transmission as a UDP packet. The current value of this constant is null, which means that the default platform encoding will be used. */ public static final String DEFAULT_ENCODING = null; String host = DEFAULT_HOST; int port = DEFAULT_PORT; String encoding = DEFAULT_ENCODING; SingleLineTracerPrintWriter stp; QuietWriter qw; public DatagramStringAppender() { this.setDestination(DEFAULT_HOST, DEFAULT_PORT, DEFAULT_ENCODING); } public DatagramStringAppender(Layout layout) { this.setLayout(layout); this.setDestination(DEFAULT_HOST, DEFAULT_PORT, DEFAULT_ENCODING); } public DatagramStringAppender(Layout layout, String host, int port) { this.setLayout(layout); this.setDestination(host, port, DEFAULT_ENCODING); } public DatagramStringAppender(Layout layout, String host, int port, String encoding) { this.setLayout(layout); this.setDestination(host, port, encoding); } /** Release any resources held by this Appender */ public void close() { closed = true; // A DatagramWriter is UDP based and needs no opening. Hence, it // can't be closed. We just unset the variables here. qw = null; stp = null; } public void append(LoggingEvent event) { if(!isAsSevereAsThreshold(event.priority)) return; // We must not attempt to append if qw is null. if(qw == null) { errorHandler.error( "No host is set for DatagramStringAppender named \"" + this.name + "\"."); return; } String buffer = layout.format(event); qw.write(buffer); if(event.throwable != null) event.throwable.printStackTrace(stp); else if (event.throwableInformation != null) { // we must be the receiver of a serialized/deserialized LoggingEvent; // the event's throwable member is transient, ie becomes null when // deserialized, but that's ok because throwableInformation should // have the string equivalent of the same info (ie stack trace) qw.write(event.throwableInformation); } } /** Activate the options set via the setOption method. @see #setOption */ public void activateOptions() { this.setDestination(this.host, this.port, this.encoding); } /** Returns the option names for this component, namely the string array consisting of {{@link #DATAGRAM_HOST_OPTION}, {@link #DATAGRAM_PORT_OPTION}, {@link #DATAGRAM_ENCODING_OPTION} */ public String[] getOptionStrings() { return OptionConverter.concatanateArrays(super.getOptionStrings(), new String[] { DATAGRAM_HOST_OPTION, DATAGRAM_PORT_OPTION, DATAGRAM_ENCODING_OPTION}); } /** The DatagramStringAppender requires a layout. Hence, this method return true. @since 0.8.4 */ public boolean requiresLayout() { return true; } /** Set DatagramStringAppender specific parameters.

The recognized options are DatagramHost, DatagramPort and DatagramEncoding, i.e. the values of the string constants {@link #DATAGRAM_HOST_OPTION}, {@link #DATAGRAM_PORT_OPTION} and {@link #DATAGRAM_ENCODING_OPTION} respectively.

DatagramHost
The name (or ip address) of the host machine where log output should go. If the DatagramHost is not set, then this appender will default to {@link #DEFAULT_HOST}.

DatagramPort
The UDP port number where log output should go. See {@link #DEFAULT_PORT}

DatagramEncoding
The ISO character encoding to be used when converting the Unicode message to a sequence of bytes within a UDP packet. If not defined, then the encoding defaults to the default platform encoding.
*/ public void setOption(String option, String value) { if(value == null) return; super.setOption(option, value); if(option.equals(DATAGRAM_HOST_OPTION)) { this.host = value; } else if(option.equals(DATAGRAM_PORT_OPTION)) { this.port = OptionConverter.toInt(value, DEFAULT_PORT); } else if(option.equals(DATAGRAM_ENCODING_OPTION)) { this.encoding = value; } } public void setDestination(String host, int port, String encoding) { if (host==null) { LogLog.error("setDestination: host is null"); host = DEFAULT_HOST; } this.host = host; this.port = port; this.encoding = encoding; this.qw = new QuietWriter( new DatagramStringWriter(host, port, encoding), errorHandler); this.stp = new SingleLineTracerPrintWriter(qw); } public void setLayout(Layout layout) { this.layout = layout; } } apache-log4j1.2-1.2.17.orig/contribs/KitchingSimon/udpserver.pl0000644000175000017500000000500111751454675022744 0ustar tonytony#!/opt/perl5/bin/perl -w # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. use strict; use Socket; use IO::Socket; use Sys::Hostname; main(); exit(0); sub main() { my $MAX_MSG_SIZE = 16384; # 16KBytes should be enough... my $svrport = 8300; my $svriaddr = gethostbyname(hostname()); my $svrproto = getprotobyname('udp'); my $svrpaddr = sockaddr_in($svrport, $svriaddr); socket(SOCKET, PF_INET, SOCK_DGRAM, $svrproto) || die "socket: $!"; bind(SOCKET, $svrpaddr) || die "bind: $!"; my $rin = ''; vec($rin, fileno(SOCKET), 1) = 1; # timeout after 10.0 seconds # at some time, I'm going to add signal handlers so that signals can be # sent to cause logfile rollover, or tidy exit...then the timeout will # come in useful.. my $exit = 0; while (!$exit) { my $rout = $rin; # select(readvec, writevec, exceptionvec, timeout) # : returns # of selected filehandles, modifies # vector parameters so that set bits indicate # filehandles which are readable, writable or have # an exception state my $nSelected = select($rout, undef, undef, 10.0); if ($nSelected == 0) { # timedout : go back to start of loop next; } my $msgData = ''; my $clientpaddr = recv(SOCKET, $msgData, $MAX_MSG_SIZE, 0); if (!$clientpaddr) { die "recv: $!"; } my ($clientport, $clientiaddr) = sockaddr_in($clientpaddr); my $clienthost = gethostbyaddr($clientiaddr, AF_INET); if (!$clienthost) { # unable to determine name for client : show raw ip address $clienthost = inet_ntoa($clientiaddr); } print "$clienthost:$msgData\n"; } } apache-log4j1.2-1.2.17.orig/contribs/KitchingSimon/SingleLineTracerPrintWriter.java0000644000175000017500000000441511751454675026647 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.helpers; /** SingleLineTracerPrintWriter overrides the println function in TracerPrintWriter by replacing the TAB character with spaces. It also does not print the "\n".

The default format generated by TracerPrintWriter for exceptions prints on multiple lines, which does not interact well with some logging systems. On the other hand, a stack-trace on one line can be a mite difficult to read, so this class should only be used where really necessary :-)

For syslog daemons, tabs in messages are not friendly, hence the replacement of tabs by spaces here. It shouldn't do any harm to do this for all messages...

Perhaps it might be better to enhance TracerPrintWriter to have a configuration item for one-line or multi-line mode... */ public class SingleLineTracerPrintWriter extends TracerPrintWriter { static String TAB = " "; public SingleLineTracerPrintWriter(QuietWriter qWriter) { super(qWriter); } /** Make the first Exception line print properly by omitting the \n at the end. */ public void println(Object o) { this.qWriter.write(o.toString()); } // Note: the Char[] form is handled by the TracerPrinterWriter super // class /** Remove the first character from the string (usually a TAB) and do not print "\n" */ public void println(String s) { // remove '^I' and replace it with 4 spaces this.qWriter.write(TAB+s.substring(1)); } } apache-log4j1.2-1.2.17.orig/contribs/KitchingSimon/logconfig.xml0000644000175000017500000000410411751454675023064 0ustar tonytony apache-log4j1.2-1.2.17.orig/contribs/JamesHouse/0000755000175000017500000000000012126647422017660 5ustar tonytonyapache-log4j1.2-1.2.17.orig/contribs/JamesHouse/mail-2001-01-230000644000175000017500000000640211751454673021556 0ustar tonytony Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Delivered-To: urba-cgu@urbanet.ch From: James House To: Ceki Gulcu Subject: RE: Buffering issues Date: Tue, 23 Jan 2001 11:38:30 -0800 X-Mailer: Internet Mail Service (5.5.2650.21) Ceki, Most of the "speed" issues can be easily solved, as demonstrated in the new versions of the files that are attached, and as described here: The "drawing" of the panel is time consuming. And let's face it: we will never build a swing component that can re-draw itself thousands of times per second - nor could the human eye keep up with that anyway (60-ish redraws per second is the limit of what most humans can perceive). I think you'll agree that regardless of which choice of swing components, the issue of not being able to draw more than 100 times per second (if that) will be a constant. Possible solutions to wasting a lot of time redrawing are: * Redraw every N messages * Redraw every N milliseconds * Redraw when a message of a high priority is received * Only redraw if the changes (new messages) are visible (depending on scroll-bar position) I made some very small changes (which are some of what I outlined in the previous e-mail as things on the to-do list), and you should be able to see a great difference in performance. In general the changes are: Use a "queue" to asynchronously deliver the messages to the panel for updating, rather than having the calling thread (the one generating the log message) be responsible for re-drawing the panel - this frees up the thread to continue on without waiting for the logging mechanism. The "queue" has a thread that wakes up every N milliseconds, or when a message of a specified priority arrives. It then delivers all queued messages to the panel, which then redraws ONCE for the entire batch of queued messages IF the new messages are visible in the display. With the "tail" mechanism turned on (so that any new set of messages forces a redraw, because the last message is always visible), the panel can now log about a thousand messages in 1 second. With tail turned off (so that redraw is only required if the panel is showing the space the new messages will be printed), it can receive over a 100,000 messages in just a few seconds. Also, most of the flicker is already eliminated. Again, everything in the code is really "roughed in" - just there to give the general idea, not necessarily to do things in the best way - but I really feel that this kind of solution is what you'll have to end up with in the long term. James apache-log4j1.2-1.2.17.orig/contribs/JamesHouse/LogTextPanel.java0000644000175000017500000001255711751454673023112 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.gui; import java.awt.Color; import java.awt.Image; import java.awt.Toolkit; import java.awt.BorderLayout; import javax.swing.*; import javax.swing.text.StyledDocument; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.MutableAttributeSet; import javax.swing.text.StyleConstants; import java.util.Hashtable; import java.util.StringTokenizer; import java.util.Enumeration; import java.util.ArrayList; import org.apache.log4j.*; public class LogTextPanel extends JPanel { private JScrollBar scrollBar; private JTextPane textPane; private JCheckBox cbxTail; private StyledDocument doc; private Hashtable fontAttributes; private int eventBufferMaxSize = 10000; private ArrayList eventBuffer = new ArrayList(eventBufferMaxSize); private int eventViewIndex = 0; public LogTextPanel() { constructComponents(); createDefaultFontAttributes(); } private void constructComponents() { // setup the panel's additional components... this.setLayout(new BorderLayout()); cbxTail = new JCheckBox(); cbxTail.setSelected(true); cbxTail.setText("Tail log events"); JPanel bottomPanel = new JPanel(); bottomPanel.add(cbxTail, null); textPane = new JTextPane(); textPane.setEditable(false); textPane.setText(""); doc = textPane.getStyledDocument(); scrollBar = new JScrollBar(JScrollBar.VERTICAL); this.add(bottomPanel, BorderLayout.SOUTH); this.add(scrollBar, BorderLayout.EAST); this.add(textPane, BorderLayout.CENTER); } public void setTextBackground(Color color) { textPane.setBackground(color); } public void setTextBackground(String v) { textPane.setBackground(parseColor(v)); } private void createDefaultFontAttributes() { Priority[] prio = Priority.getAllPossiblePriorities(); fontAttributes = new Hashtable(); for (int i=0; i= eventBufferMaxSize) { for(int i=0; i < evts.length; i++) { eventBuffer.remove(0); } eventViewIndex -= evts.length; if(eventViewIndex < 0) eventViewIndex = 0; } for(int i=0; i < evts.length; i++) eventBuffer.add(evts[i]); if((eventBuffer.size() > maxR) && cbxTail.isSelected()) { eventViewIndex = (eventBuffer.size() - maxR); } // only redraw if new line is visible... if((maxR < 0) || (eventBuffer.size() >= eventViewIndex && eventBuffer.size() <= (eventViewIndex + maxR))) drawText(); } int maxR = -1; void drawText() { if(maxR < 0) maxR = textPane.getHeight() / textPane.getFontMetrics(textPane.getFont()).getHeight(); try { doc.remove(0, doc.getLength()); } catch(Exception e) { e.printStackTrace(); } for(int i=eventViewIndex; (i < eventBuffer.size()) && (i < (eventViewIndex + maxR)); i++) { EventBufferElement evt = (EventBufferElement)eventBuffer.get(i); try { doc.insertString(doc.getLength(), evt.text, (MutableAttributeSet)fontAttributes.get(evt.prio)); } catch(Exception e) { e.printStackTrace(); } } } }apache-log4j1.2-1.2.17.orig/contribs/JamesHouse/TextPanelAppender.java0000644000175000017500000001415011751454673024116 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.gui; import java.awt.Color; import java.awt.Image; import java.awt.Toolkit; import java.io.*; import java.net.URL; import java.util.Enumeration; import java.util.StringTokenizer; import java.util.Hashtable; import java.util.ArrayList; import javax.swing.JPanel; import org.apache.log4j.*; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.helpers.Loader; import org.apache.log4j.helpers.QuietWriter; import org.apache.log4j.helpers.TracerPrintWriter; import org.apache.log4j.helpers.OptionConverter; /** * * @author James House */ public class TextPanelAppender extends AppenderSkeleton { TracerPrintWriter tp; StringWriter sw; QuietWriter qw; LogTextPanel logTextPanel; LogPublishingThread logPublisher; final String COLOR_OPTION_FATAL = "Color.Fatal"; final String COLOR_OPTION_ERROR = "Color.Error"; final String COLOR_OPTION_WARN = "Color.Warn"; final String COLOR_OPTION_INFO = "Color.Info"; final String COLOR_OPTION_DEBUG = "Color.Debug"; final String COLOR_OPTION_BACKGROUND = "Color.Background"; final String FONT_NAME_OPTION = "Font.Name"; final String FONT_SIZE_OPTION = "Font.Size"; final String EVENT_BUFFER_SIZE_OPTION = "EventBuffer.Size"; public TextPanelAppender(Layout layout, String name) { this.layout = layout; this.name = name; this.sw = new StringWriter(); this.qw = new QuietWriter(sw, errorHandler); this.tp = new TracerPrintWriter(qw); setLogTextPanel(new LogTextPanel()); logPublisher = new LogPublishingThread(logTextPanel, Priority.ERROR, 500); //logPublisher = new LogPublishingThread(logTextPanel, null, 500); } public void close() { } public void append(LoggingEvent event) { String text = this.layout.format(event); // Print Stacktrace // Quick Hack maybe there is a better/faster way? if (event.throwable!=null) { event.throwable.printStackTrace(tp); for (int i=0; i< sw.getBuffer().length(); i++) { if (sw.getBuffer().charAt(i)=='\t') sw.getBuffer().replace(i,i+1," "); } text += sw.toString(); sw.getBuffer().delete(0,sw.getBuffer().length()); } else if(!text.endsWith("\n")) text += "\n"; logPublisher.publishEvent(event.priority, text); } public JPanel getLogTextPanel() { return logTextPanel; } public String[] getOptionStrings() { return new String[] { COLOR_OPTION_FATAL, COLOR_OPTION_ERROR, COLOR_OPTION_WARN, COLOR_OPTION_INFO, COLOR_OPTION_DEBUG, COLOR_OPTION_BACKGROUND, FONT_NAME_OPTION, FONT_SIZE_OPTION}; } public void setName(String name) { this.name = name; } protected void setLogTextPanel(LogTextPanel logTextPanel) { this.logTextPanel = logTextPanel; logTextPanel.setTextBackground(Color.white); } public void setOption(String option, String value) { if (option.equalsIgnoreCase(COLOR_OPTION_FATAL)) logTextPanel.setTextColor(Priority.FATAL,value); if (option.equalsIgnoreCase(COLOR_OPTION_ERROR)) logTextPanel.setTextColor(Priority.ERROR,value); if (option.equalsIgnoreCase(COLOR_OPTION_WARN)) logTextPanel.setTextColor(Priority.WARN,value); if (option.equalsIgnoreCase(COLOR_OPTION_INFO)) logTextPanel.setTextColor(Priority.INFO,value); if (option.equalsIgnoreCase(COLOR_OPTION_DEBUG)) logTextPanel.setTextColor(Priority.DEBUG,value); if (option.equalsIgnoreCase(COLOR_OPTION_BACKGROUND)) logTextPanel.setTextBackground(value); if (option.equalsIgnoreCase(FONT_SIZE_OPTION)) logTextPanel.setTextFontSize(Integer.parseInt(value)); if (option.equalsIgnoreCase(FONT_NAME_OPTION)) logTextPanel.setTextFontName(value); if (option.equalsIgnoreCase(EVENT_BUFFER_SIZE_OPTION)) logTextPanel.setEventBufferSize(Integer.parseInt(value)); return; } public boolean requiresLayout() { return true; } class LogPublishingThread extends Thread { LogTextPanel logTextPanel; ArrayList evts; Priority triggerPrio; long pubInterval; public LogPublishingThread(LogTextPanel logTextPanel, Priority triggerPrio, long pubInterval) { this.logTextPanel = logTextPanel; this.evts = new ArrayList(1000); this.triggerPrio = triggerPrio; this.pubInterval = pubInterval; //this.setPriority(Thread.NORM_PRIORITY - 1); this.start(); } public void run() { while(true) { synchronized(evts) { try { evts.wait(pubInterval); } catch(InterruptedException e) {} logTextPanel.newEvents((EventBufferElement[])evts.toArray(new EventBufferElement[evts.size()])); evts.clear(); } } } public void publishEvent(Priority prio, String text) { synchronized(evts) { evts.add(new EventBufferElement(prio, text)); if(triggerPrio != null && prio.isGreaterOrEqual(triggerPrio)) evts.notify(); } } } } // TextPaneAppender class EventBufferElement { public String text; public Priority prio; public int numLines; EventBufferElement(Priority prio, String text) { this.prio = prio; this.text = text; numLines = 1; int pos = pos = text.indexOf('\n', 0); int len = text.length() - 1; while( (pos > 0) && (pos < len) ) numLines++; pos = text.indexOf('\n', pos + 1); } } apache-log4j1.2-1.2.17.orig/contribs/JamesHouse/LogTextPanelExample.java0000644000175000017500000001047111751454673024417 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.gui.examples; import javax.swing.*; import java.awt.*; import java.awt.event.*; import org.apache.log4j.*; import org.apache.log4j.gui.TextPanelAppender; public class LogTextPanelExample { boolean packFrame = false; String catName = "dum.cat.name"; public LogTextPanelExample() { // setup the logging TextPanelAppender tpa = new TextPanelAppender(new PatternLayout("%-5p %d [%t]: %m%n"), "logTextPanel"); tpa.setThreshold(Priority.DEBUG); Category cat = Category.getInstance(catName); cat.addAppender(tpa); LogFrame frame = new LogFrame(tpa); frame.validate(); //Center the frame (window), and show it Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = frame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2); frame.setVisible(true); } /**Main method*/ public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { e.printStackTrace(); } LogTextPanelExample foo = new LogTextPanelExample(); new LogTextPanelExampleGenThread(foo.catName); } } class LogFrame extends JFrame { public LogFrame(TextPanelAppender tpa) { enableEvents(AWTEvent.WINDOW_EVENT_MASK); JPanel contentPane = (JPanel) this.getContentPane(); contentPane.setLayout(new BorderLayout()); this.setSize(new Dimension(600, 400)); this.setTitle("LogTextPanel Example"); contentPane.add(tpa.getLogTextPanel(), BorderLayout.CENTER); } // exit when window is closed protected void processWindowEvent(WindowEvent e) { super.processWindowEvent(e); if (e.getID() == WindowEvent.WINDOW_CLOSING) { System.exit(0); } } } class LogTextPanelExampleGenThread extends Thread { String catName; public LogTextPanelExampleGenThread(String catName) { this.catName = catName; this.setPriority(Thread.NORM_PRIORITY - 1); this.start(); } public void run() { Category cat = Category.getInstance(catName); int cnt = 0; while(true) { cnt++; int randEvt = (int)(Math.random() * 125); if(randEvt < 3) cat.fatal("{" + cnt + "} Something screwed up bad."); else if(randEvt < 10) cat.error("{" + cnt + "} An error occured while trying to delete all of your files."); else if(randEvt < 25) cat.warn("{" + cnt + "} It seems as if your hard disk is getting full."); else if(randEvt < 55) cat.info("{" + cnt + "} It is now time for tea."); else if(randEvt < 65) cat.debug("{" + cnt + "} Something bad is happening on line 565 of com.foo.Crap"); else if(randEvt < 75) cat.debug("{" + cnt + "} Input value for xe343dd is not equal to xe39dfd!"); else if(randEvt < 85) cat.debug("{" + cnt + "} Successfully reached line 2312 of com.foo.Goo"); else if(randEvt < 105) cat.debug("{" + cnt + "} Here is some extra handy debugging information for you."); else if(randEvt < 115) cat.debug("{" + cnt + "} The file you are about to write to is not open."); else if(randEvt < 125) cat.debug("{" + cnt + "} The input value to the method was ."); try { Thread.sleep(10); } catch(Exception e) {} } } }apache-log4j1.2-1.2.17.orig/contribs/EirikLygre/0000755000175000017500000000000012126647422017663 5ustar tonytonyapache-log4j1.2-1.2.17.orig/contribs/EirikLygre/DailyFileAppender1.java0000644000175000017500000001637711751454673024155 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 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 org.apache.log4j.helpers.OptionConverter; import org.apache.log4j.helpers.QuietWriter; import org.apache.log4j.helpers.CountingQuietWriter; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.ErrorCode; /** DailyFileAppender extends FileAppender to use filenames formatted with date/time information. The filename is recomputed every day at midnight. Note that the filename doesn't have to change every day, making it possible to have logfiles which are per-week or per-month. The appender computes the proper filename using the formats specified in java.text.SimpleDateFormat. The format requires that most static text is enclosed in single quotes, which are removed. The examples below show how quotes are used to embed static information in the format. Sample filenames: Filename pattern Filename "'/logs/trace-'yyyy-MM-dd'.log'" /logs/trace-2000-12-31.log "'/logs/trace-'yyyy-ww'.log'" /logs/trace-2000-52.log @author Eirik Lygre */ public class DailyFileAppender extends FileAppender { /** A string constant used in naming the option for setting the filename pattern. Current value of this string constant is FileNamePattern. */ static final public String FILE_NAME_PATTERN_OPTION = "FilePattern"; /** The filename pattern */ private String fileNamePattern = null; /** The actual formatted filename that is currently being written to */ private String currentFileName = null; /** The timestamp when we shall next recompute the filename */ private long nextFilenameComputingMillis = System.currentTimeMillis () - 1; /** The default constructor does no longer set a default layout nor a default output target. */ public DailyFileAppender() { } /** Instantiate a RollingFileAppender and open the file designated by filename. The opened filename will become the ouput destination for this appender.

If the append parameter is true, the file will be appended to. Otherwise, the file desginated by filename will be truncated before being opened. */ public DailyFileAppender (Layout layout,String filename,boolean append) throws IOException { super(layout, filename, append); } /** Instantiate a FileAppender and open the file designated by filename. The opened filename will become the output destination for this appender.

The file will be appended to. */ public DailyFileAppender (Layout layout,String filename) throws IOException { super(layout, filename); } /** Set the current output file. The function will compute a new filename, and open a new file only when the name has changed. The function is automatically called once a day, to allow for daily files -- the purpose of this class. */ public synchronized void setFile(String fileName, boolean append) throws IOException { /* Compute filename, but only if fileNamePattern is specified */ if (fileNamePattern == null) { errorHandler.error("Missing file pattern (" + FILE_NAME_PATTERN_OPTION + ") in setFile()."); return; } Date now = new Date(); fileName = new SimpleDateFormat(fileNamePattern).format (now); if (fileName.equals(currentFileName)) return; /* Set up next filename checkpoint */ DailyFileAppenderCalendar c = new DailyFileAppenderCalendar(); c.rollToNextDay (); nextFilenameComputingMillis = c.getTimeInMillis (); currentFileName = fileName; super.setFile(fileName, append); } /** This method differentiates RollingFileAppender from its super class. */ protected void subAppend(LoggingEvent event) { if (System.currentTimeMillis () >= nextFilenameComputingMillis) { try { setFile (super.fileName, super.fileAppend); } catch(IOException e) { System.err.println("setFile(null, false) call failed."); e.printStackTrace(); } } super.subAppend(event); } /** Retuns the option names for this component, namely {@link #FILE_NAME_PATTERN_OPTION} in addition to the options of {@link FileAppender#getOptionStrings FileAppender}. */ public String[] getOptionStrings() { return OptionConverter.concatanateArrays(super.getOptionStrings(), new String[] {FILE_NAME_PATTERN_OPTION}); } /** Set the options for the appender */ public void setOption(String key, String value) { super.setOption(key, value); if(key.equalsIgnoreCase(FILE_NAME_PATTERN_OPTION)) { fileNamePattern = value; } } /** If the a value for {@link #FILE_OPTION} is non-null, then {@link #setFile} is called with the values of {@link #FILE_OPTION} and {@link #APPEND_OPTION}. @since 0.8.1 */ public void activateOptions() { try { setFile(null, super.fileAppend); } catch(java.io.IOException e) { errorHandler.error("setFile(null,"+fileAppend+") call failed.", e, ErrorCode.FILE_OPEN_FAILURE); } } } /** DailyFileAppenderCalendar is a helper class to DailyFileAppender. Using this class, it is easy to compute and access the next Millis() It subclasses the standard java.util.GregorianCalendar-object, to allow access to the protected function getTimeInMillis(), which it then exports. @author Eirik Lygre */ class DailyFileAppenderCalendar extends java.util.GregorianCalendar { /** Returns the current time in Millis */ public long getTimeInMillis() { return super.getTimeInMillis(); } /** Roll the date to the next hour, with minute, second and millisecond set to zero. */ public void rollToNextDay () { this.add(java.util.Calendar.DATE, 0); this.add(java.util.Calendar.HOUR, 0); this.set(java.util.Calendar.MINUTE, 0); this.set(java.util.Calendar.SECOND, 0); this.set(java.util.Calendar.MILLISECOND, 0); } }apache-log4j1.2-1.2.17.orig/contribs/EirikLygre/mail-2001-01-180000644000175000017500000000257311751454673021572 0ustar tonytony Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Delivered-To: urba-cgu@urbanet.ch To: Ceki Gulcu From: Eirik_Lygre/evita/no%EVITA@evita.no Subject: Re: Suggestion for new appender "DailyFileAppender" Date: Thu, 18 Jan 2001 20:18:27 +0100 X-MIMETrack: Serialize by Router on domino1/evita/no(Release 5.0.5 |September 22, 2000) at 18.01.2001 20:18:30 This version subclasses GregorianCalendar, to get access to the millis-variable used in the Calendar-classes (it is protected). What do you think? Eirik ++++++++++ Eirik Lygre eirik.lygre@evita.no e-vita as, Stortorvet 3, Oslo Mobil: (+47) 905 66476 Fax: (+47) 23 35 70 51 DailyFileAppender1.jav apache-log4j1.2-1.2.17.orig/contribs/CONTENTS0000644000175000017500000000630011751454703016775 0ustar tonytony Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ---------------------------------------------------------------------- WARNING: The contents of the contribs/ directory is not guaranteed to work properly. Some files might not even compile. ---------------------------------------------------------------------- Each directory corresponds to the name of an author containing his/her contributions. EirikLygre/ ========== DailyFileAppender1.java DailyFileAppender extends FileAppender to use filenames formatted with date/time information. The filename is recomputed every day at midnight. Note that the filename doesn't have to change every day, making it possible to have logfiles which are per-week or per-month. JamesHouse/ ========== LogTextPanel.java LogTextPanelExample.java TextPanelAppender.java JimMoore/ ======== LoggingOutputStream.java Allows the user to divert System.out and System.err to log4j. WARNING: Be sure to read the included e-mails to understand the dangers of WARNING: redirecting the console to LoggingOutputStream. LeosLiterak/ =========== TempFileAppender.java TempFileAppender creates new unique file for each logging statement. MarkDouglas/ =========== SocketNode2.java SocketServer2.java Small changes to SocketServer and SockerNode to allow the client machine name to be displayed in the logging output. This is important for us as we are using a single logging server with several clients. KevinSteppe/ =========== JDBCAppender.java JDBCTest.java KitchingSimon/ ============= DatagramStringAppender.java DatagramStringWriter.java logconfig.xml SingleLineTracerPrintWriter.java udpserver.pl A set of files that implement an Appender which sends messages to a remote host/port via UDP (datagram). Message formatting is performed at the at the client end, mainly so that: (a) the UDP server application does not have to be in java (b) non-java clients can send messages to the same UDP server. ThomasFenner/ ============ Yet one more JDBCAppender. JDBCAppender.java JDBCConnectionHandler.java JDBCIDHandler.java JDBCLogger.java Log4JTest.java code_example1.java code_example2.java configfile_example.txt Volker Mentzner/ =============== HTTPRequestHandler.java Log4jRequestHandler.java PluggableHTTPServer.java RootRequestHandler.java UserDialogRequestHandler.java Allows users to configure log4j at runtime using a web-browser.apache-log4j1.2-1.2.17.orig/contribs/ThomasFenner/0000755000175000017500000000000012126647422020206 5ustar tonytonyapache-log4j1.2-1.2.17.orig/contribs/ThomasFenner/code_example2.java0000644000175000017500000001070611751454677023577 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Here is a code example to configure the JDBCAppender without a configuration-file import org.apache.log4j.*; import java.sql.*; import java.lang.*; import java.util.*; public class Log4JTest { // Create a category instance for this class static Category cat = Category.getInstance(Log4JTest.class.getName()); public static void main(String[] args) { // A JDBCIDHandler MyIDHandler idhandler = new MyIDHandler(); // Ensure to have all necessary drivers installed ! try { Driver d = (Driver)(Class.forName("oracle.jdbc.driver.OracleDriver").newInstance()); DriverManager.registerDriver(d); } catch(Exception e){} // Set the priority which messages have to be logged cat.setPriority(Priority.DEBUG); // Create a new instance of JDBCAppender JDBCAppender ja = new JDBCAppender(); // Set options with method setOption() ja.setOption(JDBCAppender.CONNECTOR_OPTION, "MyConnectionHandler"); ja.setOption(JDBCAppender.URL_OPTION, "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(COMMUNITY=tcp.world)(PROTOCOL=TCP)(Host=LENZI)(Port=1521))(ADDRESS=(COMMUNITY=tcp.world)(PROTOCOL=TCP)(Host=LENZI)(Port=1526)))(CONNECT_DATA=(SID=LENZI)))"); ja.setOption(JDBCAppender.USERNAME_OPTION, "mex_pr_dev60"); ja.setOption(JDBCAppender.PASSWORD_OPTION, "mex_pr_dev60"); ja.setOption(JDBCAppender.TABLE_OPTION, "logtest"); // There are two ways to setup the column-descriptions : // 1. Use the the method setOption(JDBCAppender.COLUMNS_OPTION, column-description) //ja.setOption(JDBCAppender.COLUMNS_OPTION, "id_seq~EMPTY id~ID~MyIDHandler msg~MSG created_on~TIMESTAMP created_by~STATIC~:-) Thomas Fenner (t.fenner@klopotek.de)"); // 2. Use the better way of coding with method setLogType(String columnname, int LogType.xxx, Object xxx) ja.setLogType("id_seq", LogType.EMPTY, ""); ja.setLogType("id", LogType.ID, idhandler); ja.setLogType("msg", LogType.MSG, ""); ja.setLogType("created_on", LogType.TIMESTAMP, ""); ja.setLogType("created_by", LogType.STATIC, "FEN"); // If you just want to perform a static sql-statement, forget about the table- and columns-options, // and use this one : //ja.setOption(JDBCAppender.SQL_OPTION, "INSERT INTO LOGTEST (id, msg, created_on, created_by) VALUES (1, @MSG@, sysdate, 'me')"); // other options //ja.setOption(JDBCAppender.BUFFER_OPTION, "1"); //ja.setOption(JDBCAppender.COMMIT_OPTION, "Y"); // Define a layout //ja.setLayout(new PatternLayout("%m")); // Add the appender to a category cat.addAppender(ja); // These messages with Priority >= setted priority will be logged to the database. cat.debug("debug"); cat.info("info"); cat.error("error"); cat.fatal("fatal"); } } // Implement a sample JDBCConnectionHandler class MyConnectionHandler implements JDBCConnectionHandler { Connection con = null; //Default connection String url = "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(COMMUNITY=tcp.world)(PROTOCOL=TCP)(Host=LENZI)(Port=1521))(ADDRESS=(COMMUNITY=tcp.world)(PROTOCOL=TCP)(Host=LENZI)(Port=1526)))(CONNECT_DATA=(SID=LENZI)))"; String username = "mex_pr_dev60"; String password = "mex_pr_dev60"; public Connection getConnection() { return getConnection(url, username, password); } public Connection getConnection(String _url, String _username, String _password) { try { if(con != null && !con.isClosed()) con.close(); con = DriverManager.getConnection(_url, _username, _password); con.setAutoCommit(false); } catch(Exception e){} return con; } } // Implement a sample JDBCIDHandler class MyIDHandler implements JDBCIDHandler { private static long id = 0; public synchronized Object getID() { return new Long(++id); } } apache-log4j1.2-1.2.17.orig/contribs/ThomasFenner/Log4JTest.java0000644000175000017500000002707711751454677022660 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** // Class JDBCAppender, writes messages into a database // The JDBCAppender is configurable at runtime in two alternatives : // 1. Configuration-file // Define the options in a file and call a PropertyConfigurator.configure(file)-method. // 2. method JDBCAppender::setOption(JDBCAppender.xxx_OPTION, String value) // The sequence of some options is important : // 1. Connector-option OR/AND Database-options // Any database connection is required ! // 2. (Table-option AND Columns-option) OR SQL-option // Any statement is required ! // 3. All other options can be set at any time... // The other options are optional and have a default initialization, which can be custumized. // All available options are defined as static String-constants in JDBCAppender named xxx_OPTION. // Here is a description of all available options : // 1. Database-options to connect to the database // - URL_OPTION : a database url of the form jdbc:subprotocol:subname // - USERNAME_OPTION : the database user on whose behalf the connection is being made // - PASSWORD_OPTION : the user's password // // 2. Connector-option to specify your own JDBCConnectionHandler // - CONNECTOR_OPTION : a classname which is implementing the JDBCConnectionHandler-interface // This interface is used to get a customized connection. // If in addition the database-options are given, these options will be used // for invocation of the JDBCConnectionHandler-interface to get a connection. // Else if no database-options are given, the JDBCConnectionHandler-interface is called without these options. // // 3. SQL-option to specify a static sql-statement which will be performed with every occuring message-event // - SQL_OPTION : a sql-statement which will be used to write to the database // If you give this option, the table-option and columns-option will be ignored ! // Use the variable @MSG@ on that location in the statement, which has to be dynamically replaced by the message. // // 4. Table-option to specify one table contained by the database // - TABLE_OPTION : the table in which the logging will be done // // 5. Columns-option to describe the important columns of the table (Not nullable columns are mandatory to describe!) // - COLUMNS_OPTION : a formatted list of column-descriptions // Each column description consists of // - the name of the column (required) // - a logtype which is a static constant of class LogType (required) // - and a value which depends by the LogType (optional/required, depending by logtype) // Here is a description of the available logtypes of class LogType : // o MSG = a value will be ignored, the column will get the message. (One columns need to be of this type!) // o STATIC = the value will be filled into the column with every logged message. (Ensure that the type of value can be casted into the sql-type of the column!) // o ID = value must be a classname, which implements the JDBCIDHandler-interface. // o TIMESTAMP = a value will be ignored, the column will be filled with a actually timestamp with every logged message. // o EMPTY = a value will be ignored, the column will be ignored when writing to the database (Ensure to fill not nullable columns by a database trigger!) // If there are more than one column to describe, the columns must be separated by a TAB-delimiter (' ') ! // The arguments of a column-description must be separated by the delimiter '~' ! // (Example : name1~logtype1~value1 name2~logtype2~value2...) // // 6. Layout-options to define the layout of the messages (optional) // - the layout wont be set by a xxx_OPTION // Configuration-file : see at the following configuration-file example // JDBCAppender::setOption() : see at the following code example // The default is a layout of class org.apache.log4j.PatternLayout with ConversionPattern=%m // // 7. Buffer-option to define the size of the message-event-buffer (optional) // - BUFFER_OPTION : define how many messages will be buffered until they will be updated to the database. // The default is a update on every message (buffer=1=no buffer). // // 8. Commit-option to define a auto-commitment // - COMMIT_OPTION : define whether updated messages should be committed to the database (Y) or not (N). // The default is a commit on every buffer-flush. // Here is a Configuration-file example, which can be used with the PropertyConfigurator : // // Declare a appender variable named JDBC log4j.rootCategory=JDBC // JDBC is a class of JDBCAppender, which writes messages into a database log4j.appender.JDBC=JDBCAppender // 1. Database-options to connect to the database log4j.appender.JDBC.url=jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(COMMUNITY=tcp.world)(PROTOCOL=TCP)(Host=LENZI)(Port=1521))(ADDRESS=(COMMUNITY=tcp.world)(PROTOCOL=TCP)(Host=LENZI)(Port=1526)))(CONNECT_DATA=(SID=LENZI))) log4j.appender.JDBC.username=mex_pr_dev60 log4j.appender.JDBC.password=mex_pr_dev60 // 2. Connector-option to specify your own JDBCConnectionHandler log4j.appender.JDBC.connector=MyConnectionHandler // 3. SQL-option to specify a static sql-statement which will be performed with every occuring message-event log4j.appender.JDBC.sql=INSERT INTO LOGTEST (id, msg, created_on, created_by) VALUES (1, @MSG@, sysdate, 'me') // 4. Table-option to specify one table contained by the database log4j.appender.JDBC.table=logtest // 5. Columns-option to describe the important columns of the table (Not nullable columns are mandatory to describe!) log4j.appender.JDBC.columns=id_seq~EMPTY id~ID~MyIDHandler msg~MSG created_on~TIMESTAMP created_by~STATIC~Thomas Fenner (t.fenner@klopotek.de) // 6. Layout-options to define the layout of the messages (optional) log4j.appender.JDBC.layout=org.apache.log4j.PatternLayout log4j.appender.JDBC.layout.ConversionPattern=%m // 7. Buffer-option to define the size of the message-event-buffer (optional) log4j.appender.JDBC.buffer=1 // 8. Commit-option to define a auto-commitment log4j.appender.JDBC.commit=Y */ // Here is a code example to configure the JDBCAppender with a configuration-file : import org.apache.log4j.*; import java.sql.*; import java.lang.*; import java.util.*; public class Log4JTest { // Create a category instance for this class static Category cat = Category.getInstance(Log4JTest.class.getName()); public static void main(String[] args) { // Ensure to have all necessary drivers installed ! try { Driver d = (Driver)(Class.forName("oracle.jdbc.driver.OracleDriver").newInstance()); DriverManager.registerDriver(d); } catch(Exception e){} // Set the priority which messages have to be logged cat.setPriority(Priority.INFO); // Configuration with configuration-file PropertyConfigurator.configure("log4jtestprops.txt"); // These messages with Priority >= setted priority will be logged to the database. cat.debug("debug"); //this not, because Priority DEBUG is less than INFO cat.info("info"); cat.error("error"); cat.fatal("fatal"); } } // Here is a code example to configure the JDBCAppender without a configuration-file : /* import org.apache.log4j.*; import java.sql.*; import java.lang.*; import java.util.*; public class Log4JTest { // Create a category instance for this class static Category cat = Category.getInstance(Log4JTest.class.getName()); public static void main(String[] args) { // A JDBCIDHandler MyIDHandler idhandler = new MyIDHandler(); // Ensure to have all necessary drivers installed ! try { Driver d = (Driver)(Class.forName("oracle.jdbc.driver.OracleDriver").newInstance()); DriverManager.registerDriver(d); } catch(Exception e){} // Set the priority which messages have to be logged cat.setPriority(Priority.DEBUG); // Create a new instance of JDBCAppender JDBCAppender ja = new JDBCAppender(); // Set options with method setOption() ja.setOption(JDBCAppender.CONNECTOR_OPTION, "MyConnectionHandler"); ja.setOption(JDBCAppender.URL_OPTION, "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(COMMUNITY=tcp.world)(PROTOCOL=TCP)(Host=LENZI)(Port=1521))(ADDRESS=(COMMUNITY=tcp.world)(PROTOCOL=TCP)(Host=LENZI)(Port=1526)))(CONNECT_DATA=(SID=LENZI)))"); ja.setOption(JDBCAppender.USERNAME_OPTION, "mex_pr_dev60"); ja.setOption(JDBCAppender.PASSWORD_OPTION, "mex_pr_dev60"); ja.setOption(JDBCAppender.TABLE_OPTION, "logtest"); // There are two ways to setup the column-descriptions : // 1. Use the the method setOption(JDBCAppender.COLUMNS_OPTION, column-description) //ja.setOption(JDBCAppender.COLUMNS_OPTION, "id_seq~EMPTY id~ID~MyIDHandler msg~MSG created_on~TIMESTAMP created_by~STATIC~:-) Thomas Fenner (t.fenner@klopotek.de)"); // 2. Use the better way of coding with method setLogType(String columnname, int LogType.xxx, Object xxx) ja.setLogType("id_seq", LogType.EMPTY, ""); ja.setLogType("id", LogType.ID, idhandler); ja.setLogType("msg", LogType.MSG, ""); ja.setLogType("created_on", LogType.TIMESTAMP, ""); ja.setLogType("created_by", LogType.STATIC, "FEN"); // If you just want to perform a static sql-statement, forget about the table- and columns-options, // and use this one : //ja.setOption(JDBCAppender.SQL_OPTION, "INSERT INTO LOGTEST (id, msg, created_on, created_by) VALUES (1, @MSG@, sysdate, 'me')"); // other options //ja.setOption(JDBCAppender.BUFFER_OPTION, "1"); //ja.setOption(JDBCAppender.COMMIT_OPTION, "Y"); // Define a layout //ja.setLayout(new PatternLayout("%m")); // Add the appender to a category cat.addAppender(ja); // These messages with Priority >= setted priority will be logged to the database. cat.debug("debug"); cat.info("info"); cat.error("error"); cat.fatal("fatal"); } } */ // Implement a sample JDBCConnectionHandler class MyConnectionHandler implements JDBCConnectionHandler { Connection con = null; //Default connection String url = "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(COMMUNITY=tcp.world)(PROTOCOL=TCP)(Host=LENZI)(Port=1521))(ADDRESS=(COMMUNITY=tcp.world)(PROTOCOL=TCP)(Host=LENZI)(Port=1526)))(CONNECT_DATA=(SID=LENZI)))"; String username = "mex_pr_dev60"; String password = "mex_pr_dev60"; public Connection getConnection() { return getConnection(url, username, password); } public Connection getConnection(String _url, String _username, String _password) { try { if(con != null && !con.isClosed()) con.close(); con = DriverManager.getConnection(_url, _username, _password); con.setAutoCommit(false); } catch(Exception e){} return con; } } // Implement a sample JDBCIDHandler class MyIDHandler implements JDBCIDHandler { private static long id = 0; public synchronized Object getID() { return new Long(++id); } } apache-log4j1.2-1.2.17.orig/contribs/ThomasFenner/configfile_example.txt0000644000175000017500000000467111751454677024612 0ustar tonytony# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Here is a Configuration-file example, which can be used with the PropertyConfigurator : # Declare a appender variable named JDBC log4j.rootCategory=JDBC # JDBC is a class of JDBCAppender, which writes messages into a database log4j.appender.JDBC=JDBCAppender # 1. Database-options to connect to the database log4j.appender.JDBC.url=jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(COMMUNITY=tcp.world)(PROTOCOL=TCP)(Host=LENZI)(Port=1521))(ADDRESS=(COMMUNITY=tcp.world)(PROTOCOL=TCP)(Host=LENZI)(Port=1526)))(CONNECT_DATA=(SID=LENZI))) log4j.appender.JDBC.username=mex_pr_dev60 log4j.appender.JDBC.password=mex_pr_dev60 # 2. Connector-option to specify your own JDBCConnectionHandler #log4j.appender.JDBC.connector=MyConnectionHandler # 3. SQL-option to specify a static sql-statement which will be performed with every occuring message-event #log4j.appender.JDBC.sql=INSERT INTO LOGTEST (id, msg, created_on, created_by) VALUES (1, @MSG@, sysdate, 'me') # 4. Table-option to specify one table contained by the database log4j.appender.JDBC.table=logtest # 5. Columns-option to describe the important columns of the table (Not nullable columns are mandatory to describe!) log4j.appender.JDBC.columns=id_seq~EMPTY id~ID~MyIDHandler msg~MSG created_on~TIMESTAMP created_by~STATIC~Thomas Fenner (t.fenner@klopotek.de) # 6. Layout-options to define the layout of the messages (optional) #log4j.appender.JDBC.layout=org.apache.log4j.PatternLayout #log4j.appender.JDBC.layout.ConversionPattern=%m # 7. Buffer-option to define the size of the message-event-buffer (optional) #log4j.appender.JDBC.buffer=1 # 8. Commit-option to define a auto-commitment (optional) #log4j.appender.JDBC.commit=Y apache-log4j1.2-1.2.17.orig/contribs/ThomasFenner/code_example1.java0000644000175000017500000000352611751454677023600 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Here is a code example to configure the JDBCAppender with a configuration-file import org.apache.log4j.*; import java.sql.*; import java.lang.*; import java.util.*; public class Log4JTest { // Create a category instance for this class static Category cat = Category.getInstance(Log4JTest.class.getName()); public static void main(String[] args) { // Ensure to have all necessary drivers installed ! try { Driver d = (Driver)(Class.forName("oracle.jdbc.driver.OracleDriver").newInstance()); DriverManager.registerDriver(d); } catch(Exception e){} // Set the priority which messages have to be logged cat.setPriority(Priority.INFO); // Configuration with configuration-file PropertyConfigurator.configure("log4jtestprops.txt"); // These messages with Priority >= setted priority will be logged to the database. cat.debug("debug"); //this not, because Priority DEBUG is less than INFO cat.info("info"); cat.error("error"); cat.fatal("fatal"); } } apache-log4j1.2-1.2.17.orig/contribs/ThomasFenner/JDBCConnectionHandler.java0000644000175000017500000000237611751454677025114 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.klopotek.utils.log; import java.sql.*; /** This interface has to be implemented for your own database-connection-handling and its used in class JDBCLogger.

Author : Thomas Fenner

@since 1.0 */ public interface JDBCConnectionHandler { /**Get a connection*/ Connection getConnection(); /**Get a defined connection*/ Connection getConnection(String _url, String _username, String _password); } apache-log4j1.2-1.2.17.orig/contribs/ThomasFenner/JDBCAppender.java0000644000175000017500000004332711751454677023256 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.klopotek.utils.log; import java.sql.*; import java.util.*; import org.apache.log4j.*; import org.apache.log4j.helpers.*; import org.apache.log4j.spi.*; /** The JDBCAppender, writes messages into a database

The JDBCAppender is configurable at runtime by setting options in two alternatives :

1. Use a configuration-file

Define the options in a file (example) and call a PropertyConfigurator.configure(filename) in your code.

2. Use the methods of JDBCAppender to do it

Call JDBCAppender::setOption(JDBCAppender.xxx_OPTION, String value) to do it analogically without a configuration-file (example)

All available options are defined as static String-constants in JDBCAppender named xxx_OPTION.

Here is a description of all available options :

1. Database-options to connect to the database

- URL_OPTION : a database url of the form jdbc:subprotocol:subname

- USERNAME_OPTION : the database user on whose behalf the connection is being made

- PASSWORD_OPTION : the user's password

2. Connector-option to specify your own JDBCConnectionHandler

- CONNECTOR_OPTION : a classname which is implementing the JDBCConnectionHandler-interface

This interface is used to get a customized connection.

If in addition the database-options are given, these options will be used as arguments for the JDBCConnectionHandler-interface to get a connection.

Else if no database-options are given, the JDBCConnectionHandler-interface is called without them.

Else if this option is not defined, the database-options are required to open a connection by the JDBCAppender.

3. SQL-option to specify a static sql-statement which will be performed with every occuring message-event

- SQL_OPTION : a sql-statement which will be used to write to the database

Use the variable @MSG@ on a location in the statement, which has to be dynamically replaced by the message-text.

If you give this option, the table-option and columns-option will be ignored !

4. Table-option to specify a table contained by the database

- TABLE_OPTION : the table in which the logging will be done

5. Columns-option to describe the important columns of the table (Not nullable columns are mandatory to describe!)

- COLUMNS_OPTION : a formatted list of column-descriptions

Each column description consists of

- the name of the column (required)

- a logtype which is a static constant of class LogType (required)

- and a value which depends by the LogType (optional/required, depending by logtype)

Here is a description of the available logtypes of class {@link LogType} and how to handle the value:

o MSG = a value will be ignored, the column will get the message. (One columns need to be of this type!)

o STATIC = the value will be filled into the column with every logged message. (Ensure that the type of value can be casted into the sql-type of the column!)

o ID = value must be a classname, which implements the JDBCIDHandler-interface.

o TIMESTAMP = a value will be ignored, the column will be filled with a actually timestamp with every logged message.

o EMPTY = a value will be ignored, the column will be ignored when writing to the database (Ensure to fill not nullable columns by a database trigger!)

If there are more than one column to describe, the columns must be separated by a Tabulator-delimiter (unicode0008) !

The arguments of a column-description must be separated by the delimiter '~' !

(Example : name1~logtype1~value1 name2~logtype2~value2...)

6. Layout-options to define the layout of the messages (optional)

- _ : the layout wont be set by a xxx_OPTION

See the configuration-file and code examples below...

The default is a layout of the class {@link org.apache.log4j.PatternLayout} with the pattern=%m which representate only the message.

7. Buffer-option to define the size of the message-event-buffer (optional)

- BUFFER_OPTION : define how many messages will be buffered until they will be updated to the database.

The default is buffer=1, which will do a update with every happened message-event.

8. Commit-option to define a auto-commitment

- COMMIT_OPTION : define whether updated messages should be committed to the database (Y) or not (N).

The default is commit=Y.

The sequence of some options is important :

1. Connector-option OR/AND Database-options

Any database connection is required !

2. (Table-option AND Columns-option) OR SQL-option

Anything of that is required ! Whether where to write something OR what to write somewhere...;-)

3. All other options can be set at any time...

The other options are optional and have a default initialization, which can be customized.

Here is a configuration-file example, which can be used as argument for the PropertyConfigurator : configfile_example.txt

Here is a code-example to configure the JDBCAppender with a configuration-file : code_example1.java

Here is a another code-example to configure the JDBCAppender without a configuration-file : code_example2.java

Author : Thomas Fenner

@since 1.0 */ public class JDBCAppender extends AppenderSkeleton { /** A database-option to to set a database url of the form jdbc:subprotocol:subname. */ public static final String URL_OPTION = "url"; /** A database-option to set the database user on whose behalf the connection is being made. */ public static final String USERNAME_OPTION = "username"; /** A database-option to set the user's password. */ public static final String PASSWORD_OPTION = "password"; /** A table-option to specify a table contained by the database */ public static final String TABLE_OPTION = "table"; /** A connector-option to specify your own JDBCConnectionHandler */ public static final String CONNECTOR_OPTION = "connector"; /** A columns-option to describe the important columns of the table */ public static final String COLUMNS_OPTION = "columns"; /** A sql-option to specify a static sql-statement which will be performed with every occuring message-event */ public static final String SQL_OPTION = "sql"; /** A buffer-option to define the size of the message-event-buffer */ public static final String BUFFER_OPTION = "buffer"; /** A commit-option to define a auto-commitment */ public static final String COMMIT_OPTION = "commit"; //Variables to store the options values setted by setOption() : private String url = null; private String username = null; private String password = null; private String table = null; private String connection_class = null; private String sql = null; private boolean docommit = true; private int buffer_size = 1; private JDBCConnectionHandler connectionHandler = null; //This buffer stores message-events. //When the buffer_size is reached, the buffer will be flushed and the messages will updated to the database. private ArrayList buffer = new ArrayList(); //Database-connection private Connection con = null; //This class encapsulate the logic which is necessary to log into a table private JDBCLogger jlogger = new JDBCLogger(); //Flags : //A flag to indicate a established database connection private boolean connected = false; //A flag to indicate configuration status private boolean configured = false; //A flag to indicate that everything is ready to get append()-commands. private boolean ready = false; /** If program terminates close the database-connection and flush the buffer */ public void finalize() { close(); super.finalize(); } /** Internal method. Returns a array of strings containing the available options which can be set with method setOption() */ public String[] getOptionStrings() { // The sequence of options in this string is important, because setOption() is called this way ... return new String[]{CONNECTOR_OPTION, URL_OPTION, USERNAME_OPTION, PASSWORD_OPTION, SQL_OPTION, TABLE_OPTION, COLUMNS_OPTION, BUFFER_OPTION, COMMIT_OPTION}; } /** Sets all necessary options */ public void setOption(String _option, String _value) { _option = _option.trim(); _value = _value.trim(); if(_option == null || _value == null) return; if(_option.length() == 0 || _value.length() == 0) return; _value = _value.trim(); if(_option.equals(CONNECTOR_OPTION)) { if(!connected) connection_class = _value; } else if(_option.equals(URL_OPTION)) { if(!connected) url = _value; } else if(_option.equals(USERNAME_OPTION)) { if(!connected) username = _value; } else if(_option.equals(PASSWORD_OPTION)) { if(!connected) password = _value; } else if(_option.equals(SQL_OPTION)) { sql = _value; } else if(_option.equals(TABLE_OPTION)) { if(sql != null) return; table = _value; } else if(_option.equals(COLUMNS_OPTION)) { if(sql != null) return; String name = null; int logtype = -1; String value = null; String column = null; String arg = null; int num_args = 0; int num_columns = 0; StringTokenizer st_col; StringTokenizer st_arg; //Columns are TAB-separated st_col = new StringTokenizer(_value, " "); num_columns = st_col.countTokens(); if(num_columns < 1) { errorHandler.error("JDBCAppender::setOption(), Invalid COLUMN_OPTION value : " + _value + " !"); return; } for(int i=1; i<=num_columns; i++) { column = st_col.nextToken(); //Arguments are ~-separated st_arg = new StringTokenizer(column, "~"); num_args = st_arg.countTokens(); if(num_args < 2) { errorHandler.error("JDBCAppender::setOption(), Invalid COLUMN_OPTION value : " + _value + " !"); return; } for(int j=1; j<=num_args; j++) { arg = st_arg.nextToken(); if(j == 1) name = arg; else if(j == 2) { try { logtype = Integer.parseInt(arg); } catch(Exception e) { logtype = LogType.parseLogType(arg); } if(!LogType.isLogType(logtype)) { errorHandler.error("JDBCAppender::setOption(), Invalid COLUMN_OPTION LogType : " + arg + " !"); return; } } else if(j == 3) value = arg; } if(!setLogType(name, logtype, value)) return; } } else if(_option.equals(BUFFER_OPTION)) { try { buffer_size = Integer.parseInt(_value); } catch(Exception e) { errorHandler.error("JDBCAppender::setOption(), Invalid BUFFER_OPTION value : " + _value + " !"); return; } } else if(_option.equals(COMMIT_OPTION)) { docommit = _value.equals("Y"); } if(_option.equals(SQL_OPTION) || _option.equals(TABLE_OPTION)) { if(!configured) configure(); } } /** Internal method. Returns true, you may define your own layout... */ public boolean requiresLayout() { return true; } /** Internal method. Close the database connection & flush the buffer. */ public void close() { flush_buffer(); if(connection_class == null) { try{con.close();}catch(Exception e){errorHandler.error("JDBCAppender::close(), " + e);} } this.closed = true; } /** You have to call this function for all provided columns of your log-table ! */ public boolean setLogType(String _name, int _logtype, Object _value) { if(sql != null) return true; if(!configured) { if(!configure()) return false; } try { jlogger.setLogType(_name, _logtype, _value); } catch(Exception e) { errorHandler.error("JDBCAppender::setLogType(), " + e); return false; } return true; } /** Internal method. Appends the message to the database table. */ public void append(LoggingEvent event) { if(!ready) { if(!ready()) { errorHandler.error("JDBCAppender::append(), Not ready to append !"); return; } } buffer.add(event); if(buffer.size() >= buffer_size) flush_buffer(); } /** Internal method. Flushes the buffer. */ public void flush_buffer() { try { int size = buffer.size(); if(size < 1) return; for(int i=0; iAuthor : Thomas Fenner

@since 1.0 */ public class JDBCLogger { //All columns of the log-table private ArrayList logcols = null; //Only columns which will be provided by logging private String column_list = null; //Number of all columns private int num = 0; //Status for successful execution of method configure() private boolean isconfigured = false; //Status for ready to do logging with method append() private boolean ready = false; //This message will be filled with a error-string when method ready() failes, and can be got by calling getMsg() private String errormsg = ""; private Connection con = null; private Statement stmt = null; private ResultSet rs = null; private String table = null; //Variables for static SQL-statement logging private String sql = null; private String new_sql = null; private String new_sql_part1 = null; private String new_sql_part2 = null; private static final String msg_wildcard = "@MSG@"; private int msg_wildcard_pos = 0; /** Writes a message into the database table. Throws an exception, if an database-error occurs ! */ public void append(String _msg) throws Exception { if(!ready) if(!ready()) throw new Exception("JDBCLogger::append(), Not ready to append !"); if(sql != null) { appendSQL(_msg); return; } LogColumn logcol; rs.moveToInsertRow(); for(int i=0; i 0) { new_sql = new_sql_part1 + _msg + new_sql_part2; } else new_sql = sql; try { stmt.executeUpdate(new_sql); } catch(Exception e) { errormsg = new_sql; throw e; } } /** Configures this class, by reading in the structure of the log-table Throws an exception, if an database-error occurs ! */ public void configureTable(String _table) throws Exception { if(isconfigured) return; //Fill logcols with META-informations of the table-columns stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); rs = stmt.executeQuery("SELECT * FROM " + _table + " WHERE 1 = 2"); LogColumn logcol; ResultSetMetaData rsmd = rs.getMetaData(); num = rsmd.getColumnCount(); logcols = new ArrayList(num); for(int i=1; i<=num; i++) { logcol = new LogColumn(); logcol.name = rsmd.getColumnName(i).toUpperCase(); logcol.type = rsmd.getColumnTypeName(i); logcol.nullable = (rsmd.isNullable(i) == rsmd.columnNullable); logcol.isWritable = rsmd.isWritable(i); if(!logcol.isWritable) logcol.ignore = true; logcols.add(logcol); } table = _table; isconfigured = true; } /** Configures this class, by storing and parsing the given sql-statement. Throws an exception, if somethings wrong ! */ public void configureSQL(String _sql) throws Exception { if(isconfigured) return; if(!isConnected()) throw new Exception("JDBCLogger::configureSQL(), Not connected to database !"); if(_sql == null || _sql.trim().equals("")) throw new Exception("JDBCLogger::configureSQL(), Invalid SQL-Statement !"); sql = _sql.trim(); stmt = con.createStatement(); msg_wildcard_pos = sql.indexOf(msg_wildcard); if(msg_wildcard_pos > 0) { new_sql_part1 = sql.substring(0, msg_wildcard_pos-1) + "'"; //between the message... new_sql_part2 = "'" + sql.substring(msg_wildcard_pos+msg_wildcard.length()); } isconfigured = true; } /** Sets a connection. Throws an exception, if the connection is not open ! */ public void setConnection(Connection _con) throws Exception { con = _con; if(!isConnected()) throw new Exception("JDBCLogger::setConnection(), Given connection isnt connected to database !"); } /** Sets a columns logtype (LogTypes) and value, which depends on that logtype. Throws an exception, if the given arguments arent correct ! */ public void setLogType(String _name, int _logtype, Object _value) throws Exception { if(!isconfigured) throw new Exception("JDBCLogger::setLogType(), Not configured !"); //setLogType() makes only sense for further configuration of configureTable() if(sql != null) return; _name = _name.toUpperCase(); if(_name == null || !(_name.trim().length() > 0)) throw new Exception("JDBCLogger::setLogType(), Missing argument name !"); if(!LogType.isLogType(_logtype)) throw new Exception("JDBCLogger::setLogType(), Invalid logtype '" + _logtype + "' !"); if((_logtype != LogType.MSG && _logtype != LogType.EMPTY) && _value == null) throw new Exception("JDBCLogger::setLogType(), Missing argument value !"); LogColumn logcol; for(int i=0; iAuthor : Thomas Fenner

@since 1.0 */ public interface JDBCIDHandler { /**Get a unique ID*/ Object getID(); } apache-log4j1.2-1.2.17.orig/contribs/SvenReimers/0000755000175000017500000000000011751454673020066 5ustar tonytonyapache-log4j1.2-1.2.17.orig/contribs/SvenReimers/gui/0000755000175000017500000000000012126647422020643 5ustar tonytonyapache-log4j1.2-1.2.17.orig/contribs/SvenReimers/gui/examples/0000755000175000017500000000000012126647422022461 5ustar tonytonyapache-log4j1.2-1.2.17.orig/contribs/SvenReimers/gui/examples/TextPaneAppenderExample.java0000644000175000017500000000624111751454673030061 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.gui.examples; import java.awt.BorderLayout; import java.awt.event.*; import javax.swing.*; import org.apache.log4j.*; import org.apache.log4j.gui.*; public class TextPaneAppenderExample implements ActionListener { JFrame mainframe; ButtonGroup priorities; TextPaneAppender tpa; Category gui; Priority prio[]; JTabbedPane logview; public TextPaneAppenderExample () { mainframe = new JFrame("Testing the TextPaneAppender..."); mainframe.setSize(300,300); logview = new JTabbedPane(); createLogger(); createMenuBar(); mainframe.setVisible(true); mainframe.getContentPane().add(logview); } public void createLogger() { tpa = new TextPaneAppender(new PatternLayout("%-5p %d [%t]: %m%n"),"Debug"); logview.addTab("Events ...",new JScrollPane(tpa.getTextPane())); gui = Category.getInstance(this.getClass().getName()); gui.addAppender(tpa); } public void createMenuBar() { JMenu file = new JMenu("File"); JMenuItem exit = new JMenuItem("Exit"); exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { System.exit(0); } }); file.add(exit); JMenuBar mb = new JMenuBar(); mb.add(file); JMenu logevent = new JMenu("LoggingEvents"); JMenu selectprio = new JMenu("Priority"); prio = Priority.getAllPossiblePriorities(); JRadioButtonMenuItem priority[]= new JRadioButtonMenuItem[prio.length]; priorities = new ButtonGroup(); for (int i=0; iExperimental
TextPaneAppender.
* * * Created: Sat Feb 26 18:50:27 2000
* * @author Sven Reimers */ public class TextPaneAppender extends AppenderSkeleton { JTextPane textpane; StyledDocument doc; TracerPrintWriter tp; StringWriter sw; QuietWriter qw; Hashtable attributes; Hashtable icons; private String label; private boolean fancy; final String LABEL_OPTION = "Label"; final String COLOR_OPTION_FATAL = "Color.Emerg"; final String COLOR_OPTION_ERROR = "Color.Error"; final String COLOR_OPTION_WARN = "Color.Warn"; final String COLOR_OPTION_INFO = "Color.Info"; final String COLOR_OPTION_DEBUG = "Color.Debug"; final String COLOR_OPTION_BACKGROUND = "Color.Background"; final String FANCY_OPTION = "Fancy"; final String FONT_NAME_OPTION = "Font.Name"; final String FONT_SIZE_OPTION = "Font.Size"; public static Image loadIcon ( String path ) { Image img = null; try { URL url = ClassLoader.getSystemResource(path); img = (Image) (Toolkit.getDefaultToolkit()).getImage(url); } catch (Exception e) { System.out.println("Exception occured: " + e.getMessage() + " - " + e ); } return (img); } public TextPaneAppender(Layout layout, String name) { this(); this.layout = layout; this.name = name; setTextPane(new JTextPane()); createAttributes(); createIcons(); } public TextPaneAppender() { super(); setTextPane(new JTextPane()); createAttributes(); createIcons(); this.label=""; this.sw = new StringWriter(); this.qw = new QuietWriter(sw, errorHandler); this.tp = new TracerPrintWriter(qw); this.fancy =true; } public void close() { } private void createAttributes() { Priority prio[] = Priority.getAllPossiblePriorities(); attributes = new Hashtable(); for (int i=0; i= 255 ? res : res + ","+c.getAlpha(); } public void setLayout(Layout layout) { this.layout=layout; } public void setName(String name) { this.name = name; } public void setTextPane(JTextPane textpane) { this.textpane=textpane; textpane.setEditable(false); textpane.setBackground(Color.lightGray); this.doc=textpane.getStyledDocument(); } private void setColor(Priority p, String v) { StyleConstants.setForeground( (MutableAttributeSet)attributes.get(p),parseColor(v)); } private String getColor(Priority p) { Color c = StyleConstants.getForeground( (MutableAttributeSet)attributes.get(p)); return c == null ? null : colorToString(c); } ///////////////////////////////////////////////////////////////////// // option setters and getters public void setLabel(String label) { this.label = label; } public String getLabel() { return label; } public void setColorEmerg(String color) { setColor(Priority.FATAL, color); } public String getColorEmerg() { return getColor(Priority.FATAL); } public void setColorError(String color) { setColor(Priority.ERROR, color); } public String getColorError() { return getColor(Priority.ERROR); } public void setColorWarn(String color) { setColor(Priority.WARN, color); } public String getColorWarn() { return getColor(Priority.WARN); } public void setColorInfo(String color) { setColor(Priority.INFO, color); } public String getColorInfo() { return getColor(Priority.INFO); } public void setColorDebug(String color) { setColor(Priority.DEBUG, color); } public String getColorDebug() { return getColor(Priority.DEBUG); } public void setColorBackground(String color) { textpane.setBackground(parseColor(color)); } public String getColorBackground() { return colorToString(textpane.getBackground()); } public void setFancy(boolean fancy) { this.fancy = fancy; } public boolean getFancy() { return fancy; } public void setFontSize(int size) { Enumeration e = attributes.elements(); while (e.hasMoreElements()) { StyleConstants.setFontSize((MutableAttributeSet)e.nextElement(),size); } return; } public int getFontSize() { AttributeSet attrSet = (AttributeSet) attributes.get(Priority.INFO); return StyleConstants.getFontSize(attrSet); } public void setFontName(String name) { Enumeration e = attributes.elements(); while (e.hasMoreElements()) { StyleConstants.setFontFamily((MutableAttributeSet)e.nextElement(),name); } return; } public String getFontName() { AttributeSet attrSet = (AttributeSet) attributes.get(Priority.INFO); return StyleConstants.getFontFamily(attrSet); } public boolean requiresLayout() { return true; } } // TextPaneAppender apache-log4j1.2-1.2.17.orig/contribs/SvenReimers/gui/JTableAppender.java0000644000175000017500000001333411751454673024341 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.gui; import org.apache.log4j.helpers.CyclicBuffer; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.Priority; import org.apache.log4j.Category; import org.apache.log4j.Layout; import org.apache.log4j.PatternLayout; import org.apache.log4j.spi.LoggingEvent; import javax.swing.JList; import javax.swing.AbstractListModel; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import java.awt.Component; import java.awt.FlowLayout; import javax.swing.BoxLayout; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Container; import javax.swing.ImageIcon; import java.awt.Image; import java.awt.Toolkit; import java.net.URL; import java.awt.Rectangle; public class JTableAppender extends JTable { static Category cat = Category.getInstance(JTableAppender.class.getName()); PatternLayout layout; public JTableAppender() { layout = new PatternLayout("%r %p %c [%t] - %m"); this.setDefaultRenderer(Object.class, new Renderer()); } public void add(LoggingEvent event) { ((JTableAppenderModel)getModel()).add(event); } public Dimension getPreferredSize() { System.out.println("getPreferredSize() called"); return super.getPreferredSize(); } static public void main(String[] args) { JFrame frame = new JFrame("JListView test"); Container container = frame.getContentPane(); JTableAppender appender = new JTableAppender(); JTableAppenderModel model = new JTableAppenderModel(Integer.parseInt(args[0])); appender.setModel(model); //appender.createDefaultColumnsFromModel(); JScrollPane sp = new JScrollPane(appender); sp.setPreferredSize(new Dimension(250, 80)); container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS)); //container.add(view); container.add(sp); JButton button = new JButton("ADD"); container.add(button); button.addActionListener(new JTableAddAction(appender)); frame.setVisible(true); frame.setSize(new Dimension(700,700)); long before = System.currentTimeMillis(); int RUN = 10000; int i = 0; while(i++ < RUN) { LoggingEvent event = new LoggingEvent("x", cat, Priority.ERROR, "Message "+i, null); event.getThreadName(); if(i % 10 == 0) { //event.throwable = new Exception("hello "+i); } appender.add(event); } long after = System.currentTimeMillis(); System.out.println("Time taken :"+ ((after-before)*1000/RUN)); } class Renderer extends JTextArea implements TableCellRenderer { Object o = new Object(); int i = 0; public Renderer() { System.out.println("Render() called ----------------------"); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { System.out.println(o + " ============== " + i++); //LogLog.error("=======", new Exception()); //setIcon(longIcon); if(value instanceof LoggingEvent) { LoggingEvent event = (LoggingEvent) value; String str = layout.format(event); String t = event.getThrowableInformation(); if(t != null) { System.out.println("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"); setText(str + Layout.LINE_SEP + t); } else { setText(str); } } else { setText(value.toString()); } return this; } } } class JTableAppenderModel extends AbstractTableModel { CyclicBuffer cb; JTableAppenderModel(int size) { cb = new CyclicBuffer(size); } public void add(LoggingEvent event) { //System.out.println("JListViewModel.add called"); cb.add(event); int j = cb.length(); fireTableDataChanged(); } public int getColumnCount() { return 1; } public int getRowCount() { return cb.length(); } //public //Class getColumnClass(int index) { // System.out.println("getColumnClass called " + index); // return LoggingEvent.class; //} public Object getValueAt(int row, int col) { return cb.get(row); } } class JTableAddAction implements ActionListener { int j; JTableAppender appender; Category cat = Category.getInstance("x"); public JTableAddAction(JTableAppender appender) { this.appender = appender; j = 0; } public void actionPerformed(ActionEvent e) { System.out.println("Action occured"); LoggingEvent event = new LoggingEvent("x", cat, Priority.DEBUG, "Message "+j, null); if(j % 5 == 0) { //event.throwable = new Exception("hello "+j); } j++; appender.add(event); } } apache-log4j1.2-1.2.17.orig/contribs/SvenReimers/gui/JListView.java0000644000175000017500000002132511751454673023400 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.gui; import org.apache.log4j.helpers.CyclicBuffer; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.Priority; import org.apache.log4j.Category; import org.apache.log4j.Layout; import org.apache.log4j.PatternLayout; import org.apache.log4j.spi.LoggingEvent; import javax.swing.JList; import javax.swing.AbstractListModel; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import java.awt.Component; import java.awt.FlowLayout; import java.awt.GridLayout; import javax.swing.BoxLayout; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Container; import javax.swing.ImageIcon; import java.awt.Image; import java.awt.Toolkit; import java.net.URL; import java.awt.Rectangle; public class JListView extends JList { static Category cat = Category.getInstance(JListView.class.getName()); //JListViewModel model; PatternLayout layout; static LoggingEvent proto = new LoggingEvent("x", cat, Priority.ERROR, "Message ", new Throwable()); public JListView(JListViewModel model) { super(model); layout = new PatternLayout("%r %p %c [%t] - %m"); //this.setModel(model); this.setCellRenderer(new MyCellRenderer()); // setFixedCellWidth(10); //setFixedCellHeight(20); } public void add(LoggingEvent event) { ((JListViewModel)getModel()).add(event); } /* public Dimension getPreferredSize() { System.out.println("getPreferredSize() called"); return super.getPreferredSize(); } public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { System.out.println("getScrollableUnitIncrement called with " + visibleRect + "orientation: "+orientation+", direction: "+direction); return super.getScrollableUnitIncrement(visibleRect, orientation, direction); } public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { System.out.println("getScrollableBlockIncrement called with " + visibleRect + "orientation: "+orientation+ ", direction: "+direction); return super.getScrollableBlockIncrement(visibleRect, orientation, direction); } */ //public //boolean getScrollableTracksViewportWidth() { //System.out.println("getScrollableTracksViewportWidth called."); //return true; //boolean b = super.getScrollableTracksViewportWidth(); //System.out.println("result is: "+b); //return b; //} //public //boolean getScrollableTracksViewportHeight() { // System.out.println("getScrollableTracksViewportHeight called."); // return true; //boolean b = super.getScrollableTracksViewportHeight(); //System.out.println("result is: "+b); //return b; //} //public //int getFirstVisibleIndex() { //int r = getFirstVisibleIndex(); // System.out.println("----------getFirstVisibleIndex called, result: "+r); //return r; //} //public //Object getPrototypeCellValue() { //return proto; //} static public void main(String[] args) { JFrame frame = new JFrame("JListView test"); Container container = frame.getContentPane(); JListView view = new JListView(new JListViewModel(Integer.parseInt(args[0]))); JScrollPane sp = new JScrollPane(view); sp.setPreferredSize(new Dimension(250, 80)); container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS)); //container.add(view); container.add(sp); JButton b1 = new JButton("Add 1"); JButton b10 = new JButton("Add 10"); JButton b100 = new JButton("Add 100"); JButton b1000 = new JButton("Add 1000"); JButton b10000 = new JButton("Add 10000"); JPanel panel = new JPanel(new GridLayout(0,1)); container.add(panel); panel.add(b1); panel.add(b10); panel.add(b100); panel.add(b1000); panel.add(b10000); AddAction a1 = new AddAction(view, 1); AddAction a10 = new AddAction(view, 10); AddAction a100 = new AddAction(view, 100); AddAction a1000 = new AddAction(view, 1000); AddAction a10000 = new AddAction(view, 10000); b1.addActionListener(a1); b10.addActionListener(a10); b100.addActionListener(a100); b1000.addActionListener(a1000); b10000.addActionListener(a10000); frame.setVisible(true); frame.setSize(new Dimension(700,700)); long before = System.currentTimeMillis(); int RUN = 1000; int i = 0; while(i++ < RUN) { LoggingEvent event0 = new LoggingEvent("x", cat, Priority.ERROR, "Message "+i, null); Throwable t = new Exception("hello "+i); LoggingEvent event1 = new LoggingEvent("x", cat, Priority.ERROR, "Message "+i, t); if(i % 10 == 0) { event1.getThreadName(); view.add(event1); } else { event0.getThreadName(); view.add(event0); } } long after = System.currentTimeMillis(); System.out.println("Time taken :"+ ((after-before)*1000/RUN)); } class MyCellRenderer extends JTextArea implements ListCellRenderer { Object o = new Object(); int i = 0; final ImageIcon longIcon = new ImageIcon("RedFlag.gif"); public MyCellRenderer() { System.out.println("----------------------"); } public int getTabSize() { return 2; } public Image loadIcon ( String path ) { Image img = null; try { URL url = ClassLoader.getSystemResource(path); img = (Image) (Toolkit.getDefaultToolkit()).getImage(url); } catch (Exception e) { System.out.println("Exception occured: " + e.getMessage() + " - " + e ); } return (img); } public Component getListCellRendererComponent(JList list, Object value, int index, // cell index boolean isSelected, boolean cellHasFocus) { // System.out.println(o + " ============== " + i++); //LogLog.error("=======", new Exception()); //setIcon(longIcon); if(value instanceof LoggingEvent) { LoggingEvent event = (LoggingEvent) value; String str = layout.format(event); String t = event.getThrowableInformation(); if(t != null) { setText(str + Layout.LINE_SEP + t); } else { setText(str); } } else { setText(value.toString()); } return this; } } } class JListViewModel extends AbstractListModel { CyclicBuffer cb; JListViewModel(int size) { cb = new CyclicBuffer(size); } public void add(LoggingEvent event) { //System.out.println("JListViewModel.add called"); cb.add(event); int j = cb.length(); fireContentsChanged(this, 0, j); } public Object getElementAt(int index) { return cb.get(index); } public int getSize() { return cb.length(); } } class AddAction implements ActionListener { Thread t; static int counter = 0; public AddAction(JListView view, int burst) { this.t = new AddThread(view, burst); t.start(); } public void actionPerformed(ActionEvent e) { System.out.println("Action occured"); synchronized(t) { t.notify(); } } class AddThread extends Thread { int burst; JListView view; Category cat = Category.getInstance("x"); AddThread(JListView view, int burst) { super(); this.burst = burst; this.view = view; setName("AddThread"+burst); } public void run() { while(true) { synchronized(this) { try { this.wait(); } catch(Exception e) { } } for(int i = 0; i < burst; i++) { LoggingEvent event = new LoggingEvent("x", cat, Priority.DEBUG, "Message "+counter, null); event.getThreadName(); if(counter % 50 == 0) { //event.throwable = new Exception("hello "+counter); } counter++; view.add(event); } } } } } apache-log4j1.2-1.2.17.orig/contribs/LeosLiterak/0000755000175000017500000000000012126647422020033 5ustar tonytonyapache-log4j1.2-1.2.17.orig/contribs/LeosLiterak/mail0000644000175000017500000000272011751454703020702 0ustar tonytony Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. To: ceki@apache.org Subject: TempFileAppender Hi Ceki, I have created one small Appender, which puts each logging statement into separate file. We use it for storing incomming messages into second process'es spool directory. If you like it, please include it into Log4j with APL license. Usage: log4j.appender.A1=org.apache.log4j.TempFileAppender log4j.appender.A1.Path=spool_dir log4j.appender.A1.Prefix=out_ log4j.appender.A1.Suffix=.msg Leo ----------------------------------------------------- Leos Literak Software Engineer 12snap s.r.o. Pstrossova 24 110 00 Praha 1 Czech Republic mobile: ?605-849-087 phone: ?2-21-970-239 fax: ?2-21-970-241 e-mail: leos.literak@12snap.com apache-log4j1.2-1.2.17.orig/contribs/LeosLiterak/TempFileAppender.java0000644000175000017500000001305111751454703024063 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j; import java.io.File; import java.io.Writer; import java.io.FileWriter; import java.io.BufferedWriter; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.helpers.OptionConverter; import org.apache.log4j.spi.ErrorHandler; /** TempFileAppender creates new unique file for each logging statement. @author Leos Literak @author Ceki Gülcü */ public class TempFileAppender extends AppenderSkeleton { /** A string constant used in naming the option for setting the directory where the log files will be created. Current value of this string constant is Path. java.io.tmpdir directory will be used, if ommited. */ static final public String PATH_OPTION = "Path"; /** The default path is actual directory. */ protected String path = null; /** A string constant used in naming the option for setting the prefix of the log files. It has to have at least 3 characters! Current value of this string constant is Prefix. */ static final public String PREFIX_OPTION = "Prefix"; /** The default path is actual directory. */ protected String prefix = "l4j_"; /** A string constant used in naming the option for setting the suffix of the log files. Current value of this string constant is Suffix. */ static final public String SUFFIX_OPTION = "Suffix"; /** The default path is actual directory. */ protected String suffix = ".tmp"; /** Default dir */ protected File dir = null; /** The default constructor simply calls its parent's constructor. */ public TempFileAppender() { super(); } /** Retuns the option names for this component */ public String[] getOptionStrings() { return OptionConverter.concatanateArrays(super.getOptionStrings(), new String[] {PATH_OPTION,PREFIX_OPTION,SUFFIX_OPTION}); } /** Set TempFileAppender specific options. The recognized options are Path, Prefix and Suffix, i.e. the values of the string constants {@link #PATH_OPTION}, {@link #PREFIX_OPTION} and respectively {@link #SUFFIX_OPTION}. The options of the super class {@link AppenderSkeleton} are also recognized. */ public void setOption(String key, String value) { super.setOption(key, value); if(key.equalsIgnoreCase(PATH_OPTION)) { path = value; if(path==null) { errorHandler.error("Path cannot be empty!",null,0); } dir = new File(path); if(!(dir.exists() && dir.isDirectory() && dir.canWrite())) { errorHandler.error("Cannot write to directory " + path + "!",null,0); } } else if(key.equalsIgnoreCase(PREFIX_OPTION)) { if(value!=null && value.length()>=3) { prefix = value; } else { errorHandler.error("Prefix cannot be shorter than 3 characters!", null,0); } } else if(key.equalsIgnoreCase(SUFFIX_OPTION)) { if(value!=null && value.length()>=1) { suffix = value; } else { errorHandler.error("Suffix cannot be empty!",null,0); } } } /** This method is called by {@link AppenderSkeleton#doAppend} method.

Whenever this method is called, new unique file is created with specified prefix and suffix. The file is closed afterwards.

The format of the output will depend on this appender's layout. */ public void append(LoggingEvent event) { if(!checkEntryConditions()) { return; } subAppend(event); } /** This method determines if there is a sense in attempting to append. */ protected boolean checkEntryConditions() { return true; } /** This method does actual writing */ protected void subAppend(LoggingEvent event) { try { File tmp = File.createTempFile(prefix,suffix,dir); Writer out = new BufferedWriter(new FileWriter(tmp)); out.write(event.message); out.close(); /* this Appender is not supposed to be used for logging of Exceptions */ } catch (Exception e) { errorHandler.error("Error during creation of temporary File!",e,1); } } public boolean requiresLayout() { return false; } public void close() { /* nothing to do */ } } /* * @author $Author: carnold $ * @version $Revision: 511036 $ * @since $Date: 2007-02-23 18:48:53 +0100 (Fri, 23 Feb 2007) $ * * $Log$ * Revision 1.1.2.1 2005/05/27 03:27:54 mwomack * Fix for #35032. Added license header to .java files that did not already have a license. * * Revision 1.1 2001/04/20 17:38:31 ceki * * Added LeosLiterak's TempFileAppender.java * */ apache-log4j1.2-1.2.17.orig/contribs/Jamie Tsao/0000755000175000017500000000000012126647422017531 5ustar tonytonyapache-log4j1.2-1.2.17.orig/contribs/Jamie Tsao/JMSQueueAppender.java0000644000175000017500000001546611751454702023525 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 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 java.util.Hashtable; import java.util.Properties; import javax.jms.*; import javax.naming.InitialContext; import javax.naming.Context; import javax.naming.NameNotFoundException; import javax.naming.NamingException; /** * A Simple JMS (P2P) Queue Appender. * * @author Ceki Gülcü * @author Jamie Tsao */ public class JMSQueueAppender extends AppenderSkeleton { protected QueueConnection queueConnection; protected QueueSession queueSession; protected QueueSender queueSender; protected Queue queue; String initialContextFactory; String providerUrl; String queueBindingName; String queueConnectionFactoryBindingName; public JMSQueueAppender() { } /** * The InitialContextFactory option takes a string value. * Its value, along with the ProviderUrl option will be used * to get the InitialContext. */ public void setInitialContextFactory(String initialContextFactory) { this.initialContextFactory = initialContextFactory; } /** * Returns the value of the InitialContextFactory option. */ public String getInitialContextFactory() { return initialContextFactory; } /** * The ProviderUrl option takes a string value. * Its value, along with the InitialContextFactory option will be used * to get the InitialContext. */ public void setProviderUrl(String providerUrl) { this.providerUrl = providerUrl; } /** * Returns the value of the ProviderUrl option. */ public String getProviderUrl() { return providerUrl; } /** * The QueueConnectionFactoryBindingName option takes a * string value. Its value will be used to lookup the appropriate * QueueConnectionFactory from the JNDI context. */ public void setQueueConnectionFactoryBindingName(String queueConnectionFactoryBindingName) { this.queueConnectionFactoryBindingName = queueConnectionFactoryBindingName; } /** * Returns the value of the QueueConnectionFactoryBindingName option. */ public String getQueueConnectionFactoryBindingName() { return queueConnectionFactoryBindingName; } /** * The QueueBindingName option takes a * string value. Its value will be used to lookup the appropriate * destination Queue from the JNDI context. */ public void setQueueBindingName(String queueBindingName) { this.queueBindingName = queueBindingName; } /** Returns the value of the QueueBindingName option. */ public String getQueueBindingName() { return queueBindingName; } /** * Overriding this method to activate the options for this class * i.e. Looking up the Connection factory ... */ public void activateOptions() { QueueConnectionFactory queueConnectionFactory; try { Context ctx = getInitialContext(); queueConnectionFactory = (QueueConnectionFactory) ctx.lookup(queueConnectionFactoryBindingName); queueConnection = queueConnectionFactory.createQueueConnection(); queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = (Queue) ctx.lookup(queueBindingName); queueSender = queueSession.createSender(queue); queueConnection.start(); ctx.close(); } catch(Exception e) { errorHandler.error("Error while activating options for appender named ["+name+ "].", e, ErrorCode.GENERIC_FAILURE); } } protected InitialContext getInitialContext() throws NamingException { try { Hashtable ht = new Hashtable(); //Populate property hashtable with data to retrieve the context. ht.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory); ht.put(Context.PROVIDER_URL, providerUrl); return (new InitialContext(ht)); } catch (NamingException ne) { LogLog.error("Could not get initial context with ["+initialContextFactory + "] and [" + providerUrl + "]."); throw ne; } } protected boolean checkEntryConditions() { String fail = null; if(this.queueConnection == null) { fail = "No QueueConnection"; } else if(this.queueSession == null) { fail = "No QueueSession"; } else if(this.queueSender == null) { fail = "No QueueSender"; } if(fail != null) { errorHandler.error(fail +" for JMSQueueAppender named ["+name+"]."); return false; } else { return true; } } /** * Close this JMSQueueAppender. Closing releases all resources used by the * appender. A closed appender cannot be re-opened. */ public synchronized // avoid concurrent append and close operations void close() { if(this.closed) return; LogLog.debug("Closing appender ["+name+"]."); this.closed = true; try { if(queueSession != null) queueSession.close(); if(queueConnection != null) queueConnection.close(); } catch(Exception e) { LogLog.error("Error while closing JMSQueueAppender ["+name+"].", e); } // Help garbage collection queueSender = null; queueSession = null; queueConnection = null; } /** * This method called by {@link AppenderSkeleton#doAppend} method to * do most of the real appending work. The LoggingEvent will be * be wrapped in an ObjectMessage to be put on the JMS queue. */ public void append(LoggingEvent event) { if(!checkEntryConditions()) { return; } try { ObjectMessage msg = queueSession.createObjectMessage(); msg.setObject(event); queueSender.send(msg); } catch(Exception e) { errorHandler.error("Could not send message in JMSQueueAppender ["+name+"].", e, ErrorCode.GENERIC_FAILURE); } } public boolean requiresLayout() { return false; } }apache-log4j1.2-1.2.17.orig/contribs/Jamie Tsao/mail-2001-06-200000644000175000017500000000215211751454702021420 0ustar tonytony Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Hi, I have written a JMSQueueAppender that essentially logs to a JMS Queue (Point 2 Point). The JMSAppender currently packaged with log4j logs to a JMS Topic (I would rename it JMSTopicAppender). I also made it so that the InitialContextFactory and ProviderUrl are configurable appender options. I would like to submit this to Apache. Thanks, Jamie Tsaoapache-log4j1.2-1.2.17.orig/contribs/VolkerMentzner/0000755000175000017500000000000012126647422020602 5ustar tonytonyapache-log4j1.2-1.2.17.orig/contribs/VolkerMentzner/mail-03-05-20010000644000175000017500000000300111751454673022472 0ustar tonytony Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Delivered-To: cgu@qos.ch From: "Mentzner, Volker" To: "'cgu@qos.ch'" Subject: Remote configuring log4j Date: Thu, 3 May 2001 08:10:25 +0200 X-Mailer: Internet Mail Service (5.5.2653.19) Hi Ceki, I am using log4j in a GUI project. Working at the application I found it useful to remotely configure log4j with my favourite browser. This is reached by using a very small web server (PluggableHTTPServer) with extentions for tasks like configuring log4j. You can easily put this web server in an application, an example can be found in PluggableHTTPServer.main(). Maybe someone else can use this too, so I sent it to you to give it to the contrib dir if you like it. Regards Volker Mentzner <> apache-log4j1.2-1.2.17.orig/contribs/VolkerMentzner/HTTPRequestHandler.java0000644000175000017500000000525711751454673025113 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.psibt.framework.net; import java.io.*; import java.net.*; /** * This interface defines all methods that have to be implemented for a HTTPRequestHandler for the * PluggableHTTPServer. * * @author Volker Mentzner */ public interface HTTPRequestHandler { /** * Gets the title for html page */ public String getTitle(); /** * Sets the title for html page */ public void setTitle(String title); /** * Gets the description for html page */ public String getDescription(); /** * Sets the description for html page */ public void setDescription(String description); /** * Gets the virtual path in the HTTP server that ist handled in this HTTPRequestHandler. * So the root path handler will return "/" (without brackets) because it handles the path * "http://servername/" or a handler for "http://servername/somepath/" will return "/somepath/" * It is important to include the trailing "/" because all HTTPRequestHandler have to serve a path! */ public String getHandledPath(); /** * Sets the virtual path in the HTTP server that ist handled in this HTTPRequestHandler. * So set the path to "/" for the root path handler because it handles the path * "http://servername/" or set it to "/somepath/" for a handler for "http://servername/somepath/". * It is important to include the trailing "/" because all HTTPRequestHandler have to serve a path! */ public void setHandledPath(String path); /** * Handles the given request and writes the reply to the given out-stream. Every handler has to check * the request for the right path info. * * @param request - client browser request * @param out - Out stream for sending data to client browser * @return if the request was handled by this handler : true, else : false */ public boolean handleRequest(String request, Writer out); }apache-log4j1.2-1.2.17.orig/contribs/VolkerMentzner/RootRequestHandler.java0000644000175000017500000000774211751454673025260 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.psibt.framework.net; import java.io.*; import java.net.*; import java.util.*; /** * This class implements a RequestHandler for the root path "/" in the PluggableHTTPServer. * A simple HTML message will be replied to the client. * * @author Volker Mentzner */ public class RootRequestHandler implements HTTPRequestHandler { private String title; private String description; private String handledPath; private String ReplyType = "Content-type: text/html\r\n\r\n"; private String ReplyHTML = "Root\r\n" + "

Root

\r\n" + "\r\n"; /** * Creates a new RootRequestHandler object */ public RootRequestHandler() { this.setTitle("root page"); this.setDescription("root page"); this.setHandledPath("/"); } /** * Gets the content type of the reply HTTP message * * @return content type as String */ public String getReplyType() { return this.ReplyType; } /** * Sets the content type of the reply HTTP message * * @param ReplyType - content type as String */ public void setReplyType(String ReplyType) { this.ReplyType = ReplyType; } /** * Gets the HTML data of the reply HTTP message * * @return HTML message as String */ public String getReplyHTML() { return this.ReplyHTML; } /** * Sets the HTML data of the reply HTTP message * * @param ReplyHTML - HTML message as String */ public void setReplyHTML(String ReplyHTML) { this.ReplyHTML = ReplyHTML; } /** * Gets the title for html page */ public String getTitle() { return this.title; } /** * Sets the title for html page */ public void setTitle(String title) { this.title = title; } /** * Gets the description for html page */ public String getDescription() { return this.description; } /** * Sets the description for html page */ public void setDescription(String description) { this.description = description; } /** * Gets the server path * * @return the server path */ public String getHandledPath() { return this.handledPath; } /** * Sets the server path * * @param path - the server path */ public void setHandledPath(String path) { this.handledPath = path; } /** * Handles the given request and writes the reply to the given out-stream. * * @param request - client browser request * @param out - Out stream for sending data to client browser * @return if the request was handled by this handler : true, else : false */ public boolean handleRequest(String request, Writer out) { String path = ""; String query = null; try { URL url = new URL("http://localhost"+request); path = url.getPath(); query = url.getPath(); if (path.equals(handledPath) == false) { return false; } out.write("HTTP/1.0 200 OK\r\n"); if (ReplyType != null) out.write(ReplyType); if (ReplyHTML != null) out.write(ReplyHTML); out.flush(); return true; } catch (Exception ex) { return false; } } }apache-log4j1.2-1.2.17.orig/contribs/VolkerMentzner/PluggableHTTPServer.java0000644000175000017500000001775211751454673025261 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.psibt.framework.net; import java.net.*; import java.io.*; import java.util.*; import org.apache.log4j.*; /** * This class implements a HTTP-server frame. All HTTP-requests are handled by HTTPRequestHandler * classes which implement the HTTPRequestHandler interface. Every RequestHandler has * to be registered in the PluggableHTTPServer with the addRequestHandler method. * A new thread is created for each connection to handle the request. If all reply data are sent * to the client the connection is closed and the thread ends. * An example how to use the PluggableHTTPServer class can be found in the main method * at the end of the source file. * * @author Volker Mentzner */ public class PluggableHTTPServer implements Runnable { public static final int DEFAULT_PORT = 80; static Category cat = Category.getInstance("PluggableHTTPServer"); private int port; private Vector handler; private ServerSocket server; /** * Creates a new server object on the given TCP port. * If the port is occupied by another process a IOException (java.net.BindException) is thrown. * * @param port - TCP port number to listen on for requests */ public PluggableHTTPServer(int port) throws IOException { this.port = port; this.handler = new Vector(); cat.setPriority(Priority.ERROR); server = new ServerSocket(this.port); } /** * Creates a new server object on the default TCP port 80 * If the port is occupied by another process a IOException (java.net.BindException) is thrown. */ public PluggableHTTPServer() throws IOException { this(DEFAULT_PORT); } /** * Registers the given HTTPRequestHandler * * @param h - the HTTPRequestHandler to register */ public void addRequestHandler(HTTPRequestHandler h) { handler.add(h); } /** * Unregisters the given HTTPRequestHandler * * @param h - the HTTPRequestHandler to unregister */ public void removeRequestHandler(HTTPRequestHandler h) { handler.remove(h); } /** * Sends the HTTP message 404 - File Not Found * see RFC2616 for details * * @param out - Out stream for sending data to client browser */ public static void replyNotFound(Writer out) { try { out.write("HTTP/1.0 404 Not Found\r\n"); out.write("Not Found\r\n"); out.write("

Not Found

\r\n"); out.write("\r\n"); out.flush(); } // end try catch (IOException e) { } } /** * Sends the HTTP message 405 - Method Not Allowed * see RFC2616 for details * * @param out - Out stream for sending data to client browser */ public static void replyMethodNotAllowed(Writer out) { try { out.write("HTTP/1.1 405 Method Not Allowed\r\n"); out.write("Allow: GET, PUT\r\n"); out.write("Method Not Allowed\r\n"); out.write("

Method Not Allowed

\r\n"); out.write("\r\n"); out.flush(); } // end try catch (IOException e) { } } /** * Creates the ReplyHTML data for the root page * * @param index - index of the RootRequestHandler */ public void autoCreateRootPage(int index) { if (handler.get(index) instanceof RootRequestHandler) { RootRequestHandler r = (RootRequestHandler)handler.get(index); String html = ""+r.getTitle()+"\r\n"; html = html + "

"+r.getDescription()+"

\r\n"; for (int i = 0; i < handler.size(); i++) { html = html + "" + ((HTTPRequestHandler)handler.get(i)).getDescription() + "
"; } html = html + "\r\n"; r.setReplyHTML(html); } } /** * Main loop of the PluggableHTTPServer */ public void run() { while (true) { try { Socket s = server.accept(); Thread t = new ServerThread(s); t.start(); } catch (IOException e) { } } } /** * This class handles the incomming connection for one request. */ class ServerThread extends Thread { private Socket connection; ServerThread(Socket s) { this.connection = s; } /** * Serves the HTTP request. */ public void run() { try { Writer out = new BufferedWriter( new OutputStreamWriter( connection.getOutputStream(), "ASCII" ) ); Reader in = new InputStreamReader( new BufferedInputStream( connection.getInputStream() ) ); // read the first line only; that's all we need StringBuffer req = new StringBuffer(80); while (true) { int c = in.read(); if (c == '\r' || c == '\n' || c == -1) break; req.append((char) c); } String get = req.toString(); cat.debug(get); StringTokenizer st = new StringTokenizer(get); String method = st.nextToken(); String request = st.nextToken(); String version = st.nextToken(); if (method.equalsIgnoreCase("GET")) { boolean served = false; for (int i = 0; i < handler.size(); i++) { if (handler.get(i) instanceof HTTPRequestHandler) { if (((HTTPRequestHandler)handler.get(i)).handleRequest(request, out)) { served = true; break; } } } if (!served) PluggableHTTPServer.replyNotFound(out); } else { PluggableHTTPServer.replyMethodNotAllowed(out); } } // end try catch (IOException e) { } finally { try { if (connection != null) connection.close(); } catch (IOException e) {} } } // end run } // end class ServerThread /** * Demo how to use the PluggableHTTPServer. */ public static void main(String[] args) { int thePort; // create some logging stuff BasicConfigurator.configure(); Category cat1 = Category.getInstance("cat1"); cat1.addAppender(new org.apache.log4j.ConsoleAppender(new PatternLayout("%m%n"))); Category cat2 = Category.getInstance("cat2"); cat2.setPriority(Priority.INFO); cat2.addAppender(new org.apache.log4j.ConsoleAppender(new PatternLayout("%c - %m%n"))); // set TCP port number try { thePort = Integer.parseInt(args[1]); } catch (Exception e) { thePort = PluggableHTTPServer.DEFAULT_PORT; } PluggableHTTPServer server = null; while (server == null) { try { server = new PluggableHTTPServer(thePort); server.addRequestHandler(new RootRequestHandler()); server.addRequestHandler(new Log4jRequestHandler()); server.addRequestHandler(new UserDialogRequestHandler()); server.autoCreateRootPage(0); Thread t = new Thread(server); t.start(); } catch (IOException e) { server = null; thePort++; } } } // end main } apache-log4j1.2-1.2.17.orig/contribs/VolkerMentzner/UserDialogRequestHandler.java0000644000175000017500000001134311751454673026363 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Title: PSI Java Framework: UserDialogRequestHandler

* Copyright: PSI-BT AG

* History: * Date Author What's new * 16.04.2001 VMentzner Created */ package com.psibt.framework.net; /** * This class implements a RequestHandler for the path "/userdialog/" in the PluggableHTTPServer. * A simple input form is presented in the browser where you can enter a message. This message will be sent * to the PluggableHTTPServer and shown in a JOptionPane MessageDialog. * * @author Volker Mentzner */ public class UserDialogRequestHandler extends RootRequestHandler { private Component parentComponent; /** * Creates a new UserDialogRequestHandler object */ public UserDialogRequestHandler() { this(null); } /** * Creates a new UserDialogRequestHandler object with a parentComponent reference */ public UserDialogRequestHandler(Component parentComponent) { this.setTitle("user dialog"); this.setDescription("show user dialog"); this.setHandledPath("/userdialog/"); this.parentComponent = parentComponent; } /** * Handles the given request and writes the reply to the given out-stream. * * @param request - client browser request * @param out - Out stream for sending data to client browser * @return if the request was handled by this handler : true, else : false */ public boolean handleRequest(String request, Writer out) { String path = ""; String query = null; try { URL url = new URL("http://localhost"+request); path = url.getPath(); query = url.getQuery(); if (path.startsWith(this.getHandledPath()) == false) { return false; } out.write("HTTP/1.0 200 OK\r\n"); out.write("Content-type: text/html\r\n\r\n"); out.write("" + this.getTitle() + "\r\n"); out.write("

" + this.getDescription() + "

\r\n"); if ((query != null) && (query.length() >= 0)) { int idx = query.indexOf("="); String message = query.substring(idx+1, query.length()); // replace '+' by space message = message.replace('+', ' '); // replace hex strings starting with '%' by their values idx = message.indexOf("%"); while (idx >= 0) { String sl = message.substring(0, idx); String sm = message.substring(idx+1, idx+3); String sr = message.substring(idx+3, message.length()); try { int i = Integer.parseInt(sm, 16); sm = String.valueOf((char)i); } catch (Exception ex) { sm = ""; } message = sl + sm + sr; idx = message.indexOf("%"); } // show message in a new thread if ((message != null) && (message.length() > 0)) { Thread t = new Thread(new DialogThread(parentComponent, message)); t.start(); } } out.write("
"); out.write("\r\n"); out.write(" \r\n"); out.write(" \r\n"); out.write("
Send message to user
\r\n"); out.write(""); out.write("
"); out.write("\r\n"); out.flush(); return true; } catch (Exception ex) { return false; } } /** * Internal class to start the user dialog in a new thread. This makes the RequestHandler return * immediatly */ class DialogThread implements Runnable { private Component parentComponent; private String message; public DialogThread(Component parentComponent, String message) { this.parentComponent = parentComponent; this.message = message; } public void run() { JOptionPane.showMessageDialog(parentComponent, message); } } }apache-log4j1.2-1.2.17.orig/contribs/VolkerMentzner/Log4jRequestHandler.java0000644000175000017500000001466011751454673025311 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.psibt.framework.net; import java.io.*; import java.net.*; import java.util.*; import org.apache.log4j.*; /** * This class implements a RequestHandler for log4j configuration. It serves the "/log4j/" path * in the PluggableHTTPServer. If this path is requested a list of all current log4j categories * with their current priorities is created. All priority settings can be changed by the user * and can be submitted and taken over. * * @author Volker Mentzner */ public class Log4jRequestHandler extends RootRequestHandler { private Priority[] prios = Priority.getAllPossiblePriorities(); /** * Creates a new Log4jRequestHandler object */ public Log4jRequestHandler() { this.setTitle("log4j"); this.setDescription("log4j configuration"); this.setHandledPath("/log4j/"); } /** * Handles the given request and writes the reply to the given out-stream. * * @param request - client browser request * @param out - Out stream for sending data to client browser * @return if the request was handled by this handler : true, else : false */ public boolean handleRequest(String request, Writer out) { String path = ""; String query = null; String name; try { // check request url URL url = new URL("http://localhost"+request); path = url.getPath(); query = url.getQuery(); if (path.startsWith(this.getHandledPath()) == false) { return false; } out.write("HTTP/1.0 200 OK\r\n"); out.write("Content-type: text/html\r\n\r\n"); out.write("" + this.getTitle() + "\r\n"); out.write("

log4j

\r\n"); out.write(this.getDescription() + "

\r\n"); // handle a request with query if ((query != null) && (query.length() >= 0)) { StringTokenizer st = new StringTokenizer(query, "&"); String cmd; String catname; String catval; int idx; while (st.hasMoreTokens()) { cmd = st.nextToken(); idx = cmd.indexOf("="); catname = cmd.substring(0, idx); catval = cmd.substring(idx+1, cmd.length()); if (catname.equalsIgnoreCase("root")) Category.getRoot().setPriority(Priority.toPriority(catval)); else Category.getInstance(catname).setPriority(Priority.toPriority(catval)); } } // output category information in a form with a simple table out.write("
"); out.write("\r\n"); out.write(" \r\n"); out.write(" \r\n"); out.write(" \r\n"); out.write(" \r\n"); out.write(" \r\n"); // output for root category Category cat = Category.getRoot(); out.write(" \r\n"); out.write(" \r\n"); out.write(" \r\n"); out.write(" \r\n"); // output for all other categories for (Enumeration en = Category.getCurrentCategories(); en.hasMoreElements();) { cat = (Category)en.nextElement(); out.write(" \r\n"); out.write(" \r\n"); out.write(" \r\n"); out.write(" \r\n"); out.write(" \r\n"); } out.write("
CategoryPriorityAppender
root\r\n"); out.write(" \r\n"); out.write(" \r\n"); for (Enumeration apds = cat.getAllAppenders(); apds.hasMoreElements();) { Appender apd = (Appender)apds.nextElement(); name = apd.getName(); if (name == null) name = "(no name)"; out.write(name); if (apd instanceof AppenderSkeleton) { try { AppenderSkeleton apskel = (AppenderSkeleton)apd; out.write(" [" + apskel.getThreshold().toString() + "]"); } catch (Exception ex) { } } if (apds.hasMoreElements()) out.write(", "); } out.write("
" + cat.getName() + "\r\n"); out.write(" \r\n"); out.write(" \r\n"); for (Enumeration apds = cat.getAllAppenders(); apds.hasMoreElements();) { Appender apd = (Appender)apds.nextElement(); name = apd.getName(); if (name == null) name = "(no name)"; out.write(name); if (apd instanceof AppenderSkeleton) { try { AppenderSkeleton apskel = (AppenderSkeleton)apd; out.write(" [" + apskel.getThreshold().toString() + "]"); } catch (Exception ex) { } } if (apds.hasMoreElements()) out.write(", "); } out.write("
\r\n"); out.write(""); out.write("
"); out.write("\r\n"); out.flush(); return true; } catch (Exception ex) { return false; } } }apache-log4j1.2-1.2.17.orig/contribs/CekiGulcu/0000755000175000017500000000000012126647422017470 5ustar tonytonyapache-log4j1.2-1.2.17.orig/contribs/CekiGulcu/AppenderTable.java0000644000175000017500000001642511751454702023051 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.log4j.helpers.CyclicBuffer; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.Layout; import org.apache.log4j.PatternLayout; import org.apache.log4j.spi.LoggingEvent; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.JScrollPane; import javax.swing.BoxLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Container; /** The AppenderTable illustrates one possible implementation of an Table possibly containing a great many number of rows.

In this particular example we use a fixed size buffer (CyclicBuffer) although this data structure could be easily replaced by dynamically growing one, such as a Vector. The required properties of the data structure is 1) support for indexed element access 2) support for the insertion of new elements at the end.

Experimentation on my 1400Mhz AMD machine show that it takes about 45 micro-seconds to insert an element in the table. This number does not depend on the size of the buffer. It takes as much (or as little) time to insert one million elements to a buffer of size 10 as to a buffer of size 10'000. It takes about 4 seconds to insert a total of 100'000 elements into the table.

On windows NT the test will run about twice as fast if you give the focus to the window that runs "java AppenderTable" and not the window that contains the Swing JFrame. */ public class AppenderTable extends JTable { static Logger logger = Logger.getLogger(AppenderTable.class); static public void main(String[] args) { if(args.length != 2) { System.err.println( "Usage: java AppenderTable bufferSize runLength\n" +" where bufferSize is the size of the cyclic buffer in the TableModel\n" +" and runLength is the total number of elements to add to the table in\n" +" this test run."); return; } JFrame frame = new JFrame("JTableAppennder test"); Container container = frame.getContentPane(); AppenderTable tableAppender = new AppenderTable(); int bufferSize = Integer.parseInt(args[0]); AppenderTableModel model = new AppenderTableModel(bufferSize); tableAppender.setModel(model); int runLength = Integer.parseInt(args[1]); JScrollPane sp = new JScrollPane(tableAppender); sp.setPreferredSize(new Dimension(250, 80)); container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS)); container.add(sp); // The "ADD" button is intended for manual testing. It will // add one new logging event to the table. JButton button = new JButton("ADD"); container.add(button); button.addActionListener(new JTableAddAction(tableAppender)); frame.setSize(new Dimension(500,300)); frame.setVisible(true); long before = System.currentTimeMillis(); int i = 0; while(i++ < runLength) { LoggingEvent event = new LoggingEvent("x", logger, Level.ERROR, "Message "+i, null); tableAppender.doAppend(event); } long after = System.currentTimeMillis(); long totalTime = (after-before); System.out.println("Total time :"+totalTime+ " milliseconds for "+ "runLength insertions."); System.out.println("Average time per insertion :" +(totalTime*1000/runLength)+ " micro-seconds."); } public AppenderTable() { this.setDefaultRenderer(Object.class, new Renderer()); } /** When asked to append we just insert directly into the model. In a real appender we would use two buffers one for accumulating events and another to accumalte events but after filtering. Only the second buffer would be displayed in the table and made visible to the user.*/ public void doAppend(LoggingEvent event) { ((AppenderTableModel)getModel()).insert(event); } /** The Renderer is required to display object in a friendlier from. This particular renderer is just a JTextArea.

The important point to note is that we only need *one* renderer. */ class Renderer extends JTextArea implements TableCellRenderer { PatternLayout layout; public Renderer() { layout = new PatternLayout("%r %p %c [%t] - %m"); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { // If its a LoggingEvent than format it using our layout. if(value instanceof LoggingEvent) { LoggingEvent event = (LoggingEvent) value; String str = layout.format(event); setText(str); } else { setText(value.toString()); } return this; } } } class AppenderTableModel extends AbstractTableModel { CyclicBuffer cb; AppenderTableModel(int size) { cb = new CyclicBuffer(size); } /** Insertion to the model always results in a fireTableDataChanged method call. Suprisingly enough this has no crippling impact on performance. */ public void insert(LoggingEvent event) { cb.add(event); fireTableDataChanged(); } /** We assume only one column. */ public int getColumnCount() { return 1; } /** The row count is given by the number of elements in the buffer. This number is guaranteed to be between 0 and the buffer size (inclusive). */ public int getRowCount() { return cb.length(); } /** Get the value in a given row and column. We suppose that there is only one colemn so we are only concerned with the row.

Interesting enough this method returns an object. This leaves the door open for a TableCellRenderer to render the object in a variety of ways. */ public Object getValueAt(int row, int col) { return cb.get(row); } } /** The JTableAddAction is called when the user clicks on the "ADD" button. */ class JTableAddAction implements ActionListener { AppenderTable appenderTable; Logger dummy = Logger.getLogger("x"); int counter = 0; public JTableAddAction(AppenderTable appenderTable) { this.appenderTable = appenderTable; } public void actionPerformed(ActionEvent e) { counter++; LoggingEvent event = new LoggingEvent("x", dummy, Level.DEBUG, "Message "+counter, null); appenderTable.doAppend(event); } } apache-log4j1.2-1.2.17.orig/contribs/CekiGulcu/Transform.java0000644000175000017500000001606511751454702022316 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.xml; import org.apache.log4j.Category; import org.apache.log4j.Layout; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.helpers.OptionConverter; import org.apache.log4j.helpers.DateLayout; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.Attributes; import org.xml.sax.XMLReader; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.XMLReaderFactory; import org.xml.sax.SAXException; import org.apache.xerces.parsers.SAXParser; import org.apache.trax.Processor; import org.apache.trax.TemplatesBuilder; import org.apache.trax.Templates; import org.apache.trax.Transformer; import org.apache.trax.Result; import org.apache.trax.ProcessorException; import org.apache.trax.ProcessorFactoryException; import org.apache.trax.TransformException; import org.apache.serialize.SerializerFactory; import org.apache.serialize.Serializer; import org.apache.serialize.OutputFormat; import org.xml.sax.helpers.AttributesImpl; import java.io.FileOutputStream; import java.io.IOException; public class Transform { public static void main(String[] args) throws Exception { PropertyConfigurator.disableAll(); PropertyConfigurator.configure("x.lcf"); // I. Instantiate a stylesheet processor. Processor processor = Processor.newInstance("xslt"); // II. Process the stylesheet. producing a Templates object. // Get the XMLReader. XMLReader reader = XMLReaderFactory.createXMLReader(); // Set the ContentHandler. TemplatesBuilder templatesBuilder = processor.getTemplatesBuilder(); reader.setContentHandler(templatesBuilder); // Set the ContentHandler to also function as a LexicalHandler, which // includes "lexical" (e.g., comments and CDATA) events. The Xalan // TemplatesBuilder -- org.apache.xalan.processor.StylesheetHandler -- is // also a LexicalHandler). if(templatesBuilder instanceof LexicalHandler) { reader.setProperty("http://xml.org/sax/properties/lexical-handler", templatesBuilder); } // Parse the stylesheet. reader.parse(args[0]); //Get the Templates object from the ContentHandler. Templates templates = templatesBuilder.getTemplates(); // III. Use the Templates object to instantiate a Transformer. Transformer transformer = templates.newTransformer(); // IV. Perform the transformation. // Set up the ContentHandler for the output. FileOutputStream fos = new FileOutputStream(args[2]); Result result = new Result(fos); Serializer serializer = SerializerFactory.getSerializer("xml"); serializer.setOutputStream(fos); transformer.setContentHandler(serializer.asContentHandler()); // Set up the ContentHandler for the input. org.xml.sax.ContentHandler chandler = transformer.getInputContentHandler(); DC dc = new DC(chandler); reader.setContentHandler(dc); if(chandler instanceof LexicalHandler) { reader.setProperty("http://xml.org/sax/properties/lexical-handler", chandler); } else { reader.setProperty("http://xml.org/sax/properties/lexical-handler", null); } // Parse the XML input document. The input ContentHandler and // output ContentHandler work in separate threads to optimize // performance. reader.parse(args[1]); } } class DC implements ContentHandler { static Category cat = Category.getInstance("DC"); ContentHandler chandler; DC(ContentHandler chandler) { this.chandler = chandler; } public void characters(char[] ch, int start, int length) throws org.xml.sax.SAXException { cat.debug("characters: ["+new String(ch, start, length)+ "] called"); chandler.characters(ch, start, length); } public void endDocument() throws org.xml.sax.SAXException { cat.debug("endDocument called."); chandler.endDocument(); } public void endElement(String namespaceURI, String localName, String qName) throws org.xml.sax.SAXException { cat.debug("endElement("+namespaceURI+", "+localName+", "+qName+") called"); chandler.endElement(namespaceURI, localName, qName); } public void endPrefixMapping(String prefix) throws org.xml.sax.SAXException { cat.debug("endPrefixMapping("+prefix+") called"); chandler.endPrefixMapping(prefix); } public void ignorableWhitespace(char[] ch, int start, int length) throws org.xml.sax.SAXException { cat.debug("ignorableWhitespace called"); chandler.ignorableWhitespace(ch, start, length); } public void processingInstruction(java.lang.String target, java.lang.String data) throws org.xml.sax.SAXException { cat.debug("processingInstruction called"); chandler.processingInstruction(target, data); } public void setDocumentLocator(Locator locator) { cat.debug("setDocumentLocator called"); chandler.setDocumentLocator(locator); } public void skippedEntity(String name) throws org.xml.sax.SAXException { cat.debug("skippedEntity("+name+") called"); chandler.skippedEntity(name); } public void startDocument() throws org.xml.sax.SAXException { cat.debug("startDocument called"); chandler.startDocument(); } public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws org.xml.sax.SAXException { cat.debug("startElement("+namespaceURI+", "+localName+", "+qName+")called"); if("log4j:event".equals(qName)) { cat.debug("-------------"); if(atts instanceof org.xml.sax.helpers.AttributesImpl) { AttributesImpl ai = (AttributesImpl) atts; int i = atts.getIndex("timestamp"); ai.setValue(i, "hello"); } String ts = atts.getValue("timestamp"); cat.debug("New timestamp is " + ts); } chandler.startElement(namespaceURI, localName, qName, atts); } public void startPrefixMapping(String prefix, String uri) throws org.xml.sax.SAXException { cat.debug("startPrefixMapping("+prefix+", "+uri+") called"); chandler.startPrefixMapping(prefix, uri); } }