Using a java.util.logging SocketHandler

This example creates a SocketHandler that writes log messages to localhost:5667. The second example, the server, listens to this port and prints out whatever it gets. Notice that the default formatter for SocketHandler is XMLFormatter.

Main.java:

import java.util.logging.*;
import java.io.*;
 
public class Main
{
   public static void main(String argv[]) throws IOException {
      Logger logger = Logger.getLogger("main");
      logger.setUseParentHandlers(false);
      logger.setLevel(Level.ALL);
 
      SocketHandler sh = new SocketHandler("127.0.0.1", 5667);
      sh.setLevel(Level.ALL);
      logger.addHandler(sh);
 
      logger.severe("log message #1");
      logger.warning("log message #2");
      logger.info("log message #3");
      logger.config("log message #4");
      logger.fine("log message #5");
   }
}

LogServer.java:

import java.util.*;
import java.net.*;
import java.io.*;
 
public class LogServer {
   public static void main(String args[]) {
      LogServerThread es = new LogServerThread();
      es.start();
   }
}
 
class LogServerThread extends Thread {
   private ServerSocket ss;
   private Socket clientSock;
   private final int port = 5667;
 
   public void run() {
      try {
         ss = new ServerSocket(port);
         System.out.println("Listening to log messages...");
         clientSock = ss.accept();
         BufferedReader br = new BufferedReader(
                               new InputStreamReader(clientSock.getInputStream()));
         String line;
         while ((line = br.readLine()) != null) {
            System.out.println(line);
         }
      } 
      catch(IOException e) {
         e.printStackTrace();
         return;
      }
      finally {
         try {
            System.out.println("Closing serversocket...");
            ss.close();
         }
         catch(IOException e) {
         }
      }
   }
}