Skip to content
Related Articles

Related Articles

Improve Article
XMLFormatter in Java Logging API
  • Last Updated : 21 Apr, 2021

In the software development cycle, always it is good to record the set of actions that are getting done. Recording the actions are called Logging. Logging in Java by using java.util.logging package(default) logs the data. Additionally, we have third-party frameworks likeLog4j, Logback, and tinylog, etc., Depends upon the requirements, preferences of selecting logging framework differ. In Java, java.util package is having the logging utility and the following imports are much necessary for logging are as follows:

import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;

Now, let us go through the specification of log message display via a ‘properties file’. Here inside a project, we can specify a properties file, and they keep track of maintaining logging functionality. Among that, “java.util.logging.ConsoleHandler.formatter” specifies the name of a Formatter class to use and the default setting is java.util.logging.SimpleFormatter, which is nothing but displaying log entries in the plain text. Here we are going to cover about XMLFormatter using LogRecord which is shown below as:

LogRecord logRecordInformation = new LogRecord(Level.INFO, “XMLFormatterTest”);

The LogRecord contains the following getter methods: 

getLevel() – It can be Info/Warning etc., (Log level of the message)

All     - 1
FINER   - 3
FINE    - 4
INFO    - 6
OFF     - 9

getMessage() – Here it will display XMLFormatterTest for the example as we have given as

LogRecord logRecordInformation = new LogRecord(Level.INFO, "XMLFormatterTest");

getMillis() – 1616767447995

getSequenceNumber() – 0

We have additional methods that are as follows:

Method Action Performed
getLoggerName()It returns the name of the Logger. 
getParameters()It returns the parameters to be inserted into the message of this LogRecord.
getResourceBundle()Displays the info If any used to localize the message of this LogRecord or else returns null.
getResourceBundleName()It displays the name of the ResourceBundle (if any) used to localize the message of this LogRecord or else returns null.
getSequenceNumber() It displays a  sequence number 
getSourceClassName() It displays the class name of the class logging the message represented by this LogRecord. 

Example 1:


// Java Program demonstrating XML Formatter Logging API
// Importing required libraries
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.XMLFormatter;
// Main class
// XMLFormatterExample
public class GFG {
    // Main driver method
    public static void main(String[] args)
        // A Locale object represents a specific
        // geographical, political, or cultural region Let
        // us take Locale.ENGLISH as the default in this
        // program
        Locale englishLocale = Locale.getDefault();
        // Try block to check for exceptions
        try {
            // Creating new object of GregorianCalendar
            // class
            GregorianCalendar calendar
                = new GregorianCalendar();
            int calendarYear = calendar.get(Calendar.YEAR);
            // There are different levels of setting
            // loggerInformation default level is INFO.
            // If the value is not specified, for our
            // example we have kept as INFO
            // other available levels are
            // ALL - 1,
            // FINEST - 2,
            // FINER - 3,
            // FINE - 4,
            // CONFIG - 5,
            // INFO - 6,
            // WARNING - 7,
            // SEVERE - 8,
            // OFF - 9
            LogRecord logRecordInformation = new LogRecord(
                Level.INFO, "XMLFormatterTest");
            // Display message for  better readibility
            // Printing logger levels, message,
            // getMillis,getSequenceNumber
                "Logger level.."
                + logRecordInformation.getLevel());
                + logRecordInformation.getMessage());
                + logRecordInformation.getMillis());
                + logRecordInformation.getSequenceNumber());
            // Display message for better readibility
            // As we are using XMLFormatter, it displays the
            // output in XML format.
            //  It has higher visibility if used with UTF-8
            // Now creating object of XMLFormatter class
            XMLFormatter formatter = new XMLFormatter();
            String xmlFormatted
                = formatter.format(logRecordInformation);
        // Executing the above code no matter
        // if there is exception or not
        finally {


Example 2:


// Java Program demonstrating XML Formatter Logging API
// Importing requied libraries
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.XMLFormatter;
// Main class
// XMLFormatterExample1
public class GFG {
    // Main driver method
    public static void main(String[] args) throws Exception
        // Creating an object of XMLFormatter class
        XMLFormatter xmlFormatter = new XMLFormatter();
        // Setting level to Info
        LogRecord logRecord = new LogRecord(
            "Logrecord message to be printed in xml file..");
        // We can see the output of LogRecord in
        // logrecordxml.xml file
        FileHandler fileHandler
            = new FileHandler("logrecordxml.xml");
        // Prepared data is displayed in the
        // logrecordxml.xml file
        // Lastly releasing out all the records
        // using the flush() method

Output: Instead of printing in the console, we can print the same in the XML file as shown below


XML notation is very helpful to read and understand log messages. Hence, XMLFormatter provides an efficient way to achieve the same. Many prefer to have XMLFormatter instead of SimpleFormatter which produces the output in the plain text format.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :