Created
December 14, 2021 00:05
-
-
Save xranby/36056eac79aa8ff5753b261b1211ae24 to your computer and use it in GitHub Desktop.
Log.java Productive Java logging measure the time in ms between two calls to System.out.println This allow simple java code to be benchmarked.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Productive Java logging | |
measure the time in ms | |
between two calls to System.out.println | |
This allow simple java code to be benchmarked. | |
Have a great day! | |
- Xerxes Rånby | |
2021 12 14 | |
$ java Log.java | |
[ 0] Hello World | |
[ 12] Hello World | |
*/ | |
import java.io.IOException; | |
import java.io.OutputStream; | |
import java.io.PrintStream; | |
public class Log extends OutputStream { | |
public static void main(String[] args) { | |
System.setOut(new PrintStream(new Log())); | |
System.out.println("Hello World"); | |
System.out.println("Hello World"); | |
} | |
private final long t0 = System.currentTimeMillis(); | |
private volatile long oldTime; | |
private final PrintStream err; | |
private Log() { | |
this.err = System.err; | |
oldTime = System.currentTimeMillis(); | |
} | |
@Override | |
public void write(byte[] b) { | |
err.print(b); | |
} | |
@Override | |
public void write(byte[] b, int off, int len) { | |
String s = new String(b).substring(off, len); | |
if(s.equals("\n")){ | |
err.print(s); | |
return; | |
} | |
print(s); | |
} | |
@Override | |
public void write(int i) throws IOException { | |
err.write(i); | |
} | |
public void print(final String message) { | |
err.printf("[%,9d] %s", getStartupDiff(), message); | |
} | |
public long getStartupDiff() { | |
final long time = System.currentTimeMillis(); | |
oldTime = time; | |
return time - t0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment