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 functionality, allowing developers to control the output format, level, and destination of log information.
Main Features:
- Highly configurable
- Supports multiple log levels
- Can output logs to multiple destinations (console, files, databases, etc.)
- Thread Safety
- Excellent performance
Core components of Log4j
Logger
Logger is the core component of Log4j, responsible for capturing log information. Applications record logs by calling Logger's methods.
Log levels (from high to low):
- FATAL - A very serious error that may cause the application to crash
- ERROR - An error event, but the application can still continue running
- WARN - A potentially harmful situation
- INFO - Coarse-grained runtime information
- DEBUG - Fine-grained debugging information
- TRACE - Information finer-grained than DEBUG
Appender
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. Common 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 a Maven project, add the following to pom.xml:
Example
log4j
log4j
1.2.17
Configuration file (log4j.properties)
Example
Set the root log level to INFO, with output destinations being the console and a file
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
import
org.apache.log4j.Logger
;
public
class
Log4jExample
{
// Get the Logger instance
private
static
final
Logger logger
=
Logger.
getLogger
(
Log4jExample.
class
)
;
public
static
void
main
(
String
[
]
args
)
{
// Record logs 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
Set the log level for the com.example package to DEBUG
log4j.logger.com.example
=
DEBUG
Use multiple Loggers
Example
// Get different Logger instances
Logger mainLogger
=
Logger.
getLogger
(
"main"
)
;
Logger dbLogger
=
Logger.
getLogger
(
"database"
)
;
mainLogger.
info
(
"Application started"
)
;
dbLogger.
debug
(
"Database connection established"
)
;
Asynchronous logging
For performance-critical applications, you can use AsyncAppender to implement asynchronous logging:
Example
log4j.appender.async
=
org.apache.log4j.AsyncAppender
log4j.appender.async.appender-ref
=
file
New features of Log4j 2.x
Log4j 2.x is an upgraded version of Log4j, providing more improvements:
- Significantly improved performance
- Supports a plugin architecture
- More flexible configuration methods (XML, JSON, YAML)
- Supports lambda expressions
- Automatically reloads the configuration file
Log4j 2.x basic configuration example (log4j2.xml)
Example
Best Practices
- Use log levels reasonably: Use INFO or WARN in production, and DEBUG in development
- Avoid excessive logging: Only record necessary information to avoid performance issues
- Use meaningful log messages: The message should contain enough context information to facilitate troubleshooting
- Record the stack trace when handling exceptions: Use the logger.error("message", exception) format
- Archive and clean up logs regularly: To prevent log files from becoming too large
Summary
Log4j is a widely used logging framework in the Java ecosystem. Mastering its use is essential for developing high-quality Java applications. Through reasonable configuration and usage, Log4j can help developers:
- Quickly locate and resolve problems
- Monitor the running status of applications
- Record important business operations
- Improve the maintainability of applications
For new projects, it is recommended to consider using Log4j 2.x, which provides better performance and more features.
Common Java Libraries