Logging in Java


1. Using java.util.logging (built-in Java logging)

import java.util.logging.Logger;
import java.util.logging.Level;

public class LoggingExample {
    private static final Logger logger = Logger.getLogger(LoggingExample.class.getName());

    public static void main(String[] args) {
        logger.info("This is an info message");
        logger.warning("This is a warning message");
        logger.severe("This is a severe message");

        int x = 5;
        int y = 0;
        try {
            int result = x / y;
        } catch (ArithmeticException e) {
            logger.log(Level.SEVERE, "Exception occurred", e);
        }
    }
}
  • Logger is the main class.
  • Level defines the severity (INFO, WARNING, SEVERE, FINE, etc.).
  • You can configure it to log to files, consoles, or custom handlers.

2. Using Log4j (popular external logging library)

Step 1: Add dependency (if using Maven)

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.20.0</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.20.0</version>
</dependency>

Step 2: Create a logger in Java

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Log4jExample {
    private static final Logger logger = LogManager.getLogger(Log4jExample.class);

    public static void main(String[] args) {
        logger.info("Info message");
        logger.error("Error message");
        logger.debug("Debug message");
    }
}

Step 3: Configure Log4j using log4j2.xml

<Configuration status="WARN">
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d [%t] %-5level: %msg%n%throwable"/>
    </Console>
  </Appenders>
  <Loggers>
    <Root level="info">
      <AppenderRef ref="Console"/>
    </Root>
  </Loggers>
</Configuration>

3. Using SLF4J (Simple Logging Facade for Java)

SLF4J is an abstraction, which can work with Log4j, Logback, or java.util.logging. Example:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SLF4JExample {
    private static final Logger logger = LoggerFactory.getLogger(SLF4JExample.class);

    public static void main(String[] args) {
        logger.info("Hello SLF4J");
        logger.warn("Warning SLF4J");
    }
}

Tips for Good Logging

  1. Use different levels (TRACE, DEBUG, INFO, WARN, ERROR) properly.
  2. Avoid logging sensitive information.
  3. Configure log rotation for file logs.
  4. Use a consistent format for easier debugging and monitoring.

Leave a Reply