gpt4 book ai didi

java - 自动在 'System.out.println()' 语句中显示日期

转载 作者:搜寻专家 更新时间:2023-11-01 01:12:57 25 4
gpt4 key购买 nike

我知道你打印的每一行都可以用日期标记(也可以保存为日志文件)。

例如在我的世界中:

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

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

最佳答案

可以通过调用 System.out.println

显示字符串中的日期前缀
  1. 创建您的自定义 PrintStream
  2. 覆盖 println 方法以在字符串前加上日期
  3. 使用您的自定义 PrintStream 设置 System.setOut

自定义流:

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!

关于java - 自动在 'System.out.println()' 语句中显示日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21681066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com