Java Logging Framework Log4j
Log4j is an open-source logging framework under the Apache Software Foundation, designed specifically for Java applications.
Log4j provides flexible logging capabilities, allowing developers to control the output format, level, and target location of log information.
Main Features:
- Highly configurable
- Supports multiple log levels
- Can output logs to multiple destinations (console, file, database, etc.)
- Thread-safe
- Excellent performance
Log4j Core Components
Logger (Log Recorder)
Logger is the core component of Log4j, responsible for capturing log information. Applications record logs by calling methods on the Logger.
Log Levels (from high to low):
- FATAL - Very serious errors that may cause the application to crash
- ERROR - Error events, but the application can still continue running
- WARN - Potentially harmful situations
- INFO - Coarse-grained runtime information
- DEBUG - Fine-grained debugging information
- TRACE - More fine-grained information than DEBUG
Appender (Output Source)
Appender defines the destination of log output. Common Appenders include:
- ConsoleAppender: Output to the console
- FileAppender: Output to a file
- RollingFileAppender: Output to a file, supports file rolling
- JDBCAppender: Output to a database
Layout
Layout controls the format of log information. Commonly used Layouts include:
- PatternLayout: Uses a pattern string to define the format
- SimpleLayout: Simple format (level + message)
- HTMLLayout: HTML table format
Basic Usage of Log4j
Add Dependency
For Maven projects, add to pom.xml:
Example
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
Configuration File (log4j.properties)
Example
log4j.rootLogger=INFO, console, file
# Console output configuration
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# File output configuration
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=logs/application.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Java Code Example
Example
public class Log4jExample {
// Get Logger instance
private static final Logger logger = Logger.getLogger(Log4jExample.class);
public static void main(String[] args) {
// Log messages at different levels
logger.trace("This is a TRACE message");
logger.debug("This is a DEBUG message");
logger.info("This is an INFO message");
logger.warn("This is a WARN message");
logger.error("This is an ERROR message");
logger.fatal("This is a FATAL message");
try {
int result = 10 / 0;
} catch (Exception e) {
logger.error("An error occurred: ", e);
}
}
}
Advanced Configuration of Log4j
Set Different Log Levels by Package/Class
Example
log4j.logger.com.example=DEBUG
Using Multiple Loggers
Example
Logger mainLogger = Logger.getLogger("main");
Logger dbLogger = Logger.getLogger("database");
mainLogger.info("Application started");
dbLogger.debug("Database connection established");
Asynchronous Logging
For applications with high performance requirements, AsyncAppender can be used to implement asynchronous logging:
Example
log4j.appender.async.appender-ref=file
New Features in Log4j 2.x
Log4j 2.x is an upgraded version of Log4j, providing more improvements:
- Significant performance improvement
- Supports plugin architecture
- More flexible configuration methods (XML, JSON, YAML)
- Supports lambda expressions
- Automatically reloads configuration files
Log4j 2.x Basic Configuration Example (log4j2.xml)
Example
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<File name="File" fileName="logs/application.log">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</File>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
<AppenderRef ref="File"/>
</Root>
</Loggers>
</Configuration>
Best Practices
- Use log levels reasonably: Use INFO or WARN in production, and DEBUG in development
- Avoid excessive logging: Only log necessary information to avoid performance issues
- Use meaningful log messages: Messages should contain enough context information for troubleshooting
- Log the stack trace when handling exceptions: Use the logger.error("message", exception) format
- Regularly archive and clean up logs: Prevent log files from becoming too large
Summary
Log4j is a widely used logging framework in the Java ecosystem. Mastering its usage is crucial for developing high-quality Java applications. With proper configuration and usage, Log4j can help developers:
- Quickly locate and resolve issues
- Monitor application runtime status
- Record important business operations
- Improve the maintainability of applications
For new projects, it is recommended to consider using Log4j 2.x, which offers better performance and more features.
Other Extensions
Java Common Class Libraries