1 16 17 package org.apache.log4j.net.test; 18 19 import org.apache.log4j.Logger; 20 import org.apache.log4j.BasicConfigurator; 21 import org.apache.log4j.net.SocketAppender; 22 import org.apache.log4j.Priority; 23 import org.apache.log4j.NDC; 24 import java.io.InputStreamReader ; 25 26 public class SocketMin { 27 28 static Logger cat = Logger.getLogger(SyslogMin.class.getName()); 29 static SocketAppender s; 30 31 public 32 static 33 void main(String argv[]) { 34 if(argv.length == 3) 35 init(argv[0], argv[1]); 36 else 37 usage("Wrong number of arguments."); 38 39 NDC.push("some context"); 40 if(argv[2].equals("true")) 41 loop(); 42 else 43 test(); 44 45 s.close(); 46 } 47 48 static 49 void usage(String msg) { 50 System.err.println(msg); 51 System.err.println("Usage: java " + SocketMin.class 52 + " host port true|false"); 53 System.exit(1); 54 } 55 56 static 57 void init(String host, String portStr) { 58 Logger root = Logger.getRootLogger(); 59 BasicConfigurator.configure(); 60 try { 61 int port = Integer.parseInt(portStr); 62 cat.info("Creating socket appender ("+host+","+port+")."); 63 s = new SocketAppender(host, port); 64 s.setName("S"); 65 root.addAppender(s); 66 } 67 catch(java.lang.NumberFormatException e) { 68 e.printStackTrace(); 69 usage("Could not interpret port number ["+ portStr +"]."); 70 } 71 catch(Exception e) { 72 System.err.println("Could not start!"); 73 e.printStackTrace(); 74 System.exit(1); 75 } 76 } 77 78 static 79 void loop() { 80 Logger root = Logger.getRootLogger(); 81 InputStreamReader in = new InputStreamReader (System.in); 82 System.out.println("Type 'q' to quit"); 83 int i; 84 int k = 0; 85 while (true) { 86 cat.debug("Message " + k++); 87 cat.info("Message " + k++); 88 cat.warn("Message " + k++); 89 cat.error("Message " + k++, new Exception ("Just testing")); 90 try {i = in.read(); } 91 catch(Exception e) { return; } 92 if(i == -1) break; 93 if(i == 'q') break; 94 if(i == 'r') { 95 System.out.println("Removing appender S"); 96 root.removeAppender("S"); 97 } 98 } 99 } 100 101 static 102 void test() { 103 int i = 0; 104 cat.debug( "Message " + i++); 105 cat.info( "Message " + i++); 106 cat.warn( "Message " + i++); 107 cat.error( "Message " + i++); 108 cat.log(Priority.FATAL, "Message " + i++); 109 cat.debug("Message " + i++, new Exception ("Just testing.")); 110 } 111 } 112 | Popular Tags |