每个项目都要求打log,我也编写了一个适合我现在的机能的log类,它能够每天,针对每一个线程创建一个文件并在里边填写log文字。感觉还有可以提高的地方,比如,log级别debug和运行实现不同的log,好像要用到log4j的什么东西,我没深研究,但是,控制台程序也没那么多配置。至于功能上,我觉得还有可以实现的功能,比如不跨行的单行打印,还有针对类名的多信息打印。
打出来的log类似:
[11:04:31]: system property:mail.smtp.host = lzt-server01
[11:04:31]: prepare to read mail body object
[11:04:31]: create mime mail body!
[11:04:31]: config smtp auth:mail.smtp.auth = true
[11:04:31]: config mail subject
[11:04:31]: set fromer!
[11:04:31]: config mail header :X-IFArea
[11:04:31]: sending mail....
[11:04:31]: sending mail succeed!
源程序如下:
/* * Logger.java * * Created on 2008.7.10, pm2:01 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package mail; import com.sun.org.apache.bcel.internal.generic.CALOAD; import java.io.*; import java.util.Date; import java.util.Calendar; import java.text.SimpleDateFormat; /** * * @author user */ public class Logger { /** Creates a new instance of Logger */ public Logger() { } public static void println(String log){ print(log,true); } public static void println(){ print("",true); } public static void print(String log){ print(log,false); } public static void print(String log, boolean newLine){ try{ //add time to the log log = getSysSecondInString() + log; //make log file File directory = new File(""); String pathStr = directory.getAbsolutePath(); File folder = new File(CONSTANT.logAddress); folder.mkdir(); String fileName = CONSTANT.logPrefix + Thread.currentThread().getName() + "_" + getSystimeInString(); FileWriter writeFile = new FileWriter(pathStr + "//" + CONSTANT.logAddress + "//" + fileName + CONSTANT.logFileType ,true); //write log PrintWriter bw = new PrintWriter(writeFile); if(newLine){ System.out.println("["+Thread.currentThread().getName() + "]" + log); bw.write("/r/n"+log); }else{ System.out.print(log); bw.write(log); } bw.close(); writeFile.close(); }catch(FileNotFoundException ex){ ex.printStackTrace(); }catch(IOException ex){ ex.printStackTrace(); } } private static String getSysSecondInString(){ Calendar calendar = Calendar.getInstance(); SimpleDateFormat format=new SimpleDateFormat("[hh:mm:ss]:/t"); String nowtime=format.format(calendar.getTime()); return nowtime; } private static String getSystimeInString(){ Calendar calendar = Calendar.getInstance(); SimpleDateFormat format=new SimpleDateFormat("yyyy.MM.dd"); String nowtime=format.format(calendar.getTime()); return nowtime; } }