/**
*
*/
importjava.io.File;
importjava.io.FileWriter;
importjava.io.IOException;
importjava.text.SimpleDateFormat;
importjava.util.Date;
/**
*@authormagic282
*
*/
publicclassLogger{
privatestaticStringlogFilePath;
privatestaticbooleanisInitialized=false;
privatestaticFileWriterlogWriter=null;
privatestaticbooleanprintLogWhenLog=true;
privatestaticbooleanInitLogger(){
StringlogDirectoryPath=System.getProperty("user.dir")
+java.io.File.separatorChar+"log";
if(!newFile(logDirectoryPath).exists()){
newFile(logDirectoryPath).mkdir();
}
DatelogfileDate=newDate();
SimpleDateFormatdateFormat=newSimpleDateFormat(
"yyyy-MM-dd-HH-mm-ss");
logFilePath=logDirectoryPath+java.io.File.separatorChar
+dateFormat.format(logfileDate)+".log";
try{
logWriter=newFileWriter(logFilePath,true);
isInitialized=true;
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
System.err.println("Unabletocreatelogfile.");
System.err.println("Initilizationfail.");
e.printStackTrace();
returnfalse;
}
returntrue;
}
publicstaticvoidLog(Stringmessage){
if(!isInitialized){
InitLogger();
}
DatelogfileDate=newDate();
SimpleDateFormatdateFormat=newSimpleDateFormat(
"yyyy-MM-dd-HH-mm-ss");
StringcallingClassName=newException().getStackTrace()[1]
.getClassName();
synchronized(logWriter){
Stringlog=String.format("[%s]@[%s]:%s\n",callingClassName,
dateFormat.format(logfileDate),message);
if(printLogWhenLog){
System.out.printf("[log]:%s",log);
}
try{
logWriter.write(log);
logWriter.flush();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
System.err.println("Writelogtofile%serror.");
e.printStackTrace();
}
}
}
publicstaticvoidLog(Exceptionexception){
if(!isInitialized){
InitLogger();
}
DatelogfileDate=newDate();
SimpleDateFormatdateFormat=newSimpleDateFormat(
"yyyy-MM-dd-HH-mm-ss");
StringcallingClassName=newException().getStackTrace()[1]
.getClassName();
synchronized(logWriter){
Stringlog=String.format("[%s]@[%s]:%s\n",callingClassName,
dateFormat.format(logfileDate),exception.toString());
if(printLogWhenLog){
System.out.printf("[log]:%s",log);
}
try{
logWriter.write(log);
logWriter.flush();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
System.err.println("Writelogtofile%serror.");
e.printStackTrace();
}
}
}
}