LogUtil 代码:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 记录系统日志
*/
public class LogUtil {
public static void log(String msg){
try {
// 指向日志文件
PrintStream ps = new PrintStream(new FileOutputStream("log_file.txt",true));
// 改变输出方向
System.setOut(ps);
// 获取系统当前时间
Date nowTime = new Date();
// 日期格式化
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
String strTime = sdf.format(nowTime);
System.out.println(strTime + ":" + msg);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
测试类:
public class LogTest {
public static void main(String[] args) {
LogUtil.log("张三注册");
LogUtil.log("输入密码格式不合法");
LogUtil.log("注册成功");
LogUtil.log("购买商品中...");
}
}
运行结果:
在
log_file
文件中看到以下结果:
2020-04-12 16:54:26 164:张三注册
2020-04-12 16:54:26 207:输入密码格式不合法
2020-04-12 16:54:26 208:注册成功
2020-04-12 16:54:26 208:购买商品中...
原文:https://www.cnblogs.com/yerun/p/12686238.html