DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Java
  4. Logging With Log4j in Java

Logging With Log4j in Java

Here's an introduction to logging with Log4j. If you aren't familiar with it already, take a look at what it offers and how to configure it for your Java projects.

Akash Tomar user avatar by
Akash Tomar
·
Jun. 05, 18 · Tutorial
Like (17)
Save
Tweet
Share
262.93K Views

Join the DZone community and get the full member experience.

Join For Free

If we use SOP (System.out.print()) statements to print log messages, then we can run into some disadvantages:

  1. We can print log messages on the console only. So, when the console is closed, we will lose all of those logs.
  2. We can’t store log messages in any permanent place. These messages will print one by one on the console because it is a single-threaded environment.

To overcome these problems, the Log4j framework came into the picture. Log4j is an open source framework provided by Apache for Java projects.

Log4j Components

Log4j has three main components, which are the following:

  1. Logger
  2. Appender
  3. Layout

Logger

Logger is a class in the org.apache.log4j.* package. We have to initialize one Logger object for each Java class. We use Logger’s methods to generate log statements. Log4j provides the factory method to get Logger objects.

Syntax to get Logger objects:

static Logger logger = Logger.getLogger(CurrentClass.class.getName()).


Note: CurrentClass is a Java class name for which we are getting logger object.

Example

public class Student{

    private static final Logger LOGGER = Logger.getLogger(Student.class);
    public void getStudentRecord() {
    }
}


The Logger class has some methods that are used to print application status.

We have five methods in the Logger class

  1. info()
  2. debug()
  3. warn()
  4. fatal()
  5. error()

How and when to use these methods depends on us. Here, the method names are different, but the process is the same for all of them: all will print a message only.

Levels

Level is a class in the org.apache.log4j.* package. We can also make a custom level by extending the Level class. Each level has a different priority order, like this:

debug < info < warn < error < fatal

It means fatal is the highest priority error, like if/when the database is closed.

Appender

Appender is used to write messages into a file or DB or SMTP.

Log4j has different types of appenders:

  1. SyslogAppendersends
  2. SMTPAppender
  3. JDBCAppender
  4. FileAppender
  5. SocketHubAppender
  6. SocketAppender
  7. TelnetAppender
  8. ConsoleAppender

Layout

This is used to define the formatting in which logs will print in a repository.

We have different types of layouts:

  1. PatternLayout
  2. SimpleLayout
  3. XMLLayout
  4. HTMLLayout

Log4j: Configuration

log4j.properties

# Root logger option
log4j.rootLogger=INFO, file, stdout

# configuration to print into file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D:\\log\\logging.log
log4j.appender.file.MaxFileSize=12MB
log4j.appender.file.MaxBackupIndex=10
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

# configuration 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


Description of log4j.properties file :

  • log4j.appender.file=org.apache.log4j.RollingFileAppender

  • log4j.appender.stdout=org.apache.log4j.ConsoleAppender

These will define appender types: That means they will specify where we want to store application logs. RollingFileAppender will print all logs in a file, and ConsoleAppender will print all logs in the console.

  • log4j.appender.file.File=D:\\log\\logging.log

That specifies the log file location.

  • 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

These specify the pattern in which logs will print to the log file.

Example:

import org.apache.log4j.Logger;

public class Student {
    static Logger logger = Logger.getLogger(Student.class);

    public static void main(String[] args) {        
        logger.debug("This is debug message");
        logger.info("This is info message");
        logger.warn("This is warn message");
        logger.fatal("This is fatal message");
        logger.error("This is error message");

        System.out.println("Logic executed successfully....");

    }

}


logging.log(log file):

2018-05-02 16:01:45 INFO  Student:12 - This is info message
2018-05-02 16:01:45 WARN  Student:13 - This is warn message
2018-05-02 16:01:45 FATAL Student:14 - This is fatal message
2018-05-02 16:01:45 ERROR Student:15 - This is error message


It will not print debug level error logs because we defined our root logger as INFO-level in our log4j.properties file. Error messages with a priority greater than INFO will print.

Console logs:

16:01:45,511 &nbsp;INFO Student:12 - This is info message
16:01:45,517 &nbsp;WARN Student:13 - This is warn message
16:01:45,517 FATAL Student:14 - This is fatal message
16:01:45,518 ERROR Student:15 - This is error message

program executed successfully....
Log4j Java (programming language)

Published at DZone with permission of Akash Tomar. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Implementing Infinite Scroll in jOOQ
  • DevSecOps Benefits and Challenges
  • Why Does DevOps Recommend Shift-Left Testing Principles?
  • Three SQL Keywords in QuestDB for Finding Missing Data

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: