The java.util.logging package includes a handy way to send log message out a port to a server. This is done by replacing the usual log handler with an instance java.util.logging.SocketHandler. The provided SocketHandler, by default, uses java.util.logging.XMLFormatter to create an XML message that will be send out a socket to the host of your choice, and to your own server code.
Suppose you need to do this with an SSL connection, rather than a normal socket?
This is simple to do using a alternate handler which functions similarly to SocketHandler, but creates an SSL connection.
package com.example.logger;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.LogRecord;
import java.util.logging.StreamHandler;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.util.logging.SocketHandler;
public class SSLHandler extends StreamHandler {
private SSLSocket sslSocket;
private String host;
private int port;
private SSLHandler() throws IOException {
}
public SSLHandler(String h, int p) throws IOException {
host = h;
port = p;
connect();
}
private void connect() throws IOException {
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
sslSocket = (SSLSocket) sslsocketfactory.createSocket(host, port);
OutputStream out = sslSocket.getOutputStream();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out);
setOutputStream(bufferedOutputStream);
java.util.logging.Logger.getLogger(getClass().getName()).log(
java.util.logging.Level.INFO,
"connect() completed to [" + host + "] at port " + port);
}
public boolean isLoggable(LogRecord record) {
return true;
}
public synchronized void publish(LogRecord record) {
if (isLoggable(record)) {
super.publish(record);
flush();
}
}
public synchronized void close() throws SecurityException {
super.close();
if (sslSocket != null) {
try {
sslSocket.close();
} catch (IOException e) {
}
}
sslSocket = null;
}
}
The use of this class is the same as using a SocketLogger.
Logger logger = Logger.getLogger(getClass().getName());
Handler handler = new SSLHandler("my_host_name", 3000);
logger.addHandler(handler);
logger.log(Level.INFO, "Hello World");
Logged messages are send as XML fragments to the designated host at port 3000 via SSL. The developer is free to implement any sort of server needed to catch and process these messages.
There's some good information related to remote logging here, including a simple non-SSL logging server example:
http://blogs.sun.com/CoreJavaTechTips/entry/socket_logging
The non-SSL server code is easily altered to open an SSL connection using an instance of SSLServerSocket.