1 7 8 9 package java.util.logging; 10 11 import java.io.*; 12 import java.net.*; 13 14 49 50 public class SocketHandler extends StreamHandler { 51 private Socket sock; 52 private String host; 53 private int port; 54 private String portProperty; 55 56 private void configure() { 60 LogManager manager = LogManager.getLogManager(); 61 String cname = getClass().getName(); 62 63 setLevel(manager.getLevelProperty(cname +".level", Level.ALL)); 64 setFilter(manager.getFilterProperty(cname +".filter", null)); 65 setFormatter(manager.getFormatterProperty(cname +".formatter", new XMLFormatter ())); 66 try { 67 setEncoding(manager.getStringProperty(cname +".encoding", null)); 68 } catch (Exception ex) { 69 try { 70 setEncoding(null); 71 } catch (Exception ex2) { 72 } 75 } 76 port = manager.getIntProperty(cname + ".port", 0); 77 host = manager.getStringProperty(cname + ".host", null); 78 } 79 80 81 89 public SocketHandler() throws IOException { 90 sealed = false; 92 configure(); 93 94 try { 95 connect(); 96 } catch (IOException ix) { 97 System.err.println("SocketHandler: connect failed to " + host + ":" + port); 98 throw ix; 99 } 100 sealed = true; 101 } 102 103 118 public SocketHandler(String host, int port) throws IOException { 119 sealed = false; 120 configure(); 121 sealed = true; 122 this.port = port; 123 this.host = host; 124 connect(); 125 } 126 127 private void connect() throws IOException { 128 if (port == 0) { 130 throw new IllegalArgumentException ("Bad port: " + port); 131 } 132 if (host == null) { 133 throw new IllegalArgumentException ("Null host name: " + host); 134 } 135 136 sock = new Socket(host, port); 138 OutputStream out = sock.getOutputStream(); 139 BufferedOutputStream bout = new BufferedOutputStream(out); 140 setOutputStream(bout); 141 } 142 143 149 public synchronized void close() throws SecurityException { 150 super.close(); 151 if (sock != null) { 152 try { 153 sock.close(); 154 } catch (IOException ix) { 155 } 157 } 158 sock = null; 159 } 160 161 167 public synchronized void publish(LogRecord record) { 168 if (!isLoggable(record)) { 169 return; 170 } 171 super.publish(record); 172 flush(); 173 } 174 } 175 | Popular Tags |