Skip to content
On this page

Log4j

Commons Logging was introduced earlier and can be used as a "log interface". The real "log implementation" can use Log4j.

Log4j is a very popular logging framework, the latest version is 2.x.

Log4j is a component-based logging system. Its architecture is roughly as follows:

log.info("User signed in.");

 │   ┌──────────┐    ┌──────────┐    ┌──────────┐    ┌──────────┐
 ├──▶│ Appender │───▶│  Filter  │───▶│  Layout  │───▶│ Console  │
 │   └──────────┘    └──────────┘    └──────────┘    └──────────┘

 │   ┌──────────┐    ┌──────────┐    ┌──────────┐    ┌──────────┐
 ├──▶│ Appender │───▶│  Filter  │───▶│  Layout  │───▶│   File   │
 │   └──────────┘    └──────────┘    └──────────┘    └──────────┘

 │   ┌──────────┐    ┌──────────┐    ┌──────────┐    ┌──────────┐
 └──▶│ Appender │───▶│  Filter  │───▶│  Layout  │───▶│  Socket  │
     └──────────┘    └──────────┘    └──────────┘    └──────────┘

When we use Log4j to output a log, Log4j automatically outputs the same log to different destinations through different Appenders. For example:

console: output to the screen; file: output to file; socket: output to a remote computer through the network; jdbc: output to database In the process of outputting logs, Filter is used to filter which logs need to be output and which logs do not need to be output. For example, only ERROR level logs are output.

Finally, format the log information through Layout, for example, automatically add date, time, method name and other information.

Although the above structure is complex, when we actually use it, we do not need to care about the Log4j API, but configure it through the configuration file.

Taking XML configuration as an example, when using Log4j, we put a log4j2.xml file on classpath and let Log4j read the configuration file and output logs according to our configuration. Here is an example configuration file:

xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
	<Properties>
        <!-- Define log format -->
		<Property name="log.pattern">%d{MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36}%n%msg%n%n</Property>
        <!-- Define filename variable -->
		<Property name="file.err.filename">log/err.log</Property>
		<Property name="file.err.pattern">log/err.%i.log.gz</Property>
	</Properties>
    <!-- Define Appender, the destination -->
	<Appenders>
        <!-- Define output to screen -->
		<Console name="console" target="SYSTEM_OUT">
            <!-- The log format refers to the log.pattern defined above -->
			<PatternLayout pattern="${log.pattern}" />
		</Console>
        <!-- Define output to a file, the file name refers to file.err.filename defined above -->
		<RollingFile name="err" bufferedIO="true" fileName="${file.err.filename}" filePattern="${file.err.pattern}">
			<PatternLayout pattern="${log.pattern}" />
			<Policies>
                <!-- Automatically cut logs according to file size -->
				<SizeBasedTriggeringPolicy size="1 MB" />
			</Policies>
            <!-- Keep the last 10 copies -->
			<DefaultRolloverStrategy max="10" />
		</RollingFile>
	</Appenders>
	<Loggers>
		<Root level="info">
            <!-- For info level logs, output to console -->
			<AppenderRef ref="console" level="info" />
            <!-- For error level logs, output them to err, which is the RollingFile defined above. -->
			<AppenderRef ref="err" level="error" />
		</Root>
	</Loggers>
</Configuration>

Although configuring Log4j is relatively cumbersome, once the configuration is completed, it is very convenient to use. For the above configuration file, all INFO level logs will be automatically output to the screen, while ERROR level logs will not only be output to the screen, but also output to a file at the same time. Moreover, once the log file reaches the specified size (1MB), Log4j will automatically cut new log files and retain up to 10 copies.

Having the configuration file is not enough, because Log4j is also a third-party library. We need to download Log4j from here . After unzipping, put the following 3 jar packages into classpath :

  • log4j-api-2.x.jar
  • log4j-core-2.x.jar
  • log4j-jcl-2.x.jar

Because Commons Logging will automatically discover and use Log4j, put commons-logging-1.2.jar downloaded in the previous section into classpath .

To print the log, you only need to write it according to Commons Logging. You can get the log output of Log4j without changing any code, similar to:

03-03 12:09:45.880 [main] INFO  com.itranswarp.learnjava.Main
Start process...

Best practices

During the development phase, the Commons Logging interface is always used to write logs, and there is no need to introduce Log4j during the development phase. If you need to write the log to a file, you only need to put the correct configuration file and the Log4j related jar package into classpath , and the log can be automatically switched to be written using Log4j without modifying any code.

Summary

Logging is implemented through Commons Logging, and Log4j can be used without modifying the code;

To use Log4j, you only need to put log4j2.xml and related jars into the classpath;

If you want to replace Log4j, you only need to remove log4j2.xml and related jars;

Only when extending Log4j, you need to reference the Log4j interface (for example, the function of encrypting logs and writing them to the database needs to be developed by yourself).

Log4j has loaded