Last active
October 8, 2015 07:18
-
-
Save DavidToca/3297819 to your computer and use it in GitHub Desktop.
Listen log4j socket output endless times (in case of disconnection)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.ServerSocket; | |
import java.net.Socket; | |
import java.io.InputStream; | |
import java.io.ObjectInputStream; | |
import java.io.EOFException; | |
import java.io.IOException; | |
import org.apache.log4j.spi.LoggingEvent; | |
public class SocketLoggerListener { | |
public static void main(String args[]) throws IOException { | |
if (args == null) { | |
System.err.println("ENTER PORT AS ARGUMENT"); | |
return; | |
} | |
int port = -1; | |
try { | |
port = Integer.parseInt(args[0]); | |
if (port < 0) { | |
System.err.println("The port must be positive"); | |
return; | |
} | |
// TODO check | |
} catch (Exception e) { | |
// TODO: handle exception | |
System.err.println("The port must be a number"); | |
return; | |
} | |
while (true) { | |
try { | |
System.out.println("Starting Listen Process at port " + port); | |
final ServerSocket serverSocket = new ServerSocket(port); | |
final Socket socket = serverSocket.accept(); | |
serverSocket.close(); | |
final InputStream is = socket.getInputStream(); | |
final ObjectInputStream ois = new ObjectInputStream(is); | |
while (true) { | |
final Object o; | |
try { | |
o = ois.readObject(); | |
} catch (EOFException eofe) { | |
break; | |
} catch (ClassNotFoundException cnfe) { | |
continue; | |
} | |
if (o instanceof LoggingEvent) { | |
final LoggingEvent logEvent = (LoggingEvent) o; | |
processEvent(logEvent); | |
} | |
} | |
ois.close(); | |
socket.close(); | |
} catch (Exception e) { | |
// TODO: handle exception | |
e.printStackTrace(); | |
} | |
} | |
} | |
public static void processEvent(LoggingEvent logEvent) { | |
System.out.print("[" + logEvent.getLevel() + "] "); | |
System.out.println(logEvent.getMessage()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment