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

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


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值