Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
67740cc
upgrade log4j and slf4j
Pil0tXia Dec 29, 2023
9c23c8b
recommanded example
Pil0tXia Dec 29, 2023
9f1e5d3
add known dependencies
Pil0tXia Dec 29, 2023
8daf32a
remove log4j-to-slf4j
Pil0tXia Dec 29, 2023
bd6c91c
Revert "recommanded example"
Pil0tXia Dec 30, 2023
854f39f
Deprecate `LogUtils` for removal
ppkarwasz Dec 30, 2023
3e4dc11
Add minimal `errorPronePatch` task
ppkarwasz Dec 30, 2023
e78fcef
Rewrite `LogUtils` call sites
ppkarwasz Dec 30, 2023
7c1c2dd
add suppliers
Pil0tXia Dec 30, 2023
c474c70
Revert "Rewrite `LogUtils` call sites"
Pil0tXia Jan 5, 2024
6a8d5cf
Merge branch 'remove-logutils' into pil0txia_enhance_4697
Pil0tXia Jan 5, 2024
f21e084
Replace the time-consuming method parms with the supplier usage of Lo…
Pil0tXia Jan 5, 2024
be0c532
Execute errorProne scripts and remove blank line by IDEA optimize import
Pil0tXia Jan 5, 2024
5dd28fa
Remove non-supplier methods in LogUtils
Pil0tXia Jan 5, 2024
ffcf2dc
Remove unused trace and error log level
Pil0tXia Jan 5, 2024
30ff1bb
Rename LogUtils to LogUtil to save space
Pil0tXia Jan 5, 2024
028f142
Merge branch 'master' into pil0txia_enhance_4697
Pil0tXia Jan 5, 2024
e6b07b1
Fix checkstyle
Pil0tXia Jan 5, 2024
40a1606
Replace isXXXXEnabled to normal use
Pil0tXia Jan 5, 2024
45028a5
Rename messageLogger to static final MESSAGE_LOGGER
Pil0tXia Jan 5, 2024
af00ea3
Fix all checkstyle warnings
Pil0tXia Jan 5, 2024
ef7292d
run spotlessApply
Pil0tXia Jan 5, 2024
005316c
Fix JDK11 Javadoc task failed
Pil0tXia Jan 5, 2024
abc67ce
Add {} and fix javadoc task
Pil0tXia Jan 6, 2024
c259f00
Revert "Add minimal `errorPronePatch` task"
Pil0tXia Jan 6, 2024
3731d78
Turn back to surpress javadoc only on JDK8
Pil0tXia Jan 6, 2024
56b3d16
Fix logging lack param
Pil0tXia Jan 6, 2024
a88e2f7
Merge branch 'master' into pil0txia_enhance_4697
Pil0tXia Jan 11, 2024
ae565be
Merge branch 'master' into pil0txia_enhance_4697
Pil0tXia Jan 11, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,7 @@ subprojects {
}

def grpcVersion = '1.43.2'
def log4jVersion = '2.22.1'

