1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
package org.apache.juli;
import java.util.logging.*;
import java.net.*;
import java.io.FileWriter;
public class UDPSocketHandler extends Handler {
protected String host;
protected int port;
protected DatagramSocket socket;
protected String msg;
protected FileWriter fw;
private void configure() {
String className = UDPSocketHandler.class.getName();
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if(port == 0) port = Integer.parseInt(getProperty(className + ".port", "" + 9632));
if(host == null) host = getProperty(className + ".host", "localhost");
setLevel(Level.parse(getProperty(className + ".level", "" + Level.ALL)));
try {
setFilter((Filter) cl.loadClass(getProperty(className + ".filter", null)).newInstance());
setFormatter((Formatter) cl.loadClass(getProperty(className + ".formatter", null)).newInstance());
setEncoding(getProperty(className + ".encoding", null));
}
catch(Exception e){
e.printStackTrace();
}
}
public UDPSocketHandler(){
this(null, 0);
}
public UDPSocketHandler(String host, int port){
try{
fw = new FileWriter("toto.txt");
}catch(Exception e){}
this.port = port;
this.host = host;
configure();
connect();
}
private void connect(){
if (port == 0) throw new IllegalArgumentException("Bad port : " + port);
if (host == null) throw new IllegalArgumentException("Null host name : " + host);
// Try to open a new socket.
try {
socket = new DatagramSocket();
//socket.connect(InetAddress.getByName(host), port);
}
catch(Exception e){
System.err.println("Unable to connect to host " + host + " on port " + port);
e.printStackTrace();
}
}
public void close() throws SecurityException {
socket.close();
socket = null;
try{fw.close();}catch(Exception e){}
}
public void flush(){
byte[] buffer = msg.getBytes();
try {
DatagramPacket sentData = new DatagramPacket(buffer, buffer.length,
InetAddress.getByName(host), port);
socket.send(sentData);
}
catch(Exception e){
e.printStackTrace();
}
}
public void publish(LogRecord record){
if(!isLoggable(record)) return;
msg = getFormatter().format(record);
try{fw.append(msg);}catch(Exception e){}
flush();
}
private String getProperty(String name, String defaultValue) {
String value = LogManager.getLogManager().getProperty(name);
if (value == null) value = defaultValue;
else value = value.trim();
return value;
}
} |
Partager