java日志实现工具_使用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[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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值