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);
 

扫描二维码关注公众号,回复: 4264610 查看本文章

}

  /**
   * 
   * 
   * @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;

}

猜你喜欢

转载自blog.csdn.net/qq_38097573/article/details/83478630