Wednesday, May 16, 2012

log4j: Remote Logging in Java

Remote Logging In Java: Remote Logging in Java: This article will be useful  when you wish to write your logs in an remote server using log4j socketAppender. First you need to visualiz...

Remote Logging in Java

This article will be useful  when you wish to write your logs in an remote server using log4j socketAppender.

First you need to visualize a server and client talking via TCP/IP protocol.
Some basic knowledge in java Socket programing will play a great role.

To try the example you can consider the client and server as your own system.

Step 1:

You can write a server.java class in Eclipse

import org.apache.log4j.net.SimpleSocketServer;

public class Server{

    public static void main(String[] args) { 
        try 
        { 
        String[] arguments = {"1980", "server.xml"}; 
        SimpleSocketServer.main(arguments); 

        } 
        catch (Exception ex) 
        { 
          System.out.println(ex.getMessage());
        } 
}
}


In the above code '1980' is  the port number in which the server will be listening for any clients request. You might use any other port number for listening.

Step 2:

You need to configure the logging details in a xml file or properties file.
I am using a xml named server.xml.

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> 
<appender name="rolling" class="org.apache.log4j.RollingFileAppender"> 
    <layout class="org.apache.log4j.PatternLayout"> 
      <param name="ConversionPattern" value="%5p (%d{DATE}) [%t] (%F:%L) - %m%n"/> 
    </layout> 
    <param name="File" value="C:/RemoteLogs/LogFile.log"/> 
    <param name="MaxFileSize" value="10KB"/> 
    <param name="MaxBackupIndex" value="5"/> 
  </appender> 

  <root>  
    <param name="level" value="INFO"/> 
    <appender-ref ref="rolling" />  
  </root> 
</log4j:configuration>



To experiment further with the layout , MaxFileSize,org.apache.log4j.RollingFileAppender, you can read detailed explanation of log4j xml file  creation by clicking here .

Step 3:





Write the Client.java as below


import java.net.Socket;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Hierarchy;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.net.SocketAppender;
import org.apache.log4j.net.SocketNode;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.xml.DOMConfigurator;

public class Client {

    private static Log logger = LogFactory.getLog(Client.class);
    public static void main(String[] a) {
        // -- Start a new SocketNode

        try {
            DOMConfigurator.configure("client.xml");
            String m_hostName = "localhost";
            String m_port = "1980";
            System.out.println("Accessing socket on host " + m_hostName
                    + " through port " + m_port);
            Socket socket = new Socket(m_hostName,
                    new Integer(m_port).intValue());

            // -- All right so far, now create the SocketNode
            System.out.println("Create the SocketNode listener");
            SocketAppender sa = new SocketAppender("localhost", 1980);
            System.out.println("Activating!");
            sa.activateOptions();
            System.out.println("Attempting to log");
            String logMsg = "Writing log event through SocketAppender instance";
            LoggingEvent le = new LoggingEvent("category",Logger.getRootLogger(),new    Date().getTime(),Level.DEBUG,logMsg,new Throwable());

            System.out.println("Appending!");
            sa.append(le);
            logger.info("Testing!");
           
            new SocketNode(socket, new Hierarchy(Logger.getRootLogger()));
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}






Make sure you give the same port number as given in the server side to listen.

Step 4:
  Create a client configuration file in xml as client.xml as described below.

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  <appender name="async" class="org.apache.log4j.AsyncAppender">
  <appender-ref ref="console" />
  <appender-ref ref="socket" />
  <param name="Blocking" value="false"/>
  <param name="bufferSize" value="256"/>
  </appender>

  <appender name="socket" class="org.apache.log4j.net.SocketAppender">
  <param name="Port" value="1980"/>
  <param name="RemoteHost" value="localhost"/>
  <param name="ReconnectionDelay" value="5000"/>
  <param name="LocationInfo" value="true"/>
  </appender>

  <appender name="console" class="org.apache.log4j.ConsoleAppender"> 
    <param name="Target" value="System.out"/> 
    <layout class="org.apache.log4j.PatternLayout"> 
      <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/> 
    </layout> 
  </appender>

  <logger name="com.test.Client">
  <param name="level" value="INFO"/>
  </logger>

  <root> 
    <param name="level" value="INFO"/>
    <appender-ref ref="async" /> 
  </root>

</log4j:configuration>


You will be needing 2 jars in your java build path 


  1.      Log4j-1.2.16
  2.      Commons-logging-1.1.1
 You can easily download these jars by googling


After adding the jars,

First Run the Server.java as a Java Application and then run the Client.java code.

You can observer that a Folder RemoteLogs will be formed in the C:/ with file LogFile.log containing the logs as output.

You may try this program with 2 systems if you have by using the respective IP instead of 'localhost'.

The logs will be entered in the following format..

 INFO (16 May 2012 16:07:50,781) [main] (SimpleSocketServer.java:60) - Listening on port 1980.......







  Hope this helped you :)