文档章节

Log4j1,Logback以及Log4j2性能测试对比

ksfzhaohui
 ksfzhaohui
发布于 2016/11/16 17:49
字数 768
阅读 1.3W
收藏 10

环境

jdk:1.7.0_79
cpu:i5-4570@3.20GHz 4核
eclipse:3.7
操作系统:win7

准备

1.log4j:1.7.21

<dependency>
        <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.21</version>
</dependency>

log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>

    <appender name="myConsole" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{dd HH:mm:ss,SSS\} %-5p] [%t] %c{2\} - %m%n" />
        </layout>

        <!--过滤器设置输出的级别 -->
        <filter class="org.apache.log4j.varia.LevelRangeFilter">
            <param name="levelMin" value="debug" />
            <param name="levelMax" value="warn" />
            <param name="AcceptOnMatch" value="true" />
        </filter>
    </appender>

    <appender name="myFile" class="org.apache.log4j.DailyRollingFileAppender">
        <param name="File" value="log4jTest.log" />
        <param name="Append" value="true" />
        <param name="DatePattern" value="'.'yyyy-MM-dd'.log'" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%t] - %m%n" />
        </layout>
    </appender>

    <appender name="async_file" class="org.apache.log4j.AsyncAppender">
        <param name="BufferSize" value="32" />
        <appender-ref ref="myFile" />
    </appender>

    <logger name="org.logTest" additivity="false">
        <level value="info" />
        <appender-ref ref="async_file" /> <!-- 同步:FILE 异步:async_file -->
    </logger>

</log4j:configuration>

2.logback:1.1.7

<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.1.7</version>
</dependency>

logback.xml

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoder 默认配置为PatternLayoutEncoder -->
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
            </pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>testFile.log</file>
        <append>true</append>
        <encoder>
            <pattern>[%t] - %m%n
            </pattern>
        </encoder>
    </appender>

    <!-- 异步输出 -->
    <appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
        <discardingThreshold>0</discardingThreshold>
        <appender-ref ref="FILE" />
    </appender>

    <logger name="org.logTest" level="INFO"
        additivity="false">
        <appender-ref ref="ASYNC" />  <!-- 同步:FILE 异步:ASYNC-->
    </logger>

    <root level="ERROR">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

3.log4j2:2.6.2

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.6.2</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
    <version>2.6.2</version>
</dependency>
<dependency>
    <groupId>com.lmax</groupId>
    <artifactId>disruptor</artifactId>
    <version>3.3.4</version>
</dependency>

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--设置log4j2的自身log级别为warn -->
<configuration status="warn">

    <appenders>
         <console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n" />
        </console>

        <RollingFile name="RollingFileInfo" fileName="info.log"
            filePattern="${sys:user.home}/logs/hpaasvc/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
            <Filters>
                <ThresholdFilter level="INFO" />
                <ThresholdFilter level="WARN" onMatch="DENY"
                    onMismatch="NEUTRAL" />
            </Filters>
            <PatternLayout pattern="[%t] - %m%n" />
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="100 MB" />
            </Policies>
        </RollingFile>

        <RandomAccessFile name="RandomAccessFile" fileName="asyncWithLocation.log"
            immediateFlush="false" append="true">
            <PatternLayout>
                <Pattern>[%t] - %m%n</Pattern>
            </PatternLayout>
        </RandomAccessFile>

    </appenders>

    <loggers>
        <!-- <AsyncLogger name="asynLogger" level="trace"
            includeLocation="true">
            <AppenderRef ref="RandomAccessFile" />
        </AsyncLogger> -->
        <Root level="info" includeLocation="true">
            <AppenderRef ref="RollingFileInfo" />
        </Root>
    </loggers>

</configuration>

测试

准备50条线程同时记录1000000条数据,然后统计时间,详细代码如下:

import java.util.concurrent.CountDownLatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class App {
    private static Logger log = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) throws InterruptedException {
        int messageSize = 1000000;
        int threadSize = 50;
        final int everySize = messageSize / threadSize;

        final CountDownLatch cdl = new CountDownLatch(threadSize);
        long startTime = System.currentTimeMillis();
        for (int ts = 0; ts < threadSize; ts++) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    for (int es = 0; es < everySize; es++) {
                        log.info("======info");
                    }
                    cdl.countDown();
                }
            }).start();
        }

        cdl.await();
        long endTime = System.currentTimeMillis();
        System.out.println("log4j1:messageSize = " + messageSize
                + ",threadSize = " + threadSize + ",costTime = "
                + (endTime - startTime) + "ms");
    }
}

log4j1和logback的同步和异步分别修改为对应的appender就行了
log4j2的异步方式提供了2中模式:
1.全局开启
设置Log4jContextSelector系统属性为:
org.apache.logging.log4j.core.async.AsyncLoggerContextSelector

System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");

2.混合同步异步模式
不需要设置Log4jContextSelector,但是需要使用AsyncLogger标签

更多详细参考官方文档:http://logging.apache.org/log4j/2.x/manual/async.html#AllAsync

结果
分别测试完以后统计成表格如下:

log4j2的异步模式表现了绝对的性能优势,优势主要得益于Disruptor框架的使用

LMAX Disruptor technology. Asynchronous Loggers internally use the Disruptor, a lock-free inter-thread communication library, instead of queues, resulting in higher throughput and lower latency.

一个无锁的线程间通信库代替了原来的队列

更多Disruptor :

http://developer.51cto.com/art/201306/399370.htm
http://ifeve.com/disruptor/
 

© 著作权归作者所有

ksfzhaohui

ksfzhaohui

粉丝 416
博文 164
码字总数 254836
作品 3
南京
高级程序员
私信 提问
加载中

评论(4)

ksfzhaohui
ksfzhaohui 博主

引用来自“磨砂轮”的评论

同一个java程序可以共存log4j与logback ?
不可以吧,我都是分开测试的
磨砂轮
磨砂轮
同一个java程序可以共存log4j与logback ?
ksfzhaohui
ksfzhaohui 博主

引用来自“bill2candy”的评论

官网已经给出了详细的Logging Peak Throughput测试结果,
建议参考:http://logging.apache.org/log4j/2.x/manual/async.html,Logging Peak Throughput章节
是的,有看到的,自己亲自测一下印象比较深一点
bill2candy
bill2candy
官网已经给出了详细的Logging Peak Throughput测试结果,
建议参考:http://logging.apache.org/log4j/2.x/manual/async.html,Logging Peak Throughput章节
jcl与jul、log4j1、log4j2、logback的集成原理

1 系列目录 - jdk-logging、log4j、logback日志介绍及原理- jcl与jul、log4j1、log4j2、logback的集成原理- slf4j与jdk-logging、log4j1、log4j2、logback的集成原理- slf4j、jcl、jul、log...

乒乓狂魔
2015/04/29
5.1K
2
spring boot 1.5.4 整合log4j2(十一)

上一篇:spring boot 1.5.4 定时任务和异步调用(十) Spring Boot整合log4j2 spring boot整合log4j2项目spring-boot-jsp源码: spring-boot相关项目源码, 码云地址:https://git.oschina.n...

wyait
2017/09/29
0
0
日志框架_Index

2种日志接口框架,4种日志实现框架 jdk-logging、log4j、logback日志介绍及原理 jcl与jul、log4j1、log4j2、logback的集成原理 slf4j与jul、log4j1、log4j2、logback的集成原理 slf4j、jcl、...

陶邦仁
2015/12/05
724
0
【Diary Report 2017-12-19】基础框架的那些事

diary_report.jpg What did you do today 日志门面有:jcl(Apache Commons Logging), slf4j, jboss-logging(不是服务大众的)。日志实现有:log4j, log4j2,logback,jul(java.util.logging)。公......

cmazxiaoma
2017/12/20
0
0
slf4j、jcl、jul、log4j1、log4j2、logback大总结

1 系列目录 - jdk-logging、log4j、logback日志介绍及原理- commons-logging与jdk-logging、log4j1、log4j2、logback的集成原理- slf4j与jdk-logging、log4j1、log4j2、logback的集成原理- s...

乒乓狂魔
2015/05/04
3.2W
34

没有更多内容

加载失败,请刷新页面

加载更多

OSChina 周六乱弹 —— 现在看动弹的人都是什么状态

Osc乱弹歌单(2020)请戳(这里) 【今日歌曲】 @薛定谔的兄弟 :分享洛神有语创建的歌单「我喜欢的音乐」: 《夏日、教室与望着窗外的我》- Candy_Wind 手机党少年们想听歌,请使劲儿戳(这里...

小小编辑
今天
77
1
wamp环境安装redis扩展

1.查看phpinfo信息根据配置信息下载对应的扩展 关键信息:VC14,TS,x86 2.下载php_redis和php_igbinary扩展 php_redis扩展下载地址: https://windows.php.net/downloads/pecl/snaps/redis...

点滴课程
今天
36
0
开源商城开发笔记1-创建MyBatis示例

一、修改pom.xml,引入MyBatis,JUnit,Log4j <dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.4</version>......

土龙
今天
56
0
The Best Way To Learn English in 2020 (In my humble opinion.)

✅Here is the plan: THINGS YOU WILL NEED: - 1 hour per day (30 minutes will work as well). - a notebook and a pen to write down new vocabulary each day. - an English song. - an ......

FalconChen
昨天
73
0
nodejs 使用 pako 压缩数据

github https://github.com/nodeca/pako 应用场景 大对象传输一般使用json, 在worker或local storage中还必须使用字符串, pako可以对字符串或者 Uint8Array 数据进行压缩和解压, 牺牲一部分读...

阿豪boy
昨天
79
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部