自己写的简易版Java日志类分享
/**
*
*/
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();
}
}
}
}热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短