当一个项目在长久运行,log日志在控制台看的并不方便。
我们可以将一些我们需要的东西打印出来,存储到一个log日志当中。
于是诞生了这个小demo
demo中可以每天在指定目录生成一个log日志。当然这里只是给出一个思路,你可以根据你的需要去更改这些代码。如果想要专业点的日志打印,还是推荐使用log4j插件。
package com.againfly.log; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; public class LogOutPut { private volatile static LogOutPut instance = null; private String logPath = "C://log//"; private static SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); private static SimpleDateFormat logFormat = new SimpleDateFormat("yyyy_MM_dd"); private File log = null; private PrintWriter out = null; private String logFileName = null; private LogOutPut(){ createLogFile(); } public void outLog(String msg){ createLogFile(); out.print(timeFormat.format(new Date()) + " ----> " + msg); } public static LogOutPut getInstance(){ if(null == instance){ synchronized (LogOutPut.class) { if(null == instance){ instance = new LogOutPut(); } } } return instance; } private void createLogFile(){ String genLogFileName = logFormat.format(new Date()); if(genLogFileName.equals(logFileName)){ return; } File dir = new File(logPath); if(!dir.exists()) dir.mkdirs(); logFileName = genLogFileName; log = new File(logPath + logFileName + ".log"); try{ if(!log.exists()) log.createNewFile(); if(out != null) out.close(); out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(log, true), "UTF-8"), true); }catch(IOException e){ e.printStackTrace(); } } }
最新评论