读书人

容易的日志类

发布时间: 2012-11-05 09:35:12 作者: rapoo

简单的日志类
public class LogFile {
private final static String DEFAULT_LOG_NAME = "import";
private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static File file = null;
private String className = null;

public LogFile(){
}

public LogFile(Class clas){
className = clas.getName();
}


/**
* 输出info日志到import.log文件
*
* @param logInfo
*/
public void writeInfo(String logInfo) {
String msg = format.format(new Date()) + " " + " -- INFO -- " + logInfo + ".";

FileOutputStream fos;
try {
fos = new FileOutputStream(file.getAbsolutePath(),true);
OutputStreamWriter dis=new OutputStreamWriter(fos);
BufferedWriter bWriter = new BufferedWriter(dis);
bWriter.write(msg);
bWriter.newLine();
bWriter.flush();
bWriter.close();
} catch (IOException e) {
e.printStackTrace();
}

}

public void writeError(String logInfo) {
String msg = format.format(new Date()) + " " + " -- ERROR -- " + "Failure:" + logInfo + "!";

FileOutputStream fos;
try {
fos = new FileOutputStream(file.getAbsolutePath(),true);
OutputStreamWriter dis=new OutputStreamWriter(fos);
BufferedWriter bWriter = new BufferedWriter(dis);
bWriter.write(msg);
bWriter.newLine();
bWriter.flush();
//throwable.printStackTrace(new PrintWriter(new FileWriter(file,true),true));
bWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void createLogFile(String basePath) {
File path = new File(basePath);
if (!path.exists()) {
path.mkdir();
}

file = new File(path + "/" + DEFAULT_LOG_NAME + ".log");
if (file.exists()) {
file.delete();
}

try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}

public static boolean isExist(){
if(file.exists()){
return true;
}else {
return false;
}
}

public static void deleteLogFile(){
if (file.exists()) {
file.delete();
}
}

//public static void main(String[] args) {
// LogFile log = new LogFile();
// String str = null;
// log.createLogFile();
// new LogFile(ImportFromFileAction.class).writeInfo("开始导入文件...");
//
// try {
//throw new NullPointerException();
//} catch (NullPointerException e) {
//new LogFile(ImportFromFileAction.class).writeError("用户编号 不能为空!");
//}
//}
}

读书人网 >编程

热点推荐