log4j UdpAppender

package cappender;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Layout;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

import java.io.IOException;
import java.net.*;


public class UDPAppender extends AppenderSkeleton {
static private int bufferSize = 8 * 1024;

private byte data[];
private String remoteHost = "localhost";
private int port = 5000;

private InetAddress address = null;
private DatagramSocket dataSocket = null;
private DatagramPacket dataPacket = null;

public UDPAppender() {

}

private void init() {
try {
dataSocket = new DatagramSocket(this.port + 1);
address = InetAddress.getByName(remoteHost);
} catch (SocketException e) {
LogLog.debug(e.getMessage());
} catch (UnknownHostException e) {
LogLog.debug(e.getMessage());
}

data = new byte[bufferSize];

if (this.layout == null) {
LogLog.debug("The layout is not loaded... we set it.");
String pattern = "%-4r %-5p %d{yyyy-MM-dd HH:mm:ss} %c %m%n";
this.setLayout(new org.apache.log4j.PatternLayout(pattern));
}
}

@Override
protected void append(LoggingEvent event) {
try {
data = subAppend(event).getBytes();
dataPacket = new DatagramPacket(data, data.length, address, port);
dataSocket.send(dataPacket);
} catch (SocketException se) {
se.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
}
}


private String subAppend(LoggingEvent event) {

StringBuilder sb = new StringBuilder();
String msg = this.layout.format(event);
sb.append(msg);

if (layout.ignoresThrowable()) {
String[] s = event.getThrowableStrRep();
if (s != null) {
int len = s.length;
for (int i = 0; i < len; i++) {
sb.append(s[i]);
sb.append(Layout.LINE_SEP);
}
}
}
return sb.toString();


}

/**
* Derived appenders should override this method if option structure
* requires it.
*/
public void activateOptions() {
init();
}


public void close() {
if (closed)
return;

if (!dataSocket.isClosed()) {
dataSocket.close();
}
closed = true;
}


public boolean requiresLayout() {
return true;
}

/**
* Returns value of the RemoteHost option.
*/
public String getRemoteHost() {
return remoteHost;
}

/**
* The RemoteHost option takes a string value which should be the
* host name of the server where a {@link String} is running.
*/
public void setRemoteHost(String host) {
String val = host.trim();
remoteHost = val;
}

/**
* Returns value of the Port option.
*/
public int getPort() {
return port;
}

/**
* The Port option takes a positive integer representing the port
* where the server is waiting for connections.
*/
public void setPort(int port) {
this.port = port;
}
}
原文地址:https://www.cnblogs.com/zbw911/p/8283602.html