How to Create a Log File in Java
Submitted by donbermoy on Friday, May 23, 2014 - 12:11.
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.
3. In your main, initialize log as a variable of Logger method to get the logger of our class file logfile.class.
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.
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.
After that, run the program. It will create files named data.log and data.log.lck.
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
- import java.util.logging.*;
- import java.io.*;
- Logger log = Logger.getLogger(logFile.class.getName());
- FileHandler fileHandler = new FileHandler("data.log", true);
- log.addHandler(fileHandler);
- if (log.isLoggable(Level.INFO)) {
- log.info("This is an information message.");
- }
- if (log.isLoggable(Level.WARNING)) {
- log.warning("This is a warning message.");
- }
Add new comment
- 1789 views