Configuration and demo
A fully open method
Add startup parameters -DLog4jContextSelector = org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
start the key parameters of a little saying:
the official documentation http://logging.apache.org/log4j/2.x/manual/async # AllAsync .html Key is -Dlog4j2.contextSelector = ...
but if you personally do experiments, or personally used, you may notice the problem, simply use with your version of:
-DLog4jContextSelector = org.apache.logging .log4j.core.async.AsyncLoggerContextSelector // == == full version supports
version supports -Dlog4j2.contextSelector = org.apache.logging.log4j.core.async.AsyncLoggerContextSelector // == 2.10.0 == later
Related code (2.10.0 later):
See org.apache.logging.log4j.util.PropertiesPropertySource and
org.apache.logging.log4j.util.PropertiesUtil.Environment
Environment There are three sets of configuration data, a different key, the same service semantics:
literal
{java.runtime.name=Java(TM) SE Runtime Environment}
normalized
{log4j2.javaRuntimeName=Java(TM) SE Runtime Environment} key 是log4j2.前缀 加上驼峰形式变量
tokenized
{[java, runtime, name]=Java(TM) SE Runtime Environment} key是list
The method of mixing two synchronous asynchronous
<!-- 使用异步日志时,启用如下配置,异步配置默认不打印location。此种方法无需配置JVM启动参数。 -->
<asyncRoot level="debug">
<AppenderRef ref="Console" />
</asyncRoot>
Some notes
- The default location information is not printed, such as line numbers, classes, methods and the like. We need to add if needed
includeLocation="true"
, but according to the official statement will be 30-100 times slower.
- Asynchronous time, if the print log in a real field value of the object referenced in the log information changed in such "hello {}", user.name this. It will not affect the accuracy of the print log. The answer is no, because log4j made a snapshot mechanism.
Malpractice asynchronous log
Asynchronous log not only the advantages of no drawbacks, the official gives some scenes (Drawbacks) not used:
- Exception handling. Even with exception handler can not cover all cases.
- In some uses, such as MapMessage and StructuredDataMessage this problem by not logging time snapshot avoid asynchronous print information may change
- CPU in a few circumstances, such as to a CPU
- Print log much faster than
appender
throughput. At this time, asynchronous and can not solve the problem, need to use a faster appender.