How to Add Log4J Dependencies to Maven Projects

Liron Biam writer profile image
By Liron Biam
Jit Logo
Edited by Jit Team

Updated February 28, 2024.

a diagram of how to add log / log / dependencies to ma

Logging was once just a best practice to help you understand what's happening inside your applications. Now, any security expert worth their salt will tell you that you can’t build a security plan without it. 

As a result, organizations have turned to specialized logging tools like Log4J to strengthen their application security. This move has proven highly effective, with cyberattack risks on businesses dropping from 44% in 2022 to 34% in 2023. 

But why stop at Log4J when you can build an ecosystem around it? Integrating Log4J with your Maven projects offers advantages like simplified setup, dependency management, and enhanced automation. This article takes you through how to add Log4J to Maven projects to take your logging capabilities to the next level.

Introducing Apache Maven

Apache Maven is a popular build automation tool for Java projects. It also acts as a central control for developers, streamlining the process of building, packaging, and managing software projects. 

Maven operates based on a structured project model defined in a Project Object Model (POM) file. This XML configuration file serves as a blueprint for the project, containing information about its structure, dependencies, and goals. Here is a standard Maven execution: 

Apache Maven


Some of Maven's key features and benefits include: 

  • Simplified dependency management - Maven automatically downloads required libraries from remote repositories, ensuring your project uses only the correct library versions. This helps to ensure CI/CD security as it reduces the risk of outdated or vulnerable dependencies in your pipeline.  
  • Standardized project structure - Maven’s standardized development practices and project structures improve the consistency of projects, make it easier to ensure code quality, and ease team collaboration.
  • Plugins - Maven has a vast ecosystem of plugins, from code analysis to deployment and integration testing, and you can also create custom plugins to fit your project’s requirements. 
  • Project reporting - You can get detailed reports ranging from code quality to project documentation, helping you strengthen your security plan. 
  • Build automation - Maven supports DevOps automation processes by automating various aspects of the build process, including compilation, testing, and packaging, to save time and avoid human errors. 
  • Integration with IDEs and CI systems - This tool integrates with popular IDEs like IntelliJ IDEA and Eclipse, and CI tools like Jenkins and Travis CI. 

Why use Log4J dependencies on Maven projects

Log4J is a widely used Java-based logging solution that enables real-time continuous monitoring. It allows you to log anything from errors to informational messages and can be configured to log to various destinations, such as files, databases, and system alerts. Some benefits of using Log4J dependencies on Maven projects include:

  • API independence -  You can use Log4J with any Java API, making it a versatile and flexible logging solution.
  • Asynchronous logging - Log4J offloads logging tasks to different threads, which reduces the impact on the main application thread and the app’s performance.
  • Better support for concurrency - Log4J can handle multiple threads simultaneously, ensuring that your logs are not lost or corrupted.
  • Customizability - Log4J lets you customize layouts, appenders, and logging levels to meet your needs. You can also define filters to ensure that the data you’re getting is relevant. 
  • Support for output destinations - Log4J supports console, files, remote servers, files, and other output destinations so you can select the most suitable for your project. 

A rundown of Log4J vulnerabilities

We can’t talk about Log4J without addressing the elephant in the room: its vulnerabilities. The Log4J scandal in 2021 is no news to anyone, but what’s surprising is that 40% of Log4J downloads still contain vulnerabilities. 

The log4j JNDI Attack


While there isn’t a magic wand to make vulnerabilities disappear, equipping yourself with the right tools, such as SAST and DAST, is one step you can take to avoid vulnerability exploits and their disastrous consequences. 

Jit’s DevSecOps platform helps you continuously monitor your entire CI/CD pipeline for vulnerabilities. It acts as a centralized hub, enabling you to manage and automate various open-source security tools in a single unified platform, which improves visibility and makes it easier to act quickly whenever security gaps are spotted. Some tools in the integration include OWASP ZAP, Legitify, and Semgrep, which help uncover Log4J-type vulnerabilities.

Adding Log4J dependencies to Maven projects: The complete tutorial

Prerequisites:

Step 1: Adding Log4J dependencies

Before we start, it's crucial to update your Log4J version to benefit from security patches and improvements. Check for the latest version on the official Log4J website.

Open your project's pom.xml file. This file is where you manage your project's dependencies. Add the Log4J dependencies within the <dependencies> section:

Log4J dependencies example


Step 2: Configuration

Next, you need to configure Log4J. Create a log4j2.xml file in your project's resources directory and define your logging settings. Here's a basic example:

log4j2 xml example


Tip: In your log4j2.xml file, consider specifying different log levels for various application components. This can help you fine-tune your logging and make it more efficient.

Step 3: Logging in your Java code

Now, you can use Log4J to log messages in your Java code. First, import the necessary classes:

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

Then, create a logger instance:

private static final Logger logger = LogManager.getLogger(YourClassName.class);

Finally, start logging:

logger.info("This is an informational message."); logger.error("An error occurred: {}", exception.getMessage());

Here, you can use different log levels (e.g., INFO, DEBUG, ERROR) appropriately in your code to provide detailed information during debugging, while avoiding unnecessary clutter in production logs.

Step 4: Implementing the RollingFileAppender

Logging everything into a single file is not always the best practice. To improve your logging strategy, you can implement the RollingFileAppender. This allows you to regularly roll over the active log file, ensuring better organization and management of your logs.

To implement the RollingFileAppender with the specified policies, you should add the following configuration within your log4j2.xml file:

RollingFileAppender example


You’re all done. These steps can help you fortify your application's security and optimize its performance and maintainability.

Enhancing logging security

Tools like Log4J give developers the power to gain invaluable insights into their applications' behavior, enhance security, and ensure a smoother incident response. However, it’s essential to remember that security is an ongoing battle, and you need more than just Log4J  to ensure comprehensive coverage.

Jit offers a continuous security framework that protects your Java applications from security vulnerabilities. It scans your application's bytecode to identify potential issues, fixes them automatically, and provides detailed remediation suggestions. Its integration with tools like Semgrep provides robust defense against Log4J vulnerabilities, but we take it a step further. Jit also orchestrates a vast security toolchain to cover all potential security gaps throughout your CI/CD. See more here