记录系统日志

时间:2020-04-12
本文章向大家介绍记录系统日志,主要包括记录系统日志使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

记录系统日志

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