Sunday, March 27, 2016

Socket Server for Log4jv2 Socket Appender

Log4Jv2 supports different types of appenders. Socket Appender can be used to send log messages to a remote machine where a socket server is running. There are couple of socket server applications available which work with Socket Appenders.
  • SimpleSocketServer - This comes with log4j-1.2.x.x.jar file and you can start like below,
            java -classpath <path>/log4j-1.2.17.jar org.apache.log4j.net.SimpleSocketServer 4712 log4j-server.properties
  • Chainsaw V2 - This is an elegant application with a proper UI.
We had a requirement to integrate the logs to our own monitoring application running in a remote machine. So, had to write our own application. Below code sample elaborates how to read logs and extract all details of the log entry. Please note that this is not a proper server implementation code but just written to elaborate how log event can be taken and information can be extracted from that.
You will have to add below dependancies to your POM file if your application is maven based. Otherwise you can download these from log4j download site and include in your CLASSPATH
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>com.lmax</groupId>
            <artifactId>disruptor</artifactId>
            <version>3.2.0</version>
        </dependency>
package com.directfn.oms.integration.sim;

/**
 * Created by dasunperera on 10/8/15.
 */

import org.apache.logging.log4j.core.async.RingBufferLogEvent;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

class TCPServer {
    public static void main(String argv[]) throws Exception {
        ServerSocket welcomeSocket = new ServerSocket(9500);
        Socket socket = welcomeSocket.accept();
        ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
        while (true) {
            RingBufferLogEvent loggingEvent = (RingBufferLogEvent) inputStream.readObject();
            System.out.println("Logger Name:" +loggingEvent.getLoggerName());
            System.out.println("Level" + loggingEvent.getLevel());
            System.out.println("Message" + loggingEvent.getMessage().getFormattedMessage());
            System.out.println("Thread Name" + loggingEvent.getThreadName());
            System.out.println("Date:Time" + loggingEvent.getTimeMillis()); //Comes in milleseconds and need to convert it to a date
        }
    }
}

No comments: