Background: Hello! First of all, please have in mind that I'm fairly new to Java, thus, forgive me if I have something wrong. I have been trying to format my console and save its output to a text file for 2 days now. Here's my code so far:
I'm trying to set the format of the console to
[12/20/2017 23:55:30] program(message here)
and I'm doing it like this:
public class Format {
private static final DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
PrintStream console = new PrintStream(System.out) {
public void println(String x) {
Date date = new Date();
super.println("[" + sdf.format(date) + "] " + "program(" + x + ")");
}
};
Along with this:
public void progStream() throws FileNotFoundException {
System.setOut(console);
System.out.println("This is a test.");
}
Up to here it works just fine and I can see all the system outputs show up on the eclipse's console with the correct format. However, when I try to save it a text file it saves only the message. Without the format.
public void progStream() throws FileNotFoundException {
File log = new File("log" + System.currentTimeMillis() + ".txt");
FileOutputStream fos = new FileOutputStream(log);
PrintStream console = new PrintStream(fos);
System.setOut(console);
System.out.println("This is a test.");
}
I have tried replacing System.out.println("message"); with console.print("message"); but I get the same issue. Unfortunately, I have run out of tutorials and forums to look out and I still can't find a solution to this. Thank you for your help.
Log4j