Saturday, July 9, 2016

Create ping request and logging output as needed

Here i have created a small Java program to make a ping request and log the output from the ping request.

Program does below
1. make "ping" request to list of ips/hosts
2. log total output to a log file =  log4j-application-20160709124113837.log
3. Host name and corresponding Average time = log4j-ping-20160709124113853.csv

I am creating log for each run. for that I am appending time as a suffix for log name.For that I have created a custom file appender "CustomFileAppender.java" and it is being used inside log4j.properties.

1. For ping , I have created  java class "PingStatistics .java"
2. Inside main method I have created a list of hosts/ips. Here I have included three names. google.com,yahoo.com and bing.com
3. for each item in the list, or each host name i create the ping command to execute. eg: let's say we are going to ping google.com, then command is "ping google.com".
"public static String createCommandForPing(String ip)" method is creating the command for each host.
4. we execute the command after creating command.
  the method "public static void executeCommnd(String command, String ip) ".
 Here parameter "ip" is used for logging purposes.
 If i explain execution...
   we need to have a runtime. So we create a runtime in Java
          Runtime r = Runtime.getRuntime();
 Then we execute the command using the runtime. command will execute in seperate process and we can get the return process as below.
          Process p = r.exec(command);

Then we can get the output of the process. we can't directly get a string. We need to get the InputStream and convert to Buffer and get line by line. First we create a "BufferedReader" from the input stream of the process.
         BufferedReader in = new BufferedReader(new InputStreamReader(
p.getInputStream()));

Now e have the Buffer. Now we can read line by line of the output of the process. Or In other words , output of the execution of a ping command.

String inputLine;
while ((inputLine = in.readLine()) != null) {
// System.out.println(inputLine);
log.info(inputLine);
pingResult += inputLine;
}
in.close();

Remember to close the BufferedReader. "in.close(); "



Java code

======================================================================
package com.pingt;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

public class PingStatistics {
static final Logger log = Logger.getLogger(PingStatistics.class);
final static Logger log_pingReport = Logger.getLogger("reportsLogger");

public static String createCommandForPing(String ip) {
String pingCmd = "ping " + ip;

return pingCmd;
}

/**
* ip added for logging purposes.
*
* @param command
* @param ip
*/
public static void executeCommnd(String command, String ip) {
StringBuilder pingDetails = new StringBuilder();
pingDetails.append(ip);
pingDetails.append(",");

String pingResult = "";
try {
Runtime r = Runtime.getRuntime();
Process p = r.exec(command);

BufferedReader in = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
// System.out.println(inputLine);
log.info(inputLine);
pingResult += inputLine;
}
in.close();
System.out.println(pingResult);

String time = pingResult.substring(pingResult.indexOf("Average = "));
pingDetails.append(time);
log_pingReport.info(pingDetails);

} catch (IOException e) {
System.out.println(e);
}
}

public static String printPingDetailsHeader() {
StringBuilder header = new StringBuilder();
header.append("IP/Host Name");
header.append(",");
header.append("Average Time(ms)");

return header.toString();
}

public static void main(String[] args) {

List ipList = new ArrayList();
ipList.add("google.com");
ipList.add("yahoo.com");
ipList.add("bing.com");

log_pingReport.info(printPingDetailsHeader());
for (String ip : ipList) {
String command = createCommandForPing(ip);
executeCommnd(command,ip);
}

}
}

==================================================================

Below code for custom log Appender

==================================================================
package com.log;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.FileAppender;

public class CustomFileAppender extends FileAppender {

@Override
public void setFile(String fileName) {
if (fileName.indexOf("%timestamp") >= 0) {
Date d = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSS");
fileName = fileName.replaceAll("%timestamp", format.format(d));
}
super.setFile(fileName);
}
}

=================================================================

log4j.properties

==================================================================
# Root logger option
log4j.rootLogger=DEBUG, stdout, file

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%m%n

# Redirect log messages to a log file, support file rolling.
log4j.appender.file=com.log.CustomFileAppender
log4j.appender.file.File=C:\\logs\\log4j-application-%timestamp.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%m%n

log4j.category.reportsLogger=DEBUG, reportsLog
log4j.additivity.reportsLogger=false

log4j.appender.reportsLog=com.log.CustomFileAppender
log4j.appender.reportsLog.File=C:\\logs\\log4j-ping-%timestamp.csv
log4j.appender.reportsLog.layout=org.apache.log4j.PatternLayout
log4j.appender.reportsLog.layout.ConversionPattern=%m%n

===================================================================


Output for full log

===========  log4j-application-20160709124113837.log  =======================


Pinging google.com [74.125.200.102] with 32 bytes of data:
Reply from 74.125.200.102: bytes=32 time=49ms TTL=46
Reply from 74.125.200.102: bytes=32 time=49ms TTL=46
Reply from 74.125.200.102: bytes=32 time=49ms TTL=46
Reply from 74.125.200.102: bytes=32 time=49ms TTL=46

Ping statistics for 74.125.200.102:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 49ms, Maximum = 49ms, Average = 49ms

Pinging yahoo.com [98.138.253.109] with 32 bytes of data:
Reply from 98.138.253.109: bytes=32 time=253ms TTL=46
Reply from 98.138.253.109: bytes=32 time=253ms TTL=46
Reply from 98.138.253.109: bytes=32 time=259ms TTL=46
Reply from 98.138.253.109: bytes=32 time=261ms TTL=44

Ping statistics for 98.138.253.109:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 253ms, Maximum = 261ms, Average = 256ms

Pinging bing.com [204.79.197.200] with 32 bytes of data:
Reply from 204.79.197.200: bytes=32 time=49ms TTL=118
Reply from 204.79.197.200: bytes=32 time=49ms TTL=118
Reply from 204.79.197.200: bytes=32 time=49ms TTL=118
Reply from 204.79.197.200: bytes=32 time=48ms TTL=118

Ping statistics for 204.79.197.200:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 48ms, Maximum = 49ms, Average = 48ms


==================================================================

== output for host name/average  log4j-ping-20160709124113853.csv ====================

IP/Host Name,Average Time(ms)
google.com,Average = 49ms
yahoo.com,Average = 256ms
bing.com,Average = 48ms


====================================================================


No comments:

Post a Comment