Language: Java
CLI/Utils
Log4j2 was created by the Apache Software Foundation to address performance and flexibility limitations in Log4j 1.x. It leverages a plugin architecture, supports various appenders and layouts, and provides better performance through asynchronous logging and garbage-free design.
Log4j2 is a high-performance, flexible, and reliable logging framework for Java applications. It is the successor to Log4j and provides advanced features such as asynchronous logging, custom log levels, and plugin support.
Add org.apache.logging.log4j:log4j-core and org.apache.logging.log4j:log4j-api dependencies in pom.xmlAdd implementation 'org.apache.logging.log4j:log4j-api:2.20.0' and implementation 'org.apache.logging.log4j:log4j-core:2.20.0' in build.gradleLog4j2 allows developers to log messages at different levels (TRACE, DEBUG, INFO, WARN, ERROR, FATAL). It supports configuration through XML, JSON, YAML, or properties files and integrates with SLF4J for logging abstraction.
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.info("Application started");
}
}Initializes a Log4j2 logger and logs an INFO level message.
String user = "Alice";
logger.debug("User {} has logged in", user);Shows parameterized logging to avoid string concatenation overhead.
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
logger.error("An error occurred: {}", e.getMessage(), e);
}Logs an exception with a message and stack trace.
<Configuration status="WARN">
<Appenders>
<Async name="AsyncConsole">
<Console />
</Async>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="AsyncConsole" />
</Root>
</Loggers>
</Configuration>Demonstrates asynchronous logging configuration for better performance.
<Logger name="com.example" level="debug" additivity="false">
<AppenderRef ref="FileAppender" />
</Logger>Defines a logger with a specific level and appender for fine-grained control.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Logger logger = LoggerFactory.getLogger(MyApp.class);
logger.info("Message through SLF4J facade");Integrates Log4j2 with SLF4J for logging abstraction.
Use asynchronous logging for high-throughput applications.
Externalize configuration in XML, JSON, YAML, or properties files for flexibility.
Use parameterized logging instead of string concatenation for performance.
Organize loggers per package or class for clarity.
Leverage multiple appenders (console, file, rolling file, etc.) for different logging needs.