Logger places a very important part in java application.We can have many types of messages like Error Message,Warning message etc.Thus it will keep track of all errors and warnings that occurred during program execution in our Application.
This article will help you to understand what is Logger and how we use it in our program to log sever and warning messages in a file called log file.
Why logs in XML format?
We can write logs in plain text format . The problem with text files: the delimiter may be part of the log information. When writing the log information, you have to prepend an escape character, indicating that the following character is not a delimiter, and reading the file has to take care of analyzing the escape characters as well.
What is Java Logging API
Java logging API allows you to configure how messages are written by any class with the priority.For using logger in java we have to import package java.util.logging. This package will provides the logging capabilities by the use of class Logger.
What is Logger Object
A Logger is an object of class Logger. It is used to create log file that contain messages which are then stored in a central place to report on errors. These messages can be used for many purposes like for debugging, troubleshooting and auditing.
Logger objects allocate LogRecord objects which are then passed to Handler objects and handler objects then
passes the messages to the destinations including consoles, files, OS logs, etc.
Logger object is called by the getLogger method.This will either create a new Logger or return a suitable existing Logger
How to create a logger:
First import java.util.logging.Logger and call get Logger method from your class.
private final static Logger LOGGER = Logger.getLogger(MyClass.class .getName());
Simple program for creating a log file
In the above code we use FileHandler to store all the log messages in a file that is mentioned.
And to add log handler we use addHandler method.
We can import only import java.util.logging.* in place of importing three files for FileHandler,level and logger.
After executing this code, a log file named “LogFile.log” is created in c drive.
Created log file is in XML format which is given below.
Log XML Output:
The Logging level gives you the importance and urgency of a log message .Thus log levels define the severity of a message.It defines seven log levels which are given below: