Java/J2EE and SOA (239 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (46 Blogs)
  • Comprehensive Java Course (2 Blogs)
  • Java/J2EE and SOA (239 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

What is logger in Java and why do you use it?

Published on Sep 05,2019 40 Views
10 / 21 Blog from Advance Java

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

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:

    1. Need for logging
    2. Logging Components
    3. What is Logger?
    4. Appender or Handlers
    5. Layout or Formatters

Before, we deep dive into logging in java, let us understand the need for logging.

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.

Logging Components

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:

  • Loggers – Responsible for capturing log records and passing them to the corresponding Appender.
  • Appenders or Handlers – They are responsible for recording log events to a destination. Appenders format events with the help of Layouts, before sending outputs.
  • Layouts or Formatters – Responsible to determine how data looks when it appears in the log entry.

You can refer to the below image for the working of all the three components:

Logging Components - Logger in Java - Edureka

 

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.

What is Logger in Java?

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.

Create new Logger

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.

Syntax:

static Logger logger = Logger.getLogger(SampleClass.class.getName());

Here, SampleClass is the class name for which we are getting the Logger object.

    Example:

    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

    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:

    • FATAL
    • ERROR
    • WARN
    • INFO
    • DEBUG

    java.util.logging package provides the following levels in descending order:

    • SEVERE(HIGHEST LEVEL)
    • WARNING
    • INFO
    • CONFIG
    • FINE
    • FINER
    • FINEST(LOWEST LEVEL)

    Apart from this, the above package also provides two additional levels ALL and OFF used for logging all messages and disabling logging respectively.

    Example of Logging in Java using the 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);
    

    Example of Logging in Java using the 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.

    Properties File of Log4j and Java Util Package

    Sample Log4j Properties file:

    # 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
    
    • The Log4j properties file is created inside the src folder of the project.
    • log4j.appender.file=org.apache.log4j.RollingFileAppender -> Prints all logs in a file
    • log4j.appender.stdout=org.apache.log4j.ConsoleAppender -> Prints all logs in the console
    • log4j.appender.file.File=D:loglogging.log -> Specifies the log file location
    • log4j.appender.file.MaxFileSize=10MB -> Maximum size of the log file to 10MB
    • log4j.appender.file.MaxBackupIndex=5 -> Limits the number of backup files to 5
    • log4j.appender.file.layout=org.apache.log4j.PatternLayout -> Specifies the pattern in which logs will print to the log file.
    • log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L – %m%n -> Sets the default conversion pattern.

    Sample Java Util Package Properties File

    
    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,

    • java.util.logging.FileHandler.pattern = %h/java%u.log -> Log files would be written to C:TEMPjava1.log
    • java.util.logging.FileHandler.limit = 50000 ->  The maximum amount that the logger writes to any one file in bytes.
    • java.util.logging.FileHandler.count = 1 -> Specifies the number of output files
    • java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter -> Mentions the formatter used for formatting. Here XML Formatter is used.
    • java.util.logging.ConsoleHandler.level = WARNING -> Sets the default log level to WARNING
    • java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter -> Specifies the Formatter to  be used by all ConsoleHandler‘s. Here, SimpleFormatter is used.

    Logging Events

    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:

    Method 1: 

    logger.log(Level.INFO, “Display message”);
    
    Here, level is INFO and the message to be printed is "Display Message".

    Method 2:

    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

    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:

    • FileHandler: Writess the log message to file
    • ConsoleHandler: Writes the log message to the console

    For, your better understanding, I have explained few Appenders in the properties section.

    Layout or Formatters

    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.

    1. SimpleFormatter: Generates text messages with basic information.
    2. XMLFormatter: Generates XML message for the log

    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. 

    Check out the Java training 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.

    Comments
    0 Comments

    Browse Categories

    Subscribe to our Newsletter, and get personalized recommendations.