寫日誌檔案的程式碼
阿新 • • 發佈:2019-01-25
直接上程式碼:
package com.inspur.log; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.Calendar; public class WriteLog { private static WriteLog instance = null; private WriteLog(){}; public static WriteLog getInstance() { if( instance == null ) { instance = new WriteLog(); } return instance; } public void logger(String fileNameHead,String logString) { try { String logFilePathName=null; Calendar cd = Calendar.getInstance();//日誌檔案時間 int year=cd.get(Calendar.YEAR); String month=addZero(cd.get(Calendar.MONTH)+1); String day=addZero(cd.get(Calendar.DAY_OF_MONTH)); String hour=addZero(cd.get(Calendar.HOUR_OF_DAY)); String min=addZero(cd.get(Calendar.MINUTE)); String sec=addZero(cd.get(Calendar.SECOND)); File fileParentDir=new File("./log");<span style="font-family: Arial, Helvetica, sans-serif;">//判斷log目錄是否存在 </span> if (!fileParentDir.exists()) { fileParentDir.mkdir(); } if (fileNameHead==null||fileNameHead.equals("")) { logFilePathName="./log/"+year+month+day+hour+".log";//日誌檔名 }else { logFilePathName="./log/"+fileNameHead+year+month+day+hour+".log";//日誌檔名 } PrintWriter printWriter=new PrintWriter(new FileOutputStream(logFilePathName, true)); String time="["+year+month+day+"-"+hour+":"+min+":"+sec+"] "; printWriter.println(time+logString); printWriter.flush(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.getMessage(); } } /**整數小於10前面補0 * @param i * @return */ public static String addZero(int i) { if (i<10) { String tmpString="0"+i; return tmpString; } else { return String.valueOf(i); } } public static void main(String[] args) { // TODO Auto-generated method stub WriteLog log = null; log.getInstance().logger("test", "hello world, t02,test"); } }