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