Tuesday, September 23, 2014

Java code to Create log file and write logs in it

It s very simple code just set Environment Variable and run the program. It will create the log file and will write the outputs into the EngineLogs.log 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--");
}

}

Keep visiting :) 

No comments:

Post a Comment

Scrum and Scrum master

Scrum  Scrum is a framework which helps a team to work together.  It is like a rugby team (the scrum name comes from rugby game). Scrum enco...