dependencyManagement {
dependencies {
Expand All @@ -487,10 +488,11 @@ subprojects {

dependency "com.google.guava:guava:31.0.1-jre"

dependency "org.slf4j:slf4j-api:1.7.30"
dependency "org.apache.logging.log4j:log4j-api:2.17.1"
dependency "org.apache.logging.log4j:log4j-core:2.17.1"
dependency "org.apache.logging.log4j:log4j-slf4j-impl:2.17.1"
dependency "org.slf4j:slf4j-api:2.0.9"
dependency "org.apache.logging.log4j:log4j-api:${log4jVersion}"
dependency "org.apache.logging.log4j:log4j-core:${log4jVersion}"
dependency "org.apache.logging.log4j:log4j-slf4j2-impl:${log4jVersion}"
dependency "org.apache.logging.log4j:log4j-slf4j-impl:${log4jVersion}" // used with SLF4J 1.7.x or older for third-party dependencies

dependency "com.lmax:disruptor:3.4.2"

Expand Down
4 changes: 2 additions & 2 deletions eventmesh-common/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ dependencies {

implementation "org.apache.logging.log4j:log4j-api"
implementation "org.apache.logging.log4j:log4j-core"
implementation "org.apache.logging.log4j:log4j-slf4j-impl"
implementation "org.apache.logging.log4j:log4j-slf4j2-impl"

implementation 'com.github.seancfoley:ipaddress'

Expand Down Expand Up @@ -67,7 +67,7 @@ dependencies {
testImplementation "org.slf4j:slf4j-api"
testImplementation "org.apache.logging.log4j:log4j-api"
testImplementation "org.apache.logging.log4j:log4j-core"
testImplementation "org.apache.logging.log4j:log4j-slf4j-impl"
testImplementation "org.apache.logging.log4j:log4j-slf4j2-impl"

testImplementation "com.lmax:disruptor"

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@

package org.apache.eventmesh.common.file;

import org.apache.eventmesh.common.utils.LogUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
Expand Down Expand Up @@ -62,10 +60,10 @@ private static void shutdown() {
return;
}

LogUtils.info(log, "[WatchFileManager] start close");
log.atInfo().log("[WatchFileManager] start close");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Since log.info() already supports determining log level internally, why not use a more concise log.info() here?

  2. Why not use the solution provided by @ppkarwasz in the discussion to modify LogUtils? Isn't this change smaller?

    private static final String FQCN = LogUtils.class.getName():

    public static void trace(Logger logger, Marker marker, String msg, Object arg) {
        final LoggingEventBuilder builder = logger.atTrace();
        if (builder instanceof CallerBoundaryAware) {
            ((CallerBoundaryAware) builder).setCallerBoundary(FQCN);
        }
       builder.addMarker(marker).log(msg, arg);
    }

  1. 既然log.info()内部已经支持判断日志级别,为什么这里不直接使用更简洁的log.info()
  2. 为什么不采用讨论中 ppkarwasz 提供的这种方案修改下LogUtils,这样改动不是更小吗?

Copy link
Member Author

@Pil0tXia Pil0tXia Dec 30, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Better performance:

The additional isDebugEnabled() check before log.debug() is performed in order to avoid invoking the methods referenced in the message field, thus improving logging performance. For example:

log.debug("formatted msg: {}", formatMsg(rawMsg));

Even when the log level is set to info, the formatMsg(rawMsg) method will still be called and return a result before being passed as an argument to log.debug(). This takes time.

  • Scenarios where Fluent Logging API is unnecessary:

Only the scenario mentioned in the Background Knowledge section require the use of Fluent Logging API. For example, in the case of the changes in Codec class L224, where no object parameters are passed or existing objects are referenced, there is no additional performance overhead, and there is no need to pre-evaluate log levels. The log.debug() usage can be directly applied.

There are many places where the usage of ifDebugEnabled is a remnant from the log4j era, which can be replaced with log.debug() from slf4j. However, in many cases, removing the ifDebugEnabled directly would result in a performance decrease.


有不少地方的ifDebugEnabled是log4j时代残留的用法,可以用slf4j的log.debug()代替。不过也有很多地方,直接去掉ifDebugEnabled的话,是会降低性能的。

That requires obtaining the Fully Qualified Class Name (FQCN) of each class and passing it as a parameter to LogUtils, which is not a good approach for us.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are many places where the usage of ifDebugEnabled is a remnant from the log4j era, which can be replaced with log.debug() from slf4j. However, in many cases, removing the ifDebugEnabled directly would result in a performance decrease.

To be precise it is a remnant of the Log4j 1.x/JCL era. Since the release of SLF4J in 2005 these guards are not necessary. The Log4j 2.x API (2014) works the same way as SLF4J.

That requires obtaining the Fully Qualified Class Name (FQCN) of each class and passing it as a parameter to LogUtils, which is not a good approach for us.

Probably my explanations were not clear. The FQCN to use is that of the LogUtils class, i.e. "org.apache.eventmesh.common.utils.LogUtils". The logging backend will look into the stack for the class that called LogUtils.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Better performance

Regarding "better performance", the code here does not have the same situation as the example you provided.

However, in many cases, removing the ifDebugEnabled directly would result in a performance decrease.

Could you provide some examples to illustrate the performance decrease after removing the ifDebugEnabled you mentioned here?
Also, I don't quite understand what you mean by "removing the ifDebugEnabled". What is the relationship between log.debug() internal supporting for determining log level and "removing the ifDebugEnabled"?

That requires obtaining the Fully Qualified Class Name (FQCN) of each class and passing it as a parameter to LogUtils

The fact seems to be different.


However, in many cases, removing the ifDebugEnabled directly would result in a performance decrease.

关于“性能更好”,这里的代码不存在您所举例的情况。

However, in many cases, removing the ifDebugEnabled directly would result in a performance decrease.

能否列举一些情况说明一下您这句所说的性能降低的情况?
另外,我不太明白您说的“removing the ifDebugEnabled”。log.debug()内部已经支持判断日志级别,这和“removing the ifDebugEnabled”有什么关系?

That requires obtaining the Fully Qualified Class Name (FQCN) of each class and passing it as a parameter to LogUtils

好像并非如此。

Copy link
Member Author

@Pil0tXia Pil0tXia Dec 30, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pandaapo

removing the ifDebugEnabled

From:

            if (log.isDebugEnabled()) {
                log.debug("Encoder pkg={}", JsonUtils.toJSONString(pkg));
            }

To:

           log.debug("Encoder pkg={}", JsonUtils.toJSONString(pkg));

Even if the log level is set to "info", the latter will still invoke and execute toJSONString, whereas the former will not.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Pil0tXia
So, you were referring to the situation you initially gave as an example, rather than the case of this line of reviewed code.

原来也是指最开始您所举例的情形,而非这行被review代码的情形。

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里的性能会更好,应该还是部分特殊的情况(适用于能够懒加载的情况),既然LogUtils能解决日志代码行显示的问题,我觉得也可以采用LogUtils统一封装一下,这样在编码风格上也能有一定的统一。


for (Map.Entry<String, WatchFileTask> entry : WATCH_FILE_TASK_MAP.entrySet()) {
LogUtils.info(log, "[WatchFileManager] start to shutdown : {}", entry.getKey());
log.atInfo().log("[WatchFileManager] start to shutdown : {}", entry.getKey());

try {
entry.getValue().shutdown();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import org.apache.eventmesh.common.protocol.tcp.Subscription;
import org.apache.eventmesh.common.protocol.tcp.UserAgent;
import org.apache.eventmesh.common.utils.JsonUtils;
import org.apache.eventmesh.common.utils.LogUtils;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
Expand All @@ -39,7 +38,6 @@
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.ReplayingDecoder;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Preconditions;

Expand Down Expand Up @@ -161,7 +159,7 @@ private Header parseHeader(ByteBuf in, int headerLength) throws JsonProcessingEx
}
final byte[] headerData = new byte[headerLength];
in.readBytes(headerData);
LogUtils.debug(log, "Decode headerJson={}", deserializeBytes(headerData));
log.atDebug().log("Decode headerJson={}", deserializeBytes(headerData));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
log.atDebug().log("Decode headerJson={}", deserializeBytes(headerData));
log.atDebug().addArgument(() -> deserializeBytes(headerData)).log("Decode headerJson={}");

Since the purpose of your PR is to prevent expensive computations of disabled log statement arguments, you should use a lambda here.

Copy link
Member Author

@Pil0tXia Pil0tXia Dec 30, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True🤣I tested it with the code below, and the timer shows that only Supplier could avoid executing formatMsg(). However the Fluent API said that For disabled log levels, the returned LoggingEventBuilder instance does nothing. Why is that?

Test code, ran under debug level:

        ......
        long traceStart = System.currentTimeMillis();
        log.trace("log.trace(). formatMsg() return value: {}", formatMsg("log.trace()", "executed"));
        long traceEnd = System.currentTimeMillis();
        long atTraceStart = System.currentTimeMillis();
        log.atTrace().log("log.atTrace().log(). formatMsg() return value: {}", formatMsg("log.atTrace().log()", "executed"));
        long atTraceEnd = System.currentTimeMillis();
        long atTraceSupplierStart = System.currentTimeMillis();
        log.atTrace().addArgument(() -> formatMsg("log.atTrace() Supplier", "executed")).log("log.atTrace().addArgument().log()");
        long atTraceSupplierEnd = System.currentTimeMillis();
        log.info("log.trace() cost: {}ms, log.atTrace().log() cost: {}ms, log.atTrace() Supplier cost: {}ms",
                traceEnd - traceStart, atTraceEnd - atTraceStart, atTraceSupplierEnd - atTraceSupplierStart);
    }

    private String formatMsg(String name, String status) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return name + "-" + status;
    }

Output:

log.trace() cost: 1009ms, log.atTrace().log() cost: 1002ms, log.atTrace() Supplier cost: 0ms

addArgument is really inconvenient; it is less convenient than using ifDebugEnabled.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True🤣I tested it with the code below, and the timer shows that only Supplier could avoid executing formatMsg(). However the Fluent API said that For disabled log levels, the returned LoggingEventBuilder instance does nothing. Why is that?

This is due to the order in which Java evaluates methods: it always evaluates the arguments of a method before the method itself. In this concrete example:

log.atDebug().log("Decode headerJson={}", deserializeBytes(headerData));

Java will:

  1. Call Logger#atDebug() and obtain a NOPLoggingEventBuilder,
  2. Call deserializeBytes and obtain a string,
  3. Call NOPLoggingEventBuilder#log which does nothing.

The Scala language has call-by-name arguments that are evaluated only if they are used. In Java everything is call-by-value and the arguments are computed even if they are not used.

return JsonUtils.parseObject(headerData, Header.class);
}

Expand All @@ -171,7 +169,7 @@ private Object parseBody(ByteBuf in, Header header, int bodyLength) throws JsonP
}
final byte[] bodyData = new byte[bodyLength];
in.readBytes(bodyData);
LogUtils.debug(log, "Decode bodyJson={}", deserializeBytes(bodyData));
log.atDebug().log("Decode bodyJson={}", deserializeBytes(bodyData));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
log.atDebug().log("Decode bodyJson={}", deserializeBytes(bodyData));
log.atDebug().addArgument(() -> deserializeBytes(bodyData)).log("Decode bodyJson={}");

Same as above.

return deserializeBody(deserializeBytes(bodyData), header);
}

Expand Down Expand Up @@ -223,7 +221,7 @@ private static Object deserializeBody(String bodyJsonString, Header header) thro
case REDIRECT_TO_CLIENT:
return JsonUtils.parseObject(bodyJsonString, RedirectInfo.class);
default:
LogUtils.warn(log, "Invalidate TCP command: {}", command);
log.warn("Invalidate TCP command: {}", command);
return null;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
configurations {
implementation.exclude group: 'ch.qos.logback', module: 'logback-classic'
implementation.exclude group: 'log4j', module: 'log4j'
implementation.exclude group: 'org.apache.logging.log4j', module: 'log4j-to-slf4j'
testImplementation.exclude group: 'org.apache.logging.log4j', module: 'log4j-to-slf4j'
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ dependencies {
api "org.slf4j:slf4j-api"
implementation "org.apache.logging.log4j:log4j-api"
implementation "org.apache.logging.log4j:log4j-core"
implementation "org.apache.logging.log4j:log4j-slf4j-impl"
implementation "org.apache.logging.log4j:log4j-slf4j2-impl"

implementation "com.fasterxml.jackson.core:jackson-databind"
implementation "com.fasterxml.jackson.core:jackson-core"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ dependencies {
api "org.slf4j:slf4j-api"
implementation "org.apache.logging.log4j:log4j-api"
implementation "org.apache.logging.log4j:log4j-core"
implementation "org.apache.logging.log4j:log4j-slf4j-impl"
implementation "org.apache.logging.log4j:log4j-slf4j2-impl"

implementation "com.fasterxml.jackson.core:jackson-databind"
implementation "com.fasterxml.jackson.core:jackson-core"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ dependencies {
api "org.slf4j:slf4j-api"
implementation "org.apache.logging.log4j:log4j-api"
implementation "org.apache.logging.log4j:log4j-core"
implementation "org.apache.logging.log4j:log4j-slf4j-impl"
implementation "org.apache.logging.log4j:log4j-slf4j2-impl"

compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
Expand Down
10 changes: 5 additions & 5 deletions tools/dependency-check/known-dependencies.txt
Original file line number Diff line number Diff line change
Expand Up @@ -142,10 +142,10 @@ jsr305-3.0.2.jar
jul-to-slf4j-1.7.33.jar
kafka-clients-3.0.0.jar
listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar
log4j-api-2.17.1.jar
log4j-core-2.17.1.jar
log4j-slf4j-impl-2.17.1.jar
log4j-to-slf4j-2.17.1.jar
log4j-api-2.22.1.jar
log4j-core-2.22.1.jar
log4j-slf4j2-impl-2.22.1.jar
log4j-slf4j-impl-2.22.1.jar
logback-classic-1.2.10.jar
logback-core-1.2.10.jar
lz4-java-1.7.1.jar
Expand Down Expand Up @@ -302,7 +302,7 @@ simpleclient_httpserver-0.8.1.jar
slack-api-client-1.1.6.jar
slack-api-model-1.1.6.jar
slack-app-backend-1.1.6.jar
slf4j-api-1.7.30.jar
slf4j-api-2.0.9.jar
snakeyaml-1.30.jar
snappy-java-1.1.8.1.jar
spring-aop-5.3.15.jar
Expand Down
10 changes: 5 additions & 5 deletions tools/third-party-licenses/LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -287,10 +287,10 @@ The text of each license is also included at licenses/LICENSE-[project].txt.
jetcd-resolver 0.3.0: https://github.com/etcd-io/jetcd, Apache 2.0
jna 4.2.2: https://github.com/java-native-access/jna, Apache 2.0
kafka-clients 3.0.0: https://github.com/apache/kafka, Apache 2.0
log4j-api 2.17.1: https://github.com/apache/logging-log4j2, Apache 2.0
log4j-core 2.17.1: https://github.com/apache/logging-log4j2, Apache 2.0
log4j-slf4j-impl 2.17.1: https://github.com/apache/logging-log4j2, Apache 2.0
log4j-to-slf4j 2.17.1: https://github.com/apache/logging-log4j2, Apache 2.0
log4j-api 2.22.1: https://github.com/apache/logging-log4j2, Apache 2.0
log4j-core 2.22.1: https://github.com/apache/logging-log4j2, Apache 2.0
log4j-slf4j2-impl 2.22.1: https://github.com/apache/logging-log4j2, Apache 2.0
log4j-slf4j-impl 2.22.1: https://github.com/apache/logging-log4j2, Apache 2.0
metrics-annotation 4.1.0: https://github.com/dropwizard/metrics, Apache 2.0
metrics-core 4.1.0: https://github.com/dropwizard/metrics, Apache 2.0
metrics-healthchecks 4.1.0: https://github.com/dropwizard/metrics, Apache 2.0
Expand Down Expand Up @@ -467,7 +467,7 @@ The text of each license is also included at licenses/LICENSE-[project].txt.
bcutil-jdk15on 1.69: https://github.com/bcgit/bc-java, MIT
checker-qual 3.12.0: https://github.com/typetools/checker-framework, MIT
reactive-streams 1.0.3: https://github.com/reactive-streams/reactive-streams-jvm, MIT
slf4j-api 1.7.30: https://github.com/qos-ch/slf4j, MIT
slf4j-api 2.0.9: https://github.com/qos-ch/slf4j, MIT

========================================================================
BSD-3-Clause licenses
Expand Down