自己写的简易版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 托班调皮祝福语简短