How to Create a Log File in Java

Today, I will teach you how to create a log file in java. We all know that a file is a list actions that occurred in which a program records events, such as user access or data manipulation as they occur to serve as an audit trail or warning message. So, now let's start this tutorial! 1. Open JCreator or NetBeans and make a java program with a file name of logFile.java. 2. Import java.io package. Hence we will use an input/output in creating files and for the IOException class. Also, import java.util.logging package because we will use also logging class of utilities as it have FileHandler and Logger method.
  1. import java.util.logging.*;
  2. import java.io.*;
3. In your main, initialize log as a variable of Logger method to get the logger of our class file logfile.class.
  1. Logger log = Logger.getLogger(logFile.class.getName());
Now, create an instance of FileHandler that write log to a file called data.log. Each new message will be appended at the log file.
  1.  FileHandler fileHandler = new FileHandler("data.log", true);        
  2.  log.addHandler(fileHandler);
Create an If Statement to write data to our log files for the warning and information message. This will serve as the content of our data.log.
  1.  if (log.isLoggable(Level.INFO)) {
  2.             log.info("This is an information message.");
  3.         }
  4.  
  5.         if (log.isLoggable(Level.WARNING)) {
  6.             log.warning("This is a warning message.");
  7.         }
After that, run the program. It will create files named data.log and data.log.lck. Output: output Best Regards, Engr. Lyndon Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Add new comment