Personal Log

開發過程中經常會遇到需要記錄log的時候,目的是調試數據。可以通過IDE的配置記錄log的數據文件路徑,但是本人感覺那樣比較麻煩,因爲那樣可能會記錄很多自己不想要的log日誌,於是自己寫了一個 PersonalLog.java 來輸出自己想要的log內容。

需要注意的是,在提交代碼的時候,務必刪除個人寫的代碼測試片段。

代碼片段如下:

package com.zmz;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PersonalLog {

    public static void main(String[] args) {
        testLog("Only For Test!");
    }

    public static void testLog(Object logCon){
        String logContent = logCon+"";
        String logPath="D:\\temp_log\\";
        String path01=( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ).format(new Date(System.currentTimeMillis()));
        String path02=( new SimpleDateFormat("HH時mm分") ).format(new Date(System.currentTimeMillis()));
        String path03=( new SimpleDateFormat("HH時") ).format(new Date(System.currentTimeMillis()));
        String path04=( new Date() ).getTime() +"";

        DateFormat format2 = new java.text.SimpleDateFormat("yyyyMMdd");
        String dateStr =  format2.format(new Date());
        String logFullPath= logPath + dateStr+".log";

        // 編輯要寫入的內容
        String temp="";
        if(logContent==null) temp="logContent is null";
        else temp=logContent;

        FileWriter writer;
        try {
            // 如果沒有文件夾,創建文件夾
            File folder = new File(logPath);
            if(!folder.exists()){
                folder.mkdirs();
            }
            // 創建txt文件,如果沒有,自動創建,如果有,不覆蓋
            File file = new File(logFullPath);
            if(file.isFile() && file.exists()){
                //System.out.println("文件存在");
            }else{
                file.createNewFile();
            }

            BufferedWriter bufw =  new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logFullPath, true), "UTF-8"));

            bufw.write(path01+" : "+temp);
            bufw.newLine();

            bufw.flush();
            bufw.close();

        } catch (Exception e) {
        }finally{
//            System.err.println(path01);
            readTxtFile(logFullPath);
        }
    }

    public static void readTxtFile(String filePath){
        try {
            String encoding="UTF-8";
            File file=new File(filePath);
            if(file.isFile() && file.exists()){ //判斷文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file),encoding);//考慮到編碼格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while((lineTxt = bufferedReader.readLine()) != null){
                    System.out.println(lineTxt);
                }
                read.close();
            }else{
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("讀取文件內容出錯");
            e.printStackTrace();
        }
    }



}

執行main方法,會發現有如下內容生成:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章