Java – automatically in ‘system out. Display date in println() ‘statement

I know that every line you print can be marked with a date (and saved as a log file)

For example, in minecraft:

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

What do I do? Maybe with logger? Or is there a need for an external library?

Solution

You can call system out. Println displays the date of the prefix in the string

>Create a custom printstream class > override println method, add date prefix to string > set system with custom printstream setOut

Custom flow:

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);
    }
}

Test class:

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

Output:

[Mon Feb 10 21:10:14 IST 2014] Hello World!
[Mon Feb 10 21:10:14 IST 2014] Yellow World!
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>