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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How To Detect and Secure Your Java App From Log4j Vulnerabilities
  • How to Check if a Java Project Depends on A Vulnerable Version of Log4j
  • Unit Testing Log Messages Made Easy
  • How to Merge HTML Documents in Java

Trending

  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  • Vibe Coding With GitHub Copilot: Optimizing API Performance in Fintech Microservices
  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • Enforcing Architecture With ArchUnit in Java
  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.

By 
Akash Tomar user avatar
Akash Tomar
·
Jun. 05, 18 · Tutorial
Likes (17)
Comment
Save
Tweet
Share
267.1K 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.

Related

  • How To Detect and Secure Your Java App From Log4j Vulnerabilities
  • How to Check if a Java Project Depends on A Vulnerable Version of Log4j
  • Unit Testing Log Messages Made Easy
  • How to Merge HTML Documents in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!