Monday, September 8, 2014

JAVA CODE TO WRITE LOGS IN PARTICULAR FILE

package filer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
/*
 * Author : Raj Kirpalsinh
 * */
class Base{

private String path = null;

Base(String path){
this.path = path;
}

public boolean setStandardLogOutput() {

if(path == null) {
System.out.println("Sorry !! Path is null");
return false;
}

File stdLogDirPath = new File(path);

if(stdLogDirPath.exists()==false) {
System.out.println("Directory path "+path+ " does not exist. Creating the directory path.");
if(stdLogDirPath.mkdirs() == false) {
System.out.println("Could not create directory path : "+path);
return false;
}else {
System.out.println("Directory path created successfully : "+path);
}
}

if(stdLogDirPath.isDirectory()==false) {
System.out.println(path +" is not a directory");
return false;
}

File logFile = new File(path, "EngineLogs.log");
if(logFile.exists()==false) {
System.out.println("Log file "+logFile.getName()+ " does not exist");
boolean isFileCreated = false;
try {
isFileCreated = logFile.createNewFile();
if(isFileCreated == true) {
System.out.println("Log file "+logFile.getName()+ " created at path : "+path);
FileOutputStream fs = new FileOutputStream(logFile,true);
PrintStream ps = new PrintStream(fs);
System.setOut(ps);
System.setErr(ps);
}else {
System.out.println("Error while creating file  ");
}
} catch (IOException e) {
System.out.println("Exception while creating the logfile. Reason: "+e.getMessage());
e.printStackTrace();
return false;
}
}
return true;
}
}

public class Engine extends Base {

Engine(String path){
super(path);
}

public static void main(String[] args) {
String ENGINE_HOME = System.getenv("ENGINE_HOME");
System.out.println(ENGINE_HOME);
Engine engine = new Engine(ENGINE_HOME);
boolean flag = engine.setStandardLogOutput();
if(flag == false) {
System.out.println("Error while setting the Eninge stardard logs output in a EngineLogs.log file");
}
System.out.println("--Begin--");
System.out.println("--Finish--");
}

}

No comments:

Post a Comment