StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Saturday, February 8, 2014

Using Log4j for debugging in Java

 February 08, 2014     Java     No comments   

In this article, we will explore Log4j for debugging in Java.

Log4j Introduction

Log4j is a simple, reliable, fast and extensible open source logging and tracing API. Logging is an important part of any software development lifecycle and is the only way to debug in certain production systems where it is not feasible to use debuggers.

To use these examples download Log4j from https://logging.apache.org/log4j/1.2/.

Let us quickly start with something minimal and the then try to understand Log4j terminology and APIs.

Using Log4J BasicConfigurator to log debug messages to the console

In this example we create a static logger instance and initialize using a basic configurator which logs all debug messages to the console.
package com.sourcetricks.log4j;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class Log4jTest {
  // Initialize logger for instance Log4jTest
  static Logger log  = Logger.getLogger(Log4jTest.class);
    
  public static void main (String[] args) {
    // Basic configurator to log debug messages to the console
    BasicConfigurator.configure();         
          
    // Add some log messages
    log.debug("This is a debug message");
    log.trace("This is a trace message");         
  }
}
Output
0 [main] DEBUG com.sourcetricks.log4j.Log4jTest  - This is a debug message

Using Log4J BasicConfigurator to log all messages to the console

In this example we set the log level to log all messages to the console. Only difference from the previous example is that we have set the log level to log all messages to the console. Please note that in the output we get both the log messages unlike the previous example.
package com.sourcetricks.log4j;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class Log4jTest {
  // Initialize logger for instance Log4jTest
  static Logger log  = Logger.getLogger(Log4jTest.class);
    
  public static void main (String[] args) {
    // Set the level to log all messages
    log.setLevel(Level.ALL);

    // Basic configurator to log all messages to the console
    BasicConfigurator.configure();         
          
    // Add some log messages
    log.debug("This is a debug message");
    log.trace("This is a trace message");         
  }
}
Output
0 [main] DEBUG com.sourcetricks.log4j.Log4jTest  - This is a debug message
2 [main] TRACE com.sourcetricks.log4j.Log4jTest  - This is a trace message
W ith this basic examples let us jump into some terminology to understand Log4j better.

Log4J Terminology

Logger Hierarchy

In Log4j the loggers follow a hierarchy. There is always a root logger accessed using Logger.getRootLogger() and all other loggers are instantiated and accessed using Logger.getLogger(). Logger instances follow a named hierarchy. For example, com.sourcetricks is considered parent of com.sourcetricks.log4jtest.

Log Levels

Loggers can be assigned various levels including OFF, TRACE, DEBUG, INFO, WARN, ERROR, FATAL and ALL. By default if a logger is not assigned a level it inherits the level from the first non null level from the logger hierarchy towards the root logger.

Appenders

Appenders define the output destination for logs. Examples include console, file, syslog etc. Appenders also follow the logger hierarchy.

Layouts

Log4j allows the log output line to be customized as well. This is called layouts.

e.g) 0 [main] DEBUG com.sourcetricks.log4j.Log4jTest  - This is a debug message

Configuration

Log4j provides the capability and flexibility to fully customize the logging needs either via APIs, Java properties (key = value) format or using XML files. Normal convention to use configuration files instead of APIs to perform the Log4j customization. With this basic introduction let us look at some more examples to understand better the various customization options.

Using Log4J PropertyConfigurator to log debug messages to the console

In this example we use a PropertyConfigurator and specify the properties file to log debug messages to the console. Additionally we use the layout customization.
package com.sourcetricks.log4j;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Log4jTest {

    // Initialize logger for instance Log4jTest
    static Logger log  = Logger.getLogger(Log4jTest.class);
	
    public static void main (String[] args) {	
	// Property configurator
	PropertyConfigurator.configure("resources/log4j.console");		
		
	// Add some log messages
	log.debug("This is a debug message");
	log.trace("This is a trace message");
    }
}
Properties file
# Set root logger
log4j.rootLogger=DEBUG, console
 
# Add log messages to console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c - %m%n
Output
2014-02-09 07:58:03 DEBUG com.sourcetricks.log4j.Log4jTest - This is a debug message
With this basic understanding now it is all about customizing the property files to meet our customization needs. Please refer to this article Log4j properties configuration examples on some sample Log4J property file examples.
Email ThisBlogThis!Share to XShare to Facebook

Related Posts:

  • Java Properties ExampleHandling persistent properties is an important aspect in software design to prevent hard coding values in code. Properties allow the customization of … Read More
  • Java Reflection TutorialJava reflection is an advanced feature and is the ability to examine or modify the run-time behavior of applications. Java reflection is primarily use… Read More
  • Java AnnotationsAnnotations is a form of meta-data to the Java code and doesn't directly impact the behavior of the code. This article covers key concepts around anno… Read More
  • Java Callable FutureJava Callable Future Introduction Java concurrent API support Callable and Future interfaces to implement threads that can return a value. One simple… Read More
  • JDBC handling transactionsTransaction is a set of one or more statements executed as a unit. The intent is that multiple statements which are part of a unit are executed togeth… Read More
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Python FastAPI file upload and download
    In this article, we will look at an example of how to implement a file upload and download API in a Python FastAPI microservice. Example bel...
  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Accessing the Kubernetes API
    In this article, we will explore the steps required to access the Kubernetes API and overcome common challenges. All operations and communic...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Scheduling jobs in Python
    When developing applications and microservices we run into scenarios where there is a need to run scheduled tasks. Examples include performi...
  • Using Tekton to deploy KNative services
    Tekton is a popular open-source framework for building continuous delivery pipelines. Tekton provides a declarative way to define pipelines ...

Copyright © 2025 StackStalk