[Java] Exception handling using Log4j

Use Log4j

As mentioned earlier Commons Logging, it can be used as a "logging interface". And the real "logging implementation" can use Log4j.

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

Log4jIt is a log system with component design, and 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 Log4jto output a log, we automatically output the same log to different destinations Log4jthrough different ones. AppenderFor example:

  • console: output to the screen;
  • file: output to a file;
  • socket: output to a remote computer through the network;
  • jdbc: output to the database

In the process of outputting logs, use Filter to filter which logs need to be output and which logs do not need to be output. For example, only output logs at ERROR level.

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

Although the above structure is complicated, we don't need to care about the Log4j API when we actually use it, but configure it through the configuration file.

Take the XML configuration as an example. Log4jWhen using it, we put a log4j2.xmlfile classpathdown to Log4jread the configuration file and output the log according to our configuration. The following is an example configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
	<Properties>
        <!-- 定义日志格式 -->
		<Property name="log.pattern">%d{MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36}%n%msg%n%n</Property>
        <!-- 定义文件名变量 -->
		<Property name="file.err.filename">log/err.log</Property>
		<Property name="file.err.pattern">log/err.%i.log.gz</Property>
	</Properties>
    <!-- 定义Appender,即目的地 -->
	<Appenders>
        <!-- 定义输出到屏幕 -->
		<Console name="console" target="SYSTEM_OUT">
            <!-- 日志格式引用上面定义的log.pattern -->
			<PatternLayout pattern="${log.pattern}" />
		</Console>
        <!-- 定义输出到文件,文件名引用上面定义的file.err.filename -->
		<RollingFile name="err" bufferedIO="true" fileName="${file.err.filename}" filePattern="${file.err.pattern}">
			<PatternLayout pattern="${log.pattern}" />
			<Policies>
                <!-- 根据文件大小自动切割日志 -->
				<SizeBasedTriggeringPolicy size="1 MB" />
			</Policies>
            <!-- 保留最近10份 -->
			<DefaultRolloverStrategy max="10" />
		</RollingFile>
	</Appenders>
	<Loggers>
		<Root level="info">
            <!-- 对info级别的日志,输出到console -->
			<AppenderRef ref="console" level="info" />
            <!-- 对error级别的日志,输出到err,即上面定义的RollingFile -->
			<AppenderRef ref="err" level="error" />
		</Root>
	</Loggers>
</Configuration>

Although it is cumbersome to configure Log4j, once configured, it is very convenient to use. For the configuration file above, 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 be output to a file at the same time. And, once the log file reaches the specified size (1MB), Log4j will automatically cut a new log file and keep up to 10 copies.

It is not enough to have a configuration file, because Log4j is also a third-party library, we need to download Log4j from here, after decompression, put the following 3 jar packages into the classpath:

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

Because Commons LoggingLog4j will be automatically discovered and used, put the one downloaded in the previous section commons-logging-1.2.jarinto the classpath.

To print the log, you only need to Commons Loggingwrite according to the wording, without changing any code, you can get the log output of Log4j, similar to:

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

Best Practices

During the development phase, the interface is always used Commons Loggingto write to the log, and there is no need to introduce it during the development phase Log4j. If you need to write the log to a file, you only need to put the correct configuration file and the Log4jrelevant jar package in classpath, and the log can be automatically switched to use Log4jwrite without modifying any code.

summary

By Commons Loggingimplementing the log, it can be used without modifying the code Log4j;

To use Log4j, you only need to log4j2.xmlput the related jar into it classpath;

If you want to replace Log4j, you only need to remove log4j2.xmland related jar;

Log4jThe referenced interface is only required when extending Log4j(for example, the function of writing encrypted logs to the database needs to be developed by itself).

Guess you like

Origin blog.csdn.net/ihero/article/details/132193887