1. 程式人生 > >java 輸出日誌到指定檔案中

java 輸出日誌到指定檔案中

1.在我們專案開發中經常要將專案的異常日誌輸出到制定看路徑的檔案中 ,下面用java 實現日誌輸出功能 。直接上程式碼如下 所示:
/**
 * 
 * @author Administrator 控制檯日誌輸出到 檔案中去
 *
 */

public class Testprint {

  /**
   * 
   * @param args   main  方法測試
   * @throws IOException
   */

public static void main(String[] args) throws IOException {

String content = null;
        String url = "e:/exception.txt";
        try {
            List<String> list = new ArrayList<>();
            list.add("1");
            list.add("2");
            list.add("3");
            for (String string : list) {
                System.out.println(string);

            }
            while (true) {
                String j = list.get(3);

            }

        } catch (Exception e) {

            content = e.getClass().getName() + "error  info " + e.getMessage();
        }

        Testprint testprint = new Testprint();

        testprint.setEception(url, content);
 

}

  /**
   * 
   * 
   * @param url     指定檔案的位置
   * @param content    異常輸出的內容 
   * @throws IOException
   */

private void setEception(String url, String content) throws IOException {
        File file = new File(url);
        FileWriter fw = null;
        if (!file.exists()) {

            file.createNewFile();
        }
        String writeDate = "當前時間:" + this.getTime() + "-------" + "error"
                + content;
        try {
            fw = new FileWriter(file, true);
            fw.write(writeDate + "\r\n");

        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            if (fw != null) {
                fw.close();

            }
        }

    }

/**
    *  @description    輸出當前時間
    * @return
    */
    private String getTime() {

        Calendar cal = Calendar.getInstance();
        int day = 0;
        int month = 0;
        int year = 0;
        year = cal.get(Calendar.YEAR);
        month = cal.get(Calendar.MONTH) + 1;
        day = cal.get(Calendar.DAY_OF_MONTH);
        String nowDate = String.valueOf(year) + "-" + String.valueOf(month)
                + "-" + String.valueOf(day);
        return nowDate;
    }

2.執行的結果 如下所示

1
2
3
異常輸出 到控制檯 :  Index: 3, Size: 3;

}