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方法,会发现有如下内容生成:

 

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