Java - Append events to a custom log file

by
Jeremy Canfield |
Updated: February 22 2023
| Java articles
There are various ways to go about append events to a custom log file in Java.
- Using BufferedOutputStream and FileOutputStream (this article)
- Using Log4j
- Using java.util.logging
Here is an example of how to log standard out (STDOUT) and standard error (STDERR) to a file in Java.
import java.io.IOException;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class Main {
public static void main(String[] args) {
String logfile = "C:\\Users\\john.doe\\my.log";
System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(logfile))));
System.setErr(new PrintStream(new BufferedOutputStream(new FileOutputStream(logfile))));
Logger logger = Logger.getLogger("mylogger");
FileHandler fh = new FileHandler("C:\\Users\\john.doe\\logger.log");
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
logger.info("testing");
}
}
Or like this.
import java.io.IOException;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class Main {
public static void main(String[] args) {
String logfile = "C:\\Users\\john.doe\\my.log";
System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(logfile))));
System.setErr(new PrintStream(new BufferedOutputStream(new FileOutputStream(logfile))));
Logger logger = Logger.getLogger("mylogger");
FileHandler fh;
try {
fh = new FileHandler("C:\\Users\\john.doe\\logger.log");
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
logger.info("inner");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("outer");
}
}
Did you find this article helpful?
If so, consider buying me a coffee over at