Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Logging Framework Log4j

Java Logging Framework Log4j

Common Java Libraries Common Java Libraries


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:


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):

  1. FATAL - A very serious error that may cause the application to crash
  2. ERROR - An error event, but the application can still continue running
  3. WARN - A potentially harmful situation
  4. INFO - Coarse-grained runtime information
  5. DEBUG - Fine-grained debugging information
  6. TRACE - Information finer-grained than DEBUG

Appender

Appender defines the destination of log output. Common Appenders include:

Layout

Layout controls the format of log information. Common Layouts include:


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:

Log4j 2.x basic configuration example (log4j2.xml)

Example

   

       

           

       

       

           

       

   

   

       

           

           

       

   


Best Practices

  1. Use log levels reasonably: Use INFO or WARN in production, and DEBUG in development
  2. Avoid excessive logging: Only record necessary information to avoid performance issues
  3. Use meaningful log messages: The message should contain enough context information to facilitate troubleshooting
  4. Record the stack trace when handling exceptions: Use the logger.error("message", exception) format
  5. 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:

For new projects, it is recommended to consider using Log4j 2.x, which provides better performance and more features.

Common Java Libraries Common Java Libraries