log4j-2.x 高性能配置(支持jdk6)

Java 发表评论

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <!-- Don't forget to set system property
-DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
     to make all loggers asynchronous. -->
    <Appenders>
        <RollingRandomAccessFile name="RollingRandomAccessFile" fileName="C:/Users/win7/Downloads/log/app.log"
                                 filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
            <PatternLayout>
                <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
            </PatternLayout>
            <Policies>
                <SizeBasedTriggeringPolicy size="5 MB"/>
            </Policies>
        </RollingRandomAccessFile>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="RollingRandomAccessFile"/>
        </Root>
    </Loggers>
</Configuration>

Java代码

通过添加 


-DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector

或者设置System系统属性,以使用“disruptor”开启最高性能。

package test;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Main {
    private static final Logger LOGGER = LogManager.getLogger(Main.class);

    public static void main(String[] args) throws InterruptedException {
        Thread[] threads = new Thread[2];
        for (int i = 0; i < threads.length; i++) {
            threads[i] =
                    new Thread(new Runnable() {
                        public void run() {
                            for (int i = 0; i < 1000; i++) {
                                testLog();
                            }
                        }
                    });
        }
        long s = System.currentTimeMillis();
        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }
        for (int i = 0; i < threads.length; i++) {
            threads[i].join();
        }
        long e = System.currentTimeMillis();
        System.out.println(e - s);
    }

    public static void testLog() {
        LOGGER.debug("debug!!!");
        LOGGER.info("info!!!");
        LOGGER.warn("warn!!!");
        LOGGER.error("error!!!");
        LOGGER.fatal("fatal!!!");
    }
}

依赖包(支持jdk6的jar)

disruptor-3.0.0.beta1.jar
log4j-api-2.3.jar

log4j-core-2.3.jar

兼容log4j 1.2

1.添加依赖包:log4j-1.2-api-2.3.jar

2.声明和log4j 1.2保持一致:

private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(Main.class.getName());

其他的和log4j2都是一样的(注意配置:AsyncLoggerContextSelector)。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

昵称 *