Bootstrap FreeKB - Java - Append events to a custom log file
Java - Append events to a custom log file

Updated:   |  Java articles

There are various ways to go about append events to a custom log file in Java.

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 Buy Me A Coffee



Comments


Add a Comment


Please enter 2f5024 in the box below so that we can be sure you are a human.