Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show date in 'System.out.println()' statement automatically

Tags:

java

minecraft

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...

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

like image 669
Ercksen Avatar asked Dec 02 '22 20:12

Ercksen


1 Answers

It's possible to show dates prefixed in your String by calling System.out.println

  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

Custom stream:

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!
like image 76
StoopidDonut Avatar answered Dec 24 '22 00:12

StoopidDonut