I was writing a basic server program when I used System.out.println
to print out my log messages. I wrote a basic class file that uses that to write out to log. If I were to write the following:
System.out.println("Hello, world!");
System.out.println("Goodbye, world");
The desired output would be:
Log message - Hello, world!
Log message - Goodbye, world!
What ends up happening doesn't match the desired output. Instead, it outputs to the following.
Log message - Hello, world!
Goodbye, world!
The code for the main method:
public static void main(String[] args){
LogManager.start();
System.out.println("Hello, world!");
System.out.println("Goodbye, world!");
LogManager.stop();
}
The class LogManager switches the default PrintStream
that is printed out to, and keeps a copy of the old one to print out log messages. However, "Log message - " isn't always being prefixed. Although, when sleeping for 2000ms between each println
call, the output looks like the following.
Log message - Hello, world!
Log message - Goodbye, world!Log message -
The code for LogManager is as follows.
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
public class LogManager implements Runnable{
private final PrintStream ps;
private final OutputStream out;
private static boolean cont = true;
public static void start(){
OutputStream stdout = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(stdout);
Thread th = new Thread(new LogManager(System.out, stdout));
System.setOut(ps);
th.start();
}
public static void stop(){
cont = false;
}
public LogManager(PrintStream std, OutputStream out){
this.ps = std;
this.out = out;
}
@Override
public void run() {
ByteArrayOutputStream baos = (ByteArrayOutputStream) out;
while(true){
if(!cont) return;
byte[] bytes = baos.toByteArray();
if(bytes.length > 0){
baos.reset();
ps.print("Log message - " + new String(bytes));
}
}
}
}
Could someone please point me to what I'm doing wrong, help would greatly be appreciated. I would like to stay away from libraries, as I would like to keep my JAR size to a minimum, with no additional packages having to be included, although mostly for knowing I didn't use anyone else's library to achieve what I am doing.