1 16 17 package org.apache.log4j.net; 18 19 import java.io.*; 20 import java.net.*; 21 import java.util.*; 22 import org.apache.log4j.Layout; 23 import org.apache.log4j.spi.LoggingEvent; 24 import org.apache.log4j.AppenderSkeleton; 25 import org.apache.log4j.helpers.LogLog; 26 27 54 55 public class TelnetAppender extends AppenderSkeleton { 56 57 private SocketHandler sh; 58 private int port = 23; 59 60 63 public boolean requiresLayout() { 64 return true; 65 } 66 67 69 public void activateOptions() { 70 try { 71 sh = new SocketHandler(port); 72 sh.start(); 73 } 74 catch(Exception e) { 75 e.printStackTrace(); 76 } 77 } 78 79 public 80 int getPort() { 81 return port; 82 } 83 84 public 85 void setPort(int port) { 86 this.port = port; 87 } 88 89 90 91 public void close() { 92 sh.finalize(); 93 } 94 95 97 protected void append(LoggingEvent event) { 98 sh.send(this.layout.format(event)); 99 if(layout.ignoresThrowable()) { 100 String [] s = event.getThrowableStrRep(); 101 if (s != null) { 102 int len = s.length; 103 for(int i = 0; i < len; i++) { 104 sh.send(s[i]); 105 sh.send(Layout.LINE_SEP); 106 } 107 } 108 } 109 } 110 111 113 116 protected class SocketHandler extends Thread { 117 118 private boolean done = false; 119 private Vector writers = new Vector(); 120 private Vector connections = new Vector(); 121 private ServerSocket serverSocket; 122 private int MAX_CONNECTIONS = 20; 123 124 125 public void finalize() { 126 for(Enumeration e = connections.elements();e.hasMoreElements();) { 127 try { 128 ((Socket)e.nextElement()).close(); 129 } catch(Exception ex) { 130 } 131 } 132 try { 133 serverSocket.close(); 134 } catch(Exception ex) { 135 } 136 done = true; 137 } 138 139 140 public void send(String message) { 141 Enumeration ce = connections.elements(); 142 for(Enumeration e = writers.elements();e.hasMoreElements();) { 143 Socket sock = (Socket)ce.nextElement(); 144 PrintWriter writer = (PrintWriter)e.nextElement(); 145 writer.print(message); 146 if(writer.checkError()) { 147 connections.remove(sock); 149 writers.remove(writer); 150 } 151 } 152 } 153 154 158 public void run() { 159 while(!done) { 160 try { 161 Socket newClient = serverSocket.accept(); 162 PrintWriter pw = new PrintWriter(newClient.getOutputStream()); 163 if(connections.size() < MAX_CONNECTIONS) { 164 connections.addElement(newClient); 165 writers.addElement(pw); 166 pw.print("TelnetAppender v1.0 (" + connections.size() 167 + " active connections)\r\n\r\n"); 168 pw.flush(); 169 } else { 170 pw.print("Too many connections.\r\n"); 171 pw.flush(); 172 newClient.close(); 173 } 174 } catch(Exception e) { 175 LogLog.error("Encountered error while in SocketHandler loop.", e); 176 } 177 } 178 } 179 180 public SocketHandler(int port) throws IOException { 181 serverSocket = new ServerSocket(port); 182 } 183 184 } 185 } 186 | Popular Tags |