我可以 运行 我的日志异步使用 log4j 1.x 和 log4j.properties 文件吗?

Can i run my log asynchronously using log4j 1.x with log4j.properties file?

我目前正在研究 "log4j 1.x" 与 "logback" 的性能,即 (slf4j)。

我可以将异步附加到我的 logback,但是我找不到任何可以异步我的 log4j 的 link。

Async 仅在 log4j 中引入2.x?或者有什么方法可以让我的 log4j 1.x 异步工作。

请帮助我。

谢谢。

异步日志记录是 Log4j 2 的强项之一。使用 Async Loggers 代替 AsyncAppender:性能要好得多。

Log4j 2 performance page对比Log4j-1.x、Logback和Log4j 2。看看再决定用什么日志框架。

顺便说一句,Log4j 2 有一个名为 log4j-1.2-api-2.6.jar 的适配器,它允许您的应用程序使用旧的 log4j-1.2 API,但使用新的 log4j 2 实现。

(Log4j-1.x 也有一个 AsyncAppender。就像 Log4j 2 AsyncAppender 和 Logback AsyncAppender 一样,它使用 BlockingQueue。Log4j 2 的 Async Loggers 使用非阻塞数据结构,速度要快得多。 )

log4j.properties does not handle the advanced configuration features supported by the DOMConfigurator such as support custom ErrorHandlers, nested appenders such as the AsyncAppender, etc.

参考log4j API Documentation

在log4j中配置AsyncAppender有两种方式1.x

  1. 使用log4j.xml 如下配置 AsyncAppender
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console1" class="org.apache.log4j.ConsoleAppender">
        <param name="target" value="System.out" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{1}] %m%n" />
        </layout>
    </appender>

    <!--wrap ASYNC around other appender if you want -->
    <appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
        <param name="BufferSize" value="500" />
        <!-- LocationInfo is Optional, use only if location info is required. (Default value : false)-->
        <!-- <param name="LocationInfo" value="true" /> -->
        <appender-ref ref="console1" />
    <root>
        <priority value="debug" />
        <appender-ref ref="ASYNC" />
    </root>
</log4j:configuration>
  1. 以编程方式 您可以如下所示以编程方式配置 AsyncAppender
    static {
        enableAsyncAuditLog(Logger.getRootLogger());
    }

    private static void enableAsyncAuditLog(Logger targetLogger) {
        Enumeration<Appender> appenders = targetLogger.getAllAppenders();
        AsyncAppender asyncAppender = new AsyncAppender();
        asyncAppender.setBufferSize(500);
        asyncAppender.setLocationInfo(true); // Otherwise Class and Line info will not be available to logger
        while (appenders.hasMoreElements()) {
            Appender appender = appenders.nextElement();
            if (!(appender instanceof AsyncAppender)) {
                targetLogger.removeAppender(appender);
                asyncAppender.addAppender(appender);
            }
        }
        appenders = asyncAppender.getAllAppenders();
        if (appenders != null && appenders.hasMoreElements()) {
            targetLogger.addAppender(asyncAppender);
        }
    }

可以参考这个project参考