Thursday 15 December 2016

How to write log to a file?

        An application log need to be persisted so that we can analyzed the log when an error occured in our application. For this reason we need to write to log into a file.

     The Logging API provide handlers which helps us to do this. To write log to a file we can use theFileHandler.

          We define the name of our log file and the appendable mode in this class constructor. For example you can look at the code presented below.


import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.io.IOException;

public class WriteLogToFile {
    public static void main(String[] args) throws IOException {
        Logger logger = Logger.getLogger(WriteLogToFile.class.getName());

        //
        // Create an instance of FileHandler that write log to a file called
        // app.log. Each new message will be appended at the at of the log file.
        //
        FileHandler fileHandler = new FileHandler("app.log", true);        
        logger.addHandler(fileHandler);

        if (logger.isLoggable(Level.INFO)) {
            logger.info("Information message");
        }

        if (logger.isLoggable(Level.WARNING)) {
            logger.warning("Warning message");
        }

    }
}


Ouput:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
<record>
  <date>2016-12-15T17:42:44</date>
  <millis>1481803964123</millis>
  <sequence>0</sequence>
  <logger>WriteLogToFile</logger>
  <level>INFO</level>
  <class>WriteLogToFile</class>
  <method>main</method>
  <thread>15</thread>
  <message>Information message</message>
</record>
<record>
  <date>2016-12-15T17:42:44</date>
  <millis>1481803964132</millis>
  <sequence>1</sequence>
  <logger>WriteLogToFile</logger>
  <level>WARNING</level>
  <class>WriteLogToFile</class>
  <method>main</method>
  <thread>15</thread>
  <message>Warning message</message>
</record>

No comments:

Post a Comment