Full Stack Web Development Internship Program
- 29k Enrolled Learners
- Weekend/Weekday
- Live Class
Logging is an important feature which needs to be considered by the developers to trace back the errors. Java, being one of the most popular programming languages, comes with a customizable approach to logging by providing a basic logging API. So, in this article on Logger in Java, I am going to discuss how professionals can use this feature to enable extensible logging in Java.
The following topics will be covered in this article:
Before, we deep dive into logging in java, let us understand the need for logging.
While building applications, we often face errors which have to be debugged. So, with the help of logs, we can easily get information about what is happening in the application with a record of errors and unusual circumstances. Now, it might strike your mind that, why not use the System.out.print() statement in Java. Well, the problem with these statements is that log messages will be printed only on the console. So, once you close console, automatically, all the logs will be lost. Therefore, logs will be not be stored permanently, and are displayed one by one, as it is a single-threaded environment.
To avoid such issues, logging in Java is simplified with the help of the API provided through the java.util.logging
package, and the org.apache.log4j.*
package.
The Java logging components help the developer to create logs, pass the logs to the respective destination and maintain an proper format. The following are the three components:
You can refer to the below image for the working of all the three components:
When an application makes a logging call, the Logger component records the event in a LogRecord and forwards it to the appropriate Appender. Then it formated the record using the Layout according to the required format. Apart from this, you can also use more than one Filters to specify which Appenders should be used for events.
Now, let us understand what is a logger in Java in depth.
Loggers in Java are objects which trigger log events, They are created and are called in the code of the application, where they generate Log Events before passing them to the next component which is an Appender. You can use multiple loggers in a single class to respond to various events or use Loggers in a hierarchy. They are normally named using the hierarchical dot-separated namespace. Also, all the Logger names must be based on the class or the package name of the logged component.
Apart from this, each Logger keeps a track of the nearest existing ancestor in the Logger namespace and also has a “Level” associated with it. Well, I will discuss the Loggers in the latter part of this article, but before that, let me show you how to create a Logger in Java.
The process of creating a new Logger in Java is quite simple. You have to use Logger.getLogger()
method. The getLogger()
method identifies the name of the Logger and takes string as a parameter. So, if a Logger pre-exists then, that Logger is returned, else a new Logger is created.
static Logger logger = Logger.getLogger(SampleClass.class.getName());
Here, SampleClass is the class name for which we are getting the Logger object.
public class Customer{ private static final Logger LOGGER = Logger.getLogger(Customer.class); public void getCustomerDetails() { } }
Now that I have told you how to create a Logger in Java, let us see the different levels available in logging.
Log Levels are used to categorize the logs by their severity or the impact on the stability of the application. The org.apache.log4j.*
package and the java.util.logging
both provide different levels of logging. Let us take a look at each of them one by one.
org.apache.log4j.*
package provides the following levels in descending order:
java.util.logging
package provides the following levels in descending order:
Apart from this, the above package also provides two additional levels ALL
and OFF
used for logging all messages and disabling logging respectively.
🔥𝐄𝐝𝐮𝐫𝐞𝐤𝐚 𝐉𝐚𝐯𝐚 𝐂𝐨𝐮𝐫𝐬𝐞 𝐓𝐫𝐚𝐢𝐧𝐢𝐧𝐠: https://www.edureka.co/java-j2ee-training-course (Use code “𝐘𝐎𝐔𝐓𝐔𝐁𝐄𝟐𝟎”)
This Edureka Java Full Course will help you understand the various fundamentals of Java programm…
org.apache.log4j.*
package:import org.apache.log4j.Logger; public class Customer { static Logger logger = Logger.getLogger(Customer.class); public static void main(String[] args) { logger.error("ERROR"); logger.warn("WARNING"); logger.fatal("FATAL"); logger.debug("DEBUG"); logger.info("INFO"); System.out.println("Final Output"); } }
So if your output is root logger as WARN-level in our log4j.properties file, then all the error messages with a higher priority than WARN will be printed as below:
You can also set the level by using the setLevel() method from the java.util.logging
package as below:
logger.setLevel(Level.WARNING);
java.util.logging
package:package edureka; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.*; class EdurekaLogger { private final static Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); public void sampleLog() { LOGGER.log(Level.WARNING, "Welcome to Edureka!"); } } public class Customer { public static void main(String[] args) { EdurekaLogger obj = new EdurekaLogger(); obj.sampleLog(); LogManager slg = LogManager.getLogManager(); Logger log = slg.getLogger(Logger.GLOBAL_LOGGER_NAME); log.log(Level.WARNING, "Hi! Welcome from Edureka"); } }
To enable logging in your application using the org.apache.log4j.*
package or the java.util.logging
package, you have to configure the properties file. Next in this article on Logger in Java, let us discuss the properties file of both of them.
# Enable Root logger option log4j.rootLogger=INFO, file, stdout # Attach appenders to print file log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=E:loglogging.log log4j.appender.file.MaxFileSize=10MB log4j.appender.file.MaxBackupIndex=5 log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n # Attach appenders to print on console log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
handlers= java.util.logging.ConsoleHandler .level= WARNING # Output will be stored in the default directory java.util.logging.FileHandler.pattern = %h/java%u.log java.util.logging.FileHandler.limit = 60000 java.util.logging.FileHandler.count = 1 java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter # Level of logs will be limited to WARNING and above. java.util.logging.ConsoleHandler.level = WARNING java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
Here,
To log events in Java, you have to make sure that you assign a level to easily filer out the events. To assign a level and mention a message you can use the below methods:
logger.log(Level.INFO, “Display message”);
Here, level is INFO and the message to be printed is "Display Message".
logger.info(“Display message”);
To make sure that Logger in Java, logs only events which are at or above the INFO level, you can use the setLevel() method discussed above.
Now, that I have discussed how to use Logger in Java, let us discuss the next component of Log4j architecture, i.e. Appenders.
Appender or Handlers are responsible for recording log events to a destination. Each logger has access to multiple handlers and receives the log message from the logger. Then, Appenders use Formatters or Layouts to format the events and send them to the corresponding destination.
An Appender can be turned off using the setLevel(Level.OFF) method. The two most standard handlers in the java.util.logging
package are as follows:
For, your better understanding, I have explained few Appenders in the properties section.
The layout of Formatters are used to format and convert data in a log event. Logging frameworks provide Layouts for HTML, XML, Syslog, JSON, plain text and other logs.
For, your better understanding, I have explained a few Layouts in the properties section. With this, we come to the end of this blog on “Logger in Java”. I hope you guys are clear with what has been taught to you in this article. If you’re just beginning, then watch at this Java Tutorial to Understand the Fundamental Java Concepts.
Check out the Java Online Course by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.
Got a question for us? Please mention it in the comments section of this “Logger in Java” blog and we will get back to you as soon as possible.
Course Name | Date | Details |
---|---|---|
Java Course Online | Class Starts on 21st December,2024 21st December SAT&SUN (Weekend Batch) | View Details |
Java Course Online | Class Starts on 1st March,2025 1st March SAT&SUN (Weekend Batch) | View Details |
edureka.co