自动在"System.out.println()"语句中显示日期 [英] Show date in 'System.out.println()' statement automatically

查看:177
本文介绍了自动在"System.out.println()"语句中显示日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道您打印的每一行都有可能用日期标记(也可以另存为日志文件).

I know that it is possible that every line you print can be tagged with date (and also saved as a log file).

例如在《我的世界》中:

For example in Minecraft:

[16:21:43 INFO]: Minecraft Launcher 1.3.9 (through bootstrap 5) started on windows...

我该怎么做? Maybee和Logger?还是需要外部库?

How do I do that? Maybee with Logger? Or are external librarys required?

推荐答案

可以通过调用System.out.println

  1. 创建您的自定义PrintStream
  2. 覆盖println方法以为字符串加上日期前缀
  3. 使用自定义PrintStream
  4. 设置System.setOut
  1. Create your custom PrintStream class
  2. Override println method to prefix the String with the date
  3. Set System.setOut with your custom PrintStream

自定义流:

public class MyPrintStream extends PrintStream {

    public MyPrintStream(OutputStream out) {
        super(out);
    }

    @Override
    public void println(String string) {
        Date date = new Date();
        super.println("[" + date.toString() + "] " + string);
    }
}

测试类别:

 public static void main(String[] args) {
            System.setOut(new MyPrintStream(System.out));
            System.out.println("Hello World!");
                System.out.println("Yellow World!");
        }

输出:

[Mon Feb 10 21:10:14 IST 2014] Hello World!
[Mon Feb 10 21:10:14 IST 2014] Yellow World!

这篇关于自动在"System.out.println()"语句中显示日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