用PrintStream标准输出流写 logger日志文件

用标准输出流写 logger日志文件

package com.javaSe.LogUtil;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Date;


/*
日志工具
*/
public class Logger {
    /*
    记录日志的方法。
     */
    public static void log(String msg){
        try {
            // 指向一个日志文件
            PrintStream out = new PrintStream(new FileOutputStream("log.txt",true));
            // 改变输出方向
            System.setOut(out);
            // 创建日期对象
            Date nowTime = new Date();
            // 格式化日期时间
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
            String strTime = simpleDateFormat.format(nowTime);
            System.out.println(strTime + ": " + msg);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        
    }
}

测试类:

package com.javaSe.LogUtil;


public class LoggerTest01 {
    public static void main(String[] args) {
        // 测试工具类是否好用。
        Logger.log("调用了System.gc()方法,建议启动垃圾回收!");
        Logger.log("调用了UserService的doSome()方法失败,请检查代码是否报错!");
        Logger.log("用户尝试进行登录,认证失败!");
        Logger.log("我非常喜欢这个记录日志的工具哦!");
    }
}
原文地址:https://www.cnblogs.com/xlwu/p/13466164.html