Skip to content

Instantly share code, notes, and snippets.

@xranby
Created December 14, 2021 00:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xranby/36056eac79aa8ff5753b261b1211ae24 to your computer and use it in GitHub Desktop.
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.
/*
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