使用java实现日志工具类分享
package com.teligen.eos.telecode;
import java.io.file;
import java.io.filewriter;
import java.io.ioexception;
import java.util.date;
/**
* 书写日志信息到指定的文件中
*/
public class writelogutil {
private static string rootpath = "d:\\logs\\";
/**
* 将信息写到文件中
* @param msg
*/
public static void writemsgtofile(string msg) {
//删除之前的文件
deloldfile();
filewriter filewriter = null;
try {
filewriter = new filewriter(getfilename(),true);
date today = new date();
string time = string.valueof(today.gethours()) + ":" + string.valueof(today.getminutes()) + " " + string.valueof(today.getseconds());
filewriter.write("#" + time + "# [" + msg + "]" + "\r\n");
filewriter.flush();
} catch (ioexception e) {
system.out.println("### 写日志到文件异常 ### >>> " + e.getmessage());
e.printstacktrace();
} finally {
try {
filewriter.close();
} catch (ioexception e) {
system.out.println("### 关闭写日志的流异常 ### >>> " + e.getmessage());
e.printstacktrace();
}
}
}
/**
* 删除之前的日志文件
*/
private static void deloldfile() {
date today = new date();
int month = today.getmonth()+1;
month = month - 2;
if(month == -1) month = 11;
if(month == 0) month = 12;
string delpath = rootpath + string.valueof(month) + "\\";
file folder = new file(delpath);
if(folder.exists()) {
file[] files = folder.listfiles();
for(int i=0; i<files.length; i++) {
files[i].delete();
}
}
}
/**
* 获取要保存的文件
* @return filename
*/
private static string getfilename() {
date today = new date();
string filename = string.valueof((today.getyear()+1900)) + string.valueof((today.getmonth()+1)) + string.valueof(today.getdate()) + ".log";
//创建目录
file folder = new file(rootpath + string.valueof((today.getmonth()+1)) + "\\");
if(!folder.exists()) {
folder.mkdirs();
}
//创建文件
file file = new file(filename);
if(!file.exists()) {
try {
file.createnewfile();
} catch (ioexception e) {
system.out.println("### 新建日志文件异常 ### >>> " + e.getmessage());
e.printstacktrace();
}
}
filename = rootpath + string.valueof((today.getmonth()+1)) + "\\" + filename;
return filename;
}
/**
* 测试使用的main方法
*/
public static void main(string[] args) {
//getfilename();
string teststring = "写日志咯:71fabb7890d2cc0d267fbd84f409618c0303bc597b9244c324947bde4b1c0b4cb08c33fc461f7badd088535dae42d8d7d06f4134e442d9d1ce3a0f9b3edd64337a2d18ce34fcdc137b7cbd84f409618c03038feaec79f79c2f58bd84f409618c03038feaec79f79c2f58bd84f409618c03038feaec79f79c2f581790acb3c178641d14d8c09905bc52cf1c8249b12f2ede5ac3c8faf2fd8a686e";
writemsgtofile(teststring);
//deloldfile();
}
}
上一篇: SpringBoot整合JPA的实例代码