Back to: Java Tutorials
To use Log4j in your Java application, you will need to follow these basic steps:
- Add the Log4j library to your project: Download the Log4j library from the Apache website or include it as a dependency in your build tool, such as Maven or Gradle.
- Create a Log4j configuration file: Log4j uses a configuration file to determine how to log messages. You can create a configuration file in XML, JSON, or properties format. The configuration file defines which appenders to use, the log levels to use, and the log format.
- Configure Log4j in your application: You can configure Log4j in your Java application using the
BasicConfigurator
class or by using thePropertyConfigurator
class to load the configuration file you created in step 2. - Add log statements to your code: You can add log statements to your code using the Log4j API. For example, to log a message at the INFO level, you can use the following code:
import org.apache.log4j.Logger;
public class MyClass {
private static final Logger logger = Logger.getLogger(MyClass.class);
public void doSomething() {
logger.info("Printing something...");
}
}
This will log the message “Printing something…” at the INFO level.
- View the logs: Log4j logs can be viewed in the console, a file, or a remote location, depending on how you configured the appenders in step 2.
Log4j is a powerful logging utility that provides developers with a flexible and configurable logging framework. By using Log4j in your Java applications, you can easily log information at different levels of granularity and diagnose issues quickly. With its wide range of appenders and integration with other Java-based frameworks, Log4j is a valuable tool for any Java developer.
Complete code example:
Step 1: Create a Maven Project First, create a new Maven project in your preferred IDE. You can do this by selecting File > New Project, then selecting Maven and following the prompts.
Step 2: Add Log4j Dependency to pom.xml Add the following dependency to your pom.xml file to include Log4j in your project:
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.17.1</version>
</dependency>
Step 3: Add Log4j Configuration File Create a new file named log4j2.xml
in the src/main/resources
directory. Here’s an example configuration that logs to both the console and a file:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<File name="File" fileName="logs/myapp.log">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</File>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console" />
<AppenderRef ref="File" />
</Root>
</Loggers>
</Configuration>
This configuration defines two appenders: one that logs to the console and one that logs to a file in the logs
directory. The log level is set to debug
, so all messages with a level of debug
or higher will be logged.
Step 4: Use Log4j in Your Code Finally, you can use Log4j in your code by creating a Logger
object and calling its methods to log messages. Here’s an example:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class MyApp {
private static final Logger logger = LogManager.getLogger(MyApp.class);
public static void main(String[] args) {
logger.debug("Debug message");
logger.info("Info message");
logger.warn("Warning message");
logger.error("Error message");
logger.fatal("Fatal message");
}
}
This code creates a Logger
object using the LogManager.getLogger()
method and logs messages at different levels using the logger’s methods.
When we run your Maven project, we should see log messages printed to the console and written to the log file specified in the configuration file.
Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.
Follow us on social media
Follow Author