diff --git a/.github/workflows/build-and-test-pr.yml b/.github/workflows/build-and-test-pr.yml index 32c485cf2e..2d76db5fc8 100644 --- a/.github/workflows/build-and-test-pr.yml +++ b/.github/workflows/build-and-test-pr.yml @@ -141,7 +141,7 @@ jobs: timeout-minutes: 70 run: ./mvnw --batch-mode --no-snapshot-updates -e --no-transfer-progress --fail-fast clean test verify -Pjacoco -Dmaven.wagon.httpconnectionManager.ttlSeconds=120 -Dmaven.wagon.http.retryHandler.count=5 -DskipTests=false -DskipIntegrationTests=false -Dcheckstyle.skip=false -Dcheckstyle_unix.skip=false -Drat.skip=false -Dmaven.javadoc.skip=true -DembeddedZookeeperPath=${{ github.workspace }}/.tmp/zookeeper - name: "Upload coverage to Codecov" - uses: codecov/codecov-action@v1 + uses: codecov/codecov-action@v3 integration-test-prepare: runs-on: ubuntu-latest diff --git a/.github/workflows/build-and-test-scheduled-3.0.yml b/.github/workflows/build-and-test-scheduled-3.0.yml index 5cf10ee2a2..b8dedaeb59 100644 --- a/.github/workflows/build-and-test-scheduled-3.0.yml +++ b/.github/workflows/build-and-test-scheduled-3.0.yml @@ -161,7 +161,7 @@ jobs: if: ${{ startsWith( matrix.os, 'windows') }} run: ./mvnw --batch-mode --no-snapshot-updates -e --no-transfer-progress --fail-fast clean test verify -Pjacoco -D"http.keepAlive=false" -D"maven.wagon.http.pool=false" -D"maven.wagon.httpconnectionManager.ttlSeconds=120" -D"maven.wagon.http.retryHandler.count=5" -DskipTests=false -DskipIntegrationTests=true -D"checkstyle.skip=false" -D"checkstyle_unix.skip=true" -D"rat.skip=false" -D"maven.javadoc.skip=true" -D"embeddedZookeeperPath=${{ github.workspace }}/.tmp/zookeeper" - name: "Upload coverage to Codecov" - uses: codecov/codecov-action@v1 + uses: codecov/codecov-action@v3 integration-test-prepare: runs-on: ubuntu-latest diff --git a/.github/workflows/build-and-test-scheduled-3.1.yml b/.github/workflows/build-and-test-scheduled-3.1.yml index 0188237e0c..8b134b168f 100644 --- a/.github/workflows/build-and-test-scheduled-3.1.yml +++ b/.github/workflows/build-and-test-scheduled-3.1.yml @@ -171,7 +171,7 @@ jobs: if: ${{ startsWith( matrix.os, 'windows') }} run: ./mvnw --batch-mode --no-snapshot-updates -e --no-transfer-progress --fail-fast clean test verify -Pjacoco -D"http.keepAlive=false" -D"maven.wagon.http.pool=false" -D"maven.wagon.httpconnectionManager.ttlSeconds=120" -D"maven.wagon.http.retryHandler.count=5" -DskipTests=false -DskipIntegrationTests=true -D"checkstyle.skip=false" -D"checkstyle_unix.skip=true" -D"rat.skip=false" -D"maven.javadoc.skip=true" -D"embeddedZookeeperPath=${{ github.workspace }}/.tmp/zookeeper" - name: "Upload coverage to Codecov" - uses: codecov/codecov-action@v1 + uses: codecov/codecov-action@v3 unit-test-fastjson2: needs: [build-source, unit-test-prepare] @@ -211,7 +211,7 @@ jobs: if: ${{ startsWith( matrix.os, 'windows') }} run: ./mvnw --batch-mode --no-snapshot-updates -e --no-transfer-progress --fail-fast clean test verify -Pjacoco -D"http.keepAlive=false" -D"maven.wagon.http.pool=false" -D"maven.wagon.httpconnectionManager.ttlSeconds=120" -D"maven.wagon.http.retryHandler.count=5" -DskipTests=false -DskipIntegrationTests=true -D"checkstyle.skip=false" -D"checkstyle_unix.skip=true" -D"rat.skip=false" -D"maven.javadoc.skip=true" -D"embeddedZookeeperPath=${{ github.workspace }}/.tmp/zookeeper" - name: "Upload coverage to Codecov" - uses: codecov/codecov-action@v1 + uses: codecov/codecov-action@v3 integration-test-prepare: runs-on: ubuntu-latest diff --git a/.github/workflows/build-and-test-scheduled-3.2.yml b/.github/workflows/build-and-test-scheduled-3.2.yml index a43e7b769d..c7dddc0c1d 100644 --- a/.github/workflows/build-and-test-scheduled-3.2.yml +++ b/.github/workflows/build-and-test-scheduled-3.2.yml @@ -171,7 +171,7 @@ jobs: if: ${{ startsWith( matrix.os, 'windows') }} run: ./mvnw --batch-mode --no-snapshot-updates -e --no-transfer-progress --fail-fast clean test verify -Pjacoco -D"http.keepAlive=false" -D"maven.wagon.http.pool=false" -D"maven.wagon.httpconnectionManager.ttlSeconds=120" -D"maven.wagon.http.retryHandler.count=5" -DskipTests=false -DskipIntegrationTests=true -D"checkstyle.skip=false" -D"checkstyle_unix.skip=true" -D"rat.skip=false" -D"maven.javadoc.skip=true" -D"embeddedZookeeperPath=${{ github.workspace }}/.tmp/zookeeper" - name: "Upload coverage to Codecov" - uses: codecov/codecov-action@v1 + uses: codecov/codecov-action@v3 unit-test-fastjson2: needs: [build-source, unit-test-prepare] @@ -211,7 +211,7 @@ jobs: if: ${{ startsWith( matrix.os, 'windows') }} run: ./mvnw --batch-mode --no-snapshot-updates -e --no-transfer-progress --fail-fast clean test verify -Pjacoco -D"http.keepAlive=false" -D"maven.wagon.http.pool=false" -D"maven.wagon.httpconnectionManager.ttlSeconds=120" -D"maven.wagon.http.retryHandler.count=5" -DskipTests=false -DskipIntegrationTests=true -D"checkstyle.skip=false" -D"checkstyle_unix.skip=true" -D"rat.skip=false" -D"maven.javadoc.skip=true" -D"embeddedZookeeperPath=${{ github.workspace }}/.tmp/zookeeper" - name: "Upload coverage to Codecov" - uses: codecov/codecov-action@v1 + uses: codecov/codecov-action@v3 integration-test-prepare: runs-on: ubuntu-latest diff --git a/.github/workflows/release-test-3.1.yml b/.github/workflows/release-test-3.1.yml index ce48afe905..fdab232bfc 100644 --- a/.github/workflows/release-test-3.1.yml +++ b/.github/workflows/release-test-3.1.yml @@ -23,25 +23,26 @@ env: jobs: license: - runs-on: ubuntu-20.04 + runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: Check License uses: apache/skywalking-eyes@main env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} build-source: - runs-on: ubuntu-20.04 + runs-on: ubuntu-latest outputs: version: ${{ steps.dubbo-version.outputs.version }} steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 with: path: dubbo - - uses: actions/setup-java@v1 + - uses: actions/setup-java@v3 with: + distribution: 'zulu' java-version: 8 - - uses: actions/cache@v2 + - uses: actions/cache@v3 name: "Cache local Maven repository" with: path: ~/.m2/repository @@ -50,7 +51,7 @@ jobs: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} ${{ runner.os }}-maven- - name: "Dubbo cache" - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: ~/.m2/repository/org/apache/dubbo key: ${{ runner.os }}-dubbo-snapshot-${{ github.sha }}-${{ github.run_id }} @@ -80,7 +81,7 @@ jobs: id: dubbo-version run: | REVISION=`awk '/[^<]+<\/revision>/{gsub(/|<\/revision>/,"",$1);print $1;exit;}' ./dubbo/pom.xml` - echo "::set-output name=version::$REVISION" + echo "version=$REVISION" >> $GITHUB_OUTPUT echo "dubbo version: $REVISION" unit-test-prepare: @@ -89,11 +90,11 @@ jobs: strategy: fail-fast: false matrix: - os: [ ubuntu-20.04, windows-2019 ] + os: [ ubuntu-latest, windows-latest ] env: ZOOKEEPER_VERSION: 3.6.3 steps: - - uses: actions/cache@v2 + - uses: actions/cache@v3 name: "Cache zookeeper binary archive" id: "cache-zookeeper" with: @@ -139,17 +140,18 @@ jobs: strategy: fail-fast: false matrix: - os: [ ubuntu-20.04, windows-2019 ] + os: [ ubuntu-latest, windows-latest ] jdk: [ 8, 11, 17, 19 ] env: DISABLE_FILE_SYSTEM_TEST: true steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: "Set up JDK ${{ matrix.jdk }}" - uses: actions/setup-java@v1 + uses: actions/setup-java@v3 with: java-version: ${{ matrix.jdk }} - - uses: actions/cache@v2 + distribution: 'zulu' + - uses: actions/cache@v3 name: "Cache local Maven repository" with: path: ~/.m2/repository @@ -166,7 +168,7 @@ jobs: if: ${{ startsWith( matrix.os, 'windows') }} run: ./mvnw --batch-mode --no-snapshot-updates -e --no-transfer-progress --fail-fast clean test verify -Pjacoco -D"http.keepAlive=false" -D"maven.wagon.http.pool=false" -D"maven.wagon.httpconnectionManager.ttlSeconds=120" -D"maven.wagon.http.retryHandler.count=5" -DskipTests=false -DskipIntegrationTests=true -D"checkstyle.skip=false" -D"checkstyle_unix.skip=true" -D"rat.skip=false" -D"maven.javadoc.skip=true" -D"embeddedZookeeperPath=${{ github.workspace }}/.tmp/zookeeper" - name: "Upload coverage to Codecov" - uses: codecov/codecov-action@v1 + uses: codecov/codecov-action@v3 unit-test-fastjson2: needs: [build-source, unit-test-prepare] @@ -175,19 +177,20 @@ jobs: strategy: fail-fast: false matrix: - os: [ ubuntu-20.04, windows-2019 ] + os: [ ubuntu-latest, windows-latest ] jdk: [ 8, 11, 17, 19 ] env: DISABLE_FILE_SYSTEM_TEST: true DUBBO_DEFAULT_SERIALIZATION: fastjson2 MAVEN_SUREFIRE_ADD_OPENS: true steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: "Set up JDK ${{ matrix.jdk }}" - uses: actions/setup-java@v1 + uses: actions/setup-java@v3 with: + distribution: 'zulu' java-version: ${{ matrix.jdk }} - - uses: actions/cache@v2 + - uses: actions/cache@v3 name: "Cache local Maven repository" with: path: ~/.m2/repository @@ -204,14 +207,14 @@ jobs: if: ${{ startsWith( matrix.os, 'windows') }} run: ./mvnw --batch-mode --no-snapshot-updates -e --no-transfer-progress --fail-fast clean test verify -Pjacoco -D"http.keepAlive=false" -D"maven.wagon.http.pool=false" -D"maven.wagon.httpconnectionManager.ttlSeconds=120" -D"maven.wagon.http.retryHandler.count=5" -DskipTests=false -DskipIntegrationTests=true -D"checkstyle.skip=false" -D"checkstyle_unix.skip=true" -D"rat.skip=false" -D"maven.javadoc.skip=true" -D"embeddedZookeeperPath=${{ github.workspace }}/.tmp/zookeeper" - name: "Upload coverage to Codecov" - uses: codecov/codecov-action@v1 + uses: codecov/codecov-action@v3 integration-test-prepare: - runs-on: ubuntu-20.04 + runs-on: ubuntu-latest env: JOB_COUNT: 3 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 with: repository: 'apache/dubbo-samples' ref: master @@ -226,8 +229,8 @@ jobs: integration-test-job: needs: [build-source, integration-test-prepare] - name: "Integration Test on ubuntu-20.04 (JobId: ${{matrix.job_id}})" - runs-on: ubuntu-20.04 + name: "Integration Test on ubuntu-latest (JobId: ${{matrix.job_id}})" + runs-on: ubuntu-latest timeout-minutes: 30 env: JAVA_VER: 8 @@ -237,12 +240,12 @@ jobs: matrix: job_id: [1, 2, 3] steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 with: repository: 'apache/dubbo-samples' ref: master - name: "Cache local Maven repository" - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: ~/.m2/repository key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}-${{ github.run_id }} @@ -250,7 +253,7 @@ jobs: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} ${{ runner.os }}-maven- - name: "Restore Dubbo cache" - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: ~/.m2/repository/org/apache/dubbo key: ${{ runner.os }}-dubbo-snapshot-${{ github.sha }}-${{ github.run_id }} @@ -263,9 +266,10 @@ jobs: name: test-list path: test/jobs/ - name: "Set up JDK 8" - uses: actions/setup-java@v1 + uses: actions/setup-java@v3 with: java-version: 8 + distribution: 'zulu' - name: "Init Candidate Versions" run: | DUBBO_VERSION="${{needs.build-source.outputs.version}}" @@ -286,11 +290,11 @@ jobs: integration-test-result: needs: [integration-test-job] if: always() - runs-on: ubuntu-20.04 + runs-on: ubuntu-latest env: JAVA_VER: 8 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 with: repository: 'apache/dubbo-samples' ref: master @@ -306,20 +310,21 @@ jobs: error-code-inspecting: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 with: path: "./dubbo" - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 with: repository: 'apache/dubbo-test-tools' ref: main path: "./dubbo-test-tools" - name: "Set up JDK 17" - uses: actions/setup-java@v1 + uses: actions/setup-java@v3 with: java-version: 17 + distribution: 'zulu' - name: "Compile Dubbo (Linux)" run: | diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/FilterChainBuilder.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/FilterChainBuilder.java index 00215ab02a..7b2c284930 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/FilterChainBuilder.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/FilterChainBuilder.java @@ -35,7 +35,7 @@ import org.apache.dubbo.rpc.cluster.Directory; import java.util.List; import java.util.stream.Collectors; -import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_ASYN_INVOKE_FAILED; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_EXECUTE_FILTER_EXCEPTION; import static org.apache.dubbo.common.extension.ExtensionScope.APPLICATION; @SPI(value = "default", scope = APPLICATION) @@ -221,7 +221,7 @@ public interface FilterChainBuilder { } } } catch (RuntimeException runtimeException) { - LOGGER.error(CLUSTER_ASYN_INVOKE_FAILED,"asyn Invoke exception","",String.format("Exception occurred while executing the %s filter named %s.", i, filter.getClass().getSimpleName()),runtimeException); + LOGGER.error(CLUSTER_EXECUTE_FILTER_EXCEPTION, "the custom filter is abnormal", "", String.format("Exception occurred while executing the %s filter named %s.", i, filter.getClass().getSimpleName())); if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("Whole filter list is: %s", filters.stream().map(tmpFilter -> tmpFilter.getClass().getSimpleName()).collect(Collectors.toList()))); } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java index 15c7066e06..8604def436 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java @@ -28,6 +28,7 @@ import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; /** @@ -96,15 +97,21 @@ public class ConsistentHashLoadBalance extends AbstractLoadBalance { } public Invoker select(Invocation invocation) { - String key = toKey(invocation.getArguments()); + boolean isGeneric = invocation.getMethodName().equals($INVOKE); + String key = toKey(invocation.getArguments(),isGeneric); + byte[] digest = Bytes.getMD5(key); return selectForKey(hash(digest, 0)); } + private String toKey(Object[] args, boolean isGeneric) { + return isGeneric ? toKey((Object[]) args[1]) : toKey(args); + } + private String toKey(Object[] args) { StringBuilder buf = new StringBuilder(); for (int i : argumentIndex) { - if (i >= 0 && i < args.length) { + if (i >= 0 && args != null && i < args.length) { buf.append(args[i]); } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java index ceb97a7488..bdd2ddd6d2 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java @@ -41,7 +41,7 @@ import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; -import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_ASYN_INVOKE_FAILED; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_GROUP_MERGE; import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; import static org.apache.dubbo.rpc.Constants.MERGER_KEY; @@ -102,8 +102,8 @@ public class MergeableClusterInvoker extends AbstractClusterInvoker { try { Result r = asyncResult.get(Integer.MAX_VALUE, TimeUnit.MILLISECONDS); if (r.hasException()) { - log.error(CLUSTER_ASYN_INVOKE_FAILED,"asyn Invoke exception","","Invoke " + getGroupDescFromServiceKey(entry.getKey()) + - " failed: " + r.getException().getMessage(),r.getException()); + log.error(CLUSTER_FAILED_GROUP_MERGE, "Invoke " + getGroupDescFromServiceKey(entry.getKey()) + + " failed: " + r.getException().getMessage(), "", r.getException().getMessage()); } else { resultList.add(r); } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalanceTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalanceTest.java index d9b78afd69..6d1381c993 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalanceTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalanceTest.java @@ -33,6 +33,34 @@ import java.util.concurrent.atomic.AtomicLong; @SuppressWarnings("rawtypes") public class ConsistentHashLoadBalanceTest extends LoadBalanceBaseTest { + @Test + public void testConsistentHashLoadBalanceInGenericCall() { + int runs = 10000; + Map genericInvokeCounter = getGenericInvokeCounter(runs, ConsistentHashLoadBalance.NAME); + Map invokeCounter = getInvokeCounter(runs, ConsistentHashLoadBalance.NAME); + + Invoker genericHitted = findHitted(genericInvokeCounter); + Invoker hitted = findHitted(invokeCounter); + + Assertions.assertEquals(hitted, + genericHitted, "hitted should equals to genericHitted"); + } + + private Invoker findHitted(Map invokerCounter) { + Invoker invoker = null; + + for (Map.Entry entry : invokerCounter.entrySet()) { + if (entry.getValue().longValue() > 0) { + invoker = entry.getKey(); + break; + } + } + + Assertions.assertNotNull(invoker,"invoker should be found"); + + return null; + } + @Test public void testConsistentHashLoadBalance() { int runs = 10000; diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java index c96c0fc391..cab69a1302 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java @@ -48,6 +48,7 @@ import static org.mockito.Mockito.mock; @SuppressWarnings({"unchecked", "rawtypes"}) public class LoadBalanceBaseTest { Invocation invocation; + Invocation genericInvocation; List> invokers = new ArrayList>(); Invoker invoker1; Invoker invoker2; @@ -79,6 +80,14 @@ public class LoadBalanceBaseTest { given(invocation.getMethodName()).willReturn("method1"); given(invocation.getArguments()).willReturn(new Object[] {"arg1","arg2","arg3"}); + genericInvocation = mock(Invocation.class); + String methodName = "method1"; + given(genericInvocation.getMethodName()).willReturn("$invoke"); + String[] paraTypes = new String[] {String.class.getName(),String.class.getName(),String.class.getName()}; + Object[] argsObject = new Object[] {"arg1","arg2","arg3"}; + Object[] args = new Object[] {methodName,paraTypes,argsObject}; + given(genericInvocation.getArguments()).willReturn(args); + invoker1 = mock(Invoker.class); invoker2 = mock(Invoker.class); invoker3 = mock(Invoker.class); @@ -132,6 +141,20 @@ public class LoadBalanceBaseTest { return counter; } + public Map getGenericInvokeCounter(int runs, String loadbalanceName) { + Map counter = new ConcurrentHashMap(); + LoadBalance lb = getLoadBalance(loadbalanceName); + for (Invoker invoker : invokers) { + counter.put(invoker, new AtomicLong(0)); + } + URL url = invokers.get(0).getUrl(); + for (int i = 0; i < runs; i++) { + Invoker sinvoker = lb.select(invokers, url, genericInvocation); + counter.get(sinvoker).incrementAndGet(); + } + return counter; + } + protected AbstractLoadBalance getLoadBalance(String loadbalanceName) { return (AbstractLoadBalance) ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(loadbalanceName); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Parameters.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Parameters.java index cdeaf29be4..711a64ea61 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Parameters.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Parameters.java @@ -17,7 +17,7 @@ package org.apache.dubbo.common; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; @@ -30,6 +30,7 @@ import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.HIDE_KEY_PREFIX; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; /** * Parameters for backward compatibility for version prior to 2.0.5 @@ -38,7 +39,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.HIDE_KEY_PREFIX; */ @Deprecated public class Parameters { - protected static final Logger logger = LoggerFactory.getLogger(Parameters.class); + protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(Parameters.class); private final Map parameters; public Parameters(String... pairs) { @@ -91,7 +92,7 @@ public class Parameters { try { value = URLDecoder.decode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { - logger.error(e.getMessage(), e); + logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", e.getMessage(), e); } } return value; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Version.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Version.java index ba78c46915..9f9a1d1e11 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Version.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Version.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.common; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.StringUtils; @@ -32,11 +32,13 @@ import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; + /** * Version */ public final class Version { - private static final Logger logger = LoggerFactory.getLogger(Version.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(Version.class); private static final Pattern PREFIX_DIGITS_PATTERN = Pattern.compile("^([0-9]*).*"); @@ -74,9 +76,10 @@ public final class Version { /** * Compare versions + * * @return the value {@code 0} if {@code version1 == version2}; - * a value less than {@code 0} if {@code version1 < version2}; and - * a value greater than {@code 0} if {@code version1 > version2} + * a value less than {@code 0} if {@code version1 < version2}; and + * a value greater than {@code 0} if {@code version1 > version2} */ public static int compare(String version1, String version2) { return Integer.compare(getIntVersion(version1), getIntVersion(version2)); @@ -131,9 +134,9 @@ public final class Version { v = v * 100; } } catch (Exception e) { - logger.warn("Please make sure your version value has the right format: " + - "\n 1. only contains digital number: 2.0.0; \n 2. with string suffix: 2.6.7-stable. " + - "\nIf you are using Dubbo before v2.6.2, the version value is the same with the jar version."); + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Please make sure your version value has the right format: " + + "\n 1. only contains digital number: 2.0.0; \n 2. with string suffix: 2.6.7-stable. " + + "\nIf you are using Dubbo before v2.6.2, the version value is the same with the jar version."); v = LEGACY_DUBBO_PROTOCOL_VERSION; } VERSION2INT.put(version, v); @@ -190,11 +193,11 @@ public final class Version { } URL location = codeSource.getLocation(); - if (location == null){ + if (location == null) { logger.info("No location for class " + cls.getName() + " when getVersion, use default version " + defaultVersion); return defaultVersion; } - String file = location.getFile(); + String file = location.getFile(); if (!StringUtils.isEmpty(file) && file.endsWith(".jar")) { version = getFromFile(file); } @@ -203,7 +206,7 @@ public final class Version { return StringUtils.isEmpty(version) ? defaultVersion : version; } catch (Throwable e) { // return default version when any exception is thrown - logger.error("return default version, ignore exception " + e.getMessage(), e); + logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", "return default version, ignore exception " + e.getMessage(), e); return defaultVersion; } } @@ -257,11 +260,11 @@ public final class Version { if (failOnError) { throw new IllegalStateException(error); } else { - logger.error(error); + logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", error); } } } catch (Throwable e) { - logger.error(e.getMessage(), e); + logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", e.getMessage(), e); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/beans/factory/ScopeBeanFactory.java b/dubbo-common/src/main/java/org/apache/dubbo/common/beans/factory/ScopeBeanFactory.java index bd58827d99..04448401a1 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/beans/factory/ScopeBeanFactory.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/beans/factory/ScopeBeanFactory.java @@ -21,7 +21,7 @@ import org.apache.dubbo.common.beans.support.InstantiationStrategy; import org.apache.dubbo.common.extension.ExtensionAccessor; import org.apache.dubbo.common.extension.ExtensionAccessorAware; import org.apache.dubbo.common.extension.ExtensionPostProcessor; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.Disposable; import org.apache.dubbo.common.utils.StringUtils; @@ -37,12 +37,14 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.stream.Collectors; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_DESTROY_INVOKER; + /** * A bean factory for internal sharing. */ public class ScopeBeanFactory { - protected static final Logger LOGGER = LoggerFactory.getLogger(ScopeBeanFactory.class); + protected static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(ScopeBeanFactory.class); private final ScopeBeanFactory parent; private ExtensionAccessor extensionAccessor; @@ -239,14 +241,14 @@ public class ScopeBeanFactory { } public void destroy() { - if (destroyed.compareAndSet(false, true)){ + if (destroyed.compareAndSet(false, true)) { for (BeanInfo beanInfo : registeredBeanInfos) { if (beanInfo.instance instanceof Disposable) { try { Disposable beanInstance = (Disposable) beanInfo.instance; beanInstance.destroy(); } catch (Throwable e) { - LOGGER.error("An error occurred when destroy bean [name=" + beanInfo.name + ", bean=" + beanInfo.instance + "]: " + e, e); + LOGGER.error(CONFIG_FAILED_DESTROY_INVOKER, "", "", "An error occurred when destroy bean [name=" + beanInfo.name + ", bean=" + beanInfo.instance + "]: " + e, e); } } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/CompositeConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/CompositeConfiguration.java index 34e775459a..1653e96134 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/CompositeConfiguration.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/CompositeConfiguration.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.common.config; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ArrayUtils; @@ -24,11 +24,13 @@ import java.util.Arrays; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_LOAD_ENV_VARIABLE; + /** * This is an abstraction specially customized for the sequence Dubbo retrieves properties. */ public class CompositeConfiguration implements Configuration { - private final Logger logger = LoggerFactory.getLogger(CompositeConfiguration.class); + private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CompositeConfiguration.class); /** * List holding all the configuration @@ -80,7 +82,7 @@ public class CompositeConfiguration implements Configuration { return value; } } catch (Exception e) { - logger.error("Error when trying to get value for key " + key + " from " + config + ", " + + logger.error(CONFIG_FAILED_LOAD_ENV_VARIABLE, "", "", "Error when trying to get value for key " + key + " from " + config + ", " + "will continue to try the next one."); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java index 6daeb9fdf3..eaca5a8dbb 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java @@ -20,7 +20,7 @@ package org.apache.dubbo.common.config; import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory; import org.apache.dubbo.common.extension.ExtensionAccessor; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; @@ -44,6 +44,7 @@ import java.util.Set; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_SECONDS_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; /** * Utilities for manipulating configurations from different sources @@ -57,7 +58,7 @@ public final class ConfigurationUtils { throw new UnsupportedOperationException("No instance of 'ConfigurationUtils' for you! "); } - private static final Logger logger = LoggerFactory.getLogger(ConfigurationUtils.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ConfigurationUtils.class); private static final List securityKey; static { @@ -108,6 +109,7 @@ public final class ConfigurationUtils { /** * Server shutdown wait timeout mills + * * @return */ @SuppressWarnings("deprecation") @@ -172,30 +174,30 @@ public final class ConfigurationUtils { public static Map parseProperties(String content) throws IOException { Map map = new HashMap<>(); if (StringUtils.isEmpty(content)) { - logger.warn("Config center was specified, but no config item found."); + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Config center was specified, but no config item found."); } else { Properties properties = new Properties(); properties.load(new StringReader(content)); properties.stringPropertyNames().forEach( - k -> { - boolean deny = false; - for (String key : securityKey) { - if (k.contains(key)) { - deny = true; - break; - } + k -> { + boolean deny = false; + for (String key : securityKey) { + if (k.contains(key)) { + deny = true; + break; } - if (!deny) { - map.put(k, properties.getProperty(k)); - } - }); + } + if (!deny) { + map.put(k, properties.getProperty(k)); + } + }); } return map; } public static boolean isEmptyValue(Object value) { return value == null || - value instanceof String && StringUtils.isBlank((String) value); + value instanceof String && StringUtils.isBlank((String) value); } /** @@ -212,6 +214,7 @@ public final class ConfigurationUtils { * props: {"name": "dubbo", "port" : "1234"} * * + * * @param configMaps * @param prefix * @param @@ -239,11 +242,11 @@ public final class ConfigurationUtils { } if (CollectionUtils.isNotEmptyMap(configMap)) { - Map copy ; - synchronized (configMap){ + Map copy; + synchronized (configMap) { copy = new HashMap<>(configMap); } - for(Map.Entry entry : copy.entrySet()) { + for (Map.Entry entry : copy.entrySet()) { String key = entry.getKey(); V val = entry.getValue(); if (StringUtils.startsWithIgnoreCase(key, prefix) @@ -280,8 +283,8 @@ public final class ConfigurationUtils { if (!prefix.endsWith(".")) { prefix += "."; } - Map copy ; - synchronized (configMap){ + Map copy; + synchronized (configMap) { copy = new HashMap<>(configMap); } for (Map.Entry entry : copy.entrySet()) { @@ -319,8 +322,8 @@ public final class ConfigurationUtils { } Set ids = new LinkedHashSet<>(); for (Map configMap : configMaps) { - Map copy ; - synchronized (configMap){ + Map copy; + synchronized (configMap) { copy = new HashMap<>(configMap); } for (Map.Entry entry : copy.entrySet()) { @@ -357,6 +360,7 @@ public final class ConfigurationUtils { /** * For compact single instance + * * @deprecated Replaced to {@link ConfigurationUtils#getSystemConfiguration(ScopeModel)} */ @Deprecated @@ -366,6 +370,7 @@ public final class ConfigurationUtils { /** * For compact single instance + * * @deprecated Replaced to {@link ConfigurationUtils#getEnvConfiguration(ScopeModel)} */ @Deprecated @@ -375,6 +380,7 @@ public final class ConfigurationUtils { /** * For compact single instance + * * @deprecated Replaced to {@link ConfigurationUtils#getGlobalConfiguration(ScopeModel)} */ @Deprecated @@ -384,6 +390,7 @@ public final class ConfigurationUtils { /** * For compact single instance + * * @deprecated Replaced to {@link ConfigurationUtils#getDynamicGlobalConfiguration(ScopeModel)} */ @Deprecated @@ -393,6 +400,7 @@ public final class ConfigurationUtils { /** * For compact single instance + * * @deprecated Replaced to {@link ConfigurationUtils#getCachedDynamicProperty(ScopeModel, String, String)} */ @Deprecated @@ -402,6 +410,7 @@ public final class ConfigurationUtils { /** * For compact single instance + * * @deprecated Replaced to {@link ConfigurationUtils#getDynamicProperty(ScopeModel, String)} */ @Deprecated @@ -411,6 +420,7 @@ public final class ConfigurationUtils { /** * For compact single instance + * * @deprecated Replaced to {@link ConfigurationUtils#getDynamicProperty(ScopeModel, String, String)} */ @Deprecated @@ -420,6 +430,7 @@ public final class ConfigurationUtils { /** * For compact single instance + * * @deprecated Replaced to {@link ConfigurationUtils#getProperty(ScopeModel, String)} */ @Deprecated @@ -429,6 +440,7 @@ public final class ConfigurationUtils { /** * For compact single instance + * * @deprecated Replaced to {@link ConfigurationUtils#getProperty(ScopeModel, String, String)} */ @Deprecated @@ -438,6 +450,7 @@ public final class ConfigurationUtils { /** * For compact single instance + * * @deprecated Replaced to {@link ConfigurationUtils#get(ScopeModel, String, int)} */ @Deprecated diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/Environment.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/Environment.java index 103094051d..de7ec54b9a 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/Environment.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/Environment.java @@ -21,7 +21,7 @@ import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.context.ApplicationExt; import org.apache.dubbo.common.context.LifecycleAdapter; import org.apache.dubbo.common.extension.DisableInject; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.StringUtils; @@ -35,8 +35,10 @@ import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; + public class Environment extends LifecycleAdapter implements ApplicationExt { - private static final Logger logger = LoggerFactory.getLogger(Environment.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(Environment.class); public static final String NAME = "environment"; @@ -160,6 +162,7 @@ public class Environment extends LifecycleAdapter implements ApplicationExt { /** * Merge target map properties into app configuration + * * @param map */ public void updateAppConfigMap(Map map) { @@ -215,6 +218,7 @@ public class Environment extends LifecycleAdapter implements ApplicationExt { /** * Get configuration map list for target instance + * * @param config * @param prefix * @return @@ -238,6 +242,7 @@ public class Environment extends LifecycleAdapter implements ApplicationExt { /** * Get global configuration as map list + * * @return */ public List> getConfigurationMaps() { @@ -263,7 +268,7 @@ public class Environment extends LifecycleAdapter implements ApplicationExt { try { defaultDynamicConfiguration.close(); } catch (Exception e) { - logger.warn("close dynamic configuration failed: " + e.getMessage(), e); + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "close dynamic configuration failed: " + e.getMessage(), e); } defaultDynamicConfiguration = null; } @@ -322,7 +327,7 @@ public class Environment extends LifecycleAdapter implements ApplicationExt { if (defaultDynamicGlobalConfiguration == null) { if (defaultDynamicConfiguration == null) { if (logger.isWarnEnabled()) { - logger.warn("dynamicConfiguration is null , return globalConfiguration."); + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "dynamicConfiguration is null , return globalConfiguration."); } return getConfiguration(); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/ModuleEnvironment.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/ModuleEnvironment.java index dbf2ba2794..db532150d3 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/ModuleEnvironment.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/ModuleEnvironment.java @@ -19,7 +19,7 @@ package org.apache.dubbo.common.config; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.context.ModuleExt; import org.apache.dubbo.common.extension.DisableInject; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.AbstractConfig; import org.apache.dubbo.rpc.model.ModuleModel; @@ -29,11 +29,13 @@ import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; + public class ModuleEnvironment extends Environment implements ModuleExt { // delegate - private static final Logger logger = LoggerFactory.getLogger(ModuleEnvironment.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ModuleEnvironment.class); public static final String NAME = "moduleEnvironment"; @@ -97,7 +99,7 @@ public class ModuleEnvironment extends Environment implements ModuleExt { if (dynamicGlobalConfiguration == null) { if (dynamicConfiguration == null) { if (logger.isWarnEnabled()) { - logger.warn("dynamicConfiguration is null , return globalConfiguration."); + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "dynamicConfiguration is null , return globalConfiguration."); } return getConfiguration(); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfiguration.java index 164372d081..afd1cac989 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfiguration.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfiguration.java @@ -30,6 +30,7 @@ import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; /** * The abstract implementation of {@link DynamicConfiguration} @@ -88,14 +89,14 @@ public abstract class AbstractDynamicConfiguration implements DynamicConfigurati protected AbstractDynamicConfiguration(URL url) { this(getThreadPoolPrefixName(url), getThreadPoolSize(url), getThreadPoolKeepAliveTime(url), getGroup(url), - getTimeout(url)); + getTimeout(url)); } protected AbstractDynamicConfiguration(String threadPoolPrefixName, - int threadPoolSize, - long keepAliveTime, - String group, - long timeout) { + int threadPoolSize, + long keepAliveTime, + String group, + long timeout) { this.workersThreadPool = initWorkersThreadPool(threadPoolPrefixName, threadPoolSize, keepAliveTime); this.group = group; this.timeout = timeout; @@ -212,7 +213,7 @@ public abstract class AbstractDynamicConfiguration implements DynamicConfigurati } } catch (Exception e) { if (logger.isErrorEnabled()) { - logger.error(e.getMessage(), e); + logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", e.getMessage(), e); } } return value; @@ -236,7 +237,7 @@ public abstract class AbstractDynamicConfiguration implements DynamicConfigurati int threadPoolSize, long keepAliveTime) { return new ThreadPoolExecutor(threadPoolSize, threadPoolSize, keepAliveTime, - TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), new NamedThreadFactory(threadPoolPrefixName, true)); + TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), new NamedThreadFactory(threadPoolPrefixName, true)); } protected static String getThreadPoolPrefixName(URL url) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/wrapper/CompositeDynamicConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/wrapper/CompositeDynamicConfiguration.java index 908bfa8d41..d9f6e3d30d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/wrapper/CompositeDynamicConfiguration.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/wrapper/CompositeDynamicConfiguration.java @@ -18,7 +18,7 @@ package org.apache.dubbo.common.config.configcenter.wrapper; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.util.HashSet; @@ -26,6 +26,8 @@ import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNEXPECTED_EXCEPTION; + /** * support multiple config center, simply iterating each concrete config center. */ @@ -33,7 +35,7 @@ public class CompositeDynamicConfiguration implements DynamicConfiguration { public static final String NAME = "COMPOSITE"; - private static final Logger logger = LoggerFactory.getLogger(CompositeDynamicConfiguration.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CompositeDynamicConfiguration.class); private Set configurations = new HashSet<>(); @@ -90,7 +92,7 @@ public class CompositeDynamicConfiguration implements DynamicConfiguration { try { configuration.close(); } catch (Exception e) { - logger.warn("close dynamic configuration " + configuration.getClass().getName() + "failed: " + e.getMessage(), e); + logger.warn(REGISTRY_UNEXPECTED_EXCEPTION, "", "", "close dynamic configuration " + configuration.getClass().getName() + "failed: " + e.getMessage(), e); } } configurations.clear(); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/LoggerCodeConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/LoggerCodeConstants.java index f3ead4f3f6..03c013dedf 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/LoggerCodeConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/LoggerCodeConstants.java @@ -22,7 +22,7 @@ package org.apache.dubbo.common.constants; */ public interface LoggerCodeConstants { - // common module 0-1 ~ 0-4 + // common module String COMMON_THREAD_POOL_EXHAUSTED = "0-1"; String COMMON_PROPERTY_MISSPELLING = "0-2"; @@ -31,9 +31,50 @@ public interface LoggerCodeConstants { String COMMON_CACHE_MAX_FILE_SIZE_LIMIT_EXCEED = "0-4"; - String COMMON_CACHE_MAX_ENTRY_COUNT_LIMIT_EXCEED = "0-5"; + String COMMON_THREAD_INTERRUPTED_EXCEPTION = "0-6"; + + String COMMON_CLASS_NOT_FOUND = "0-7"; + + String COMMON_FAILED_REFLECT = "0-8"; + + String COMMON_FAILED_NOTIFY_EVENT = "0-9"; + + String COMMON_UNSUPPORTED_INVOKER = "0-10"; + + String COMMON_FAILED_STOP_HTTP_SERVER = "0-11"; + + String COMMON_UNEXPECTED_EXCEPTION = "0-12"; + + String COMMON_METRICS_COLLECTOR_EXCEPTION = "0-13"; + + String COMMON_MONITOR_EXCEPTION = "0-14"; + + String COMMON_ERROR_LOAD_EXTENSION = "0-15"; + + String COMMON_EXECUTORS_NO_FOUND = "0-16"; + + String COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN = "0-17"; + + String COMMON_ERROR_USE_THREAD_POOL = "0-18"; + + String COMMON_ERROR_RUN_THREAD_TASK = "0-19"; + + String COMMON_UNEXPECTED_CREATE_DUMP = "0-20"; + + String COMMON_ERROR_TOO_MANY_INSTANCES = "0-21"; + + String COMMON_IO_EXCEPTION = "0-22"; + + String COMMON_JSON_CONVERT_EXCEPTION = "0-23"; + + String COMMON_FAILED_OVERRIDE_FIELD = "0-24"; + + String COMMON_FAILED_LOAD_MAPPING_CACHE = "0-24"; + + String COMMON_METADATA_PROCESSOR = "0-25"; + // registry module String REGISTRY_ADDRESS_INVALID = "1-1"; @@ -71,9 +112,51 @@ public interface LoggerCodeConstants { String REGISTRY_MISSING_METADATA_CONFIG_PORT = "1-18"; - String REGISTRY_ROUTER_WAIT_LONG = "1-19"; + String REGISTRY_ERROR_LISTEN_KUBERNETES = "1-19"; - // cluster module 2-1 ~ 2-18 + String REGISTRY_UNABLE_MATCH_KUBERNETES = "1-20"; + + String REGISTRY_UNABLE_FIND_SERVICE_KUBERNETES = "1-21"; + + String REGISTRY_UNABLE_ACCESS_KUBERNETES = "1-22"; + + String REGISTRY_FAILED_DOWNLOAD_FILE = "1-23"; + + String REGISTRY_FAILED_START_ZOOKEEPER = "1-24"; + + String REGISTRY_FAILED_STOP_ZOOKEEPER = "1-25"; + + String REGISTRY_FAILED_GENERATE_CERT_ISTIO = "1-26"; + + String REGISTRY_FAILED_GENERATE_KEY_ISTIO = "1-27"; + + String REGISTRY_RECEIVE_ERROR_MSG_ISTIO = "1-28"; + + String REGISTRY_ERROR_READ_FILE_ISTIO = "1-29"; + + String REGISTRY_ERROR_REQUEST_XDS = "1-30"; + + String REGISTRY_ERROR_RESPONSE_XDS = "1-31"; + + String REGISTRY_ERROR_CREATE_CHANNEL_XDS = "1-32"; + + String REGISTRY_ERROR_INITIALIZE_XDS = "1-33"; + + String REGISTRY_ERROR_PARSING_XDS = "1-34"; + + String REGISTRY_ZOOKEEPER_EXCEPTION = "1-35"; + + String REGISTRY_UNEXPECTED_EXCEPTION = "1-36"; + + String REGISTRY_NACOS_EXCEPTION = "1-37"; + + String REGISTRY_SOCKET_EXCEPTION = "1-38"; + + String REGISTRY_FAILED_LOAD_METADATA = "1-39"; + + String REGISTRY_ROUTER_WAIT_LONG = "1-40"; + + // cluster module 2-x String CLUSTER_FAILED_SITE_SELECTION = "2-1"; String CLUSTER_NO_VALID_PROVIDER = "2-2"; @@ -110,19 +193,67 @@ public interface LoggerCodeConstants { String CLUSTER_NO_RULE_LISTENER = "2-18"; - String CLUSTER_ASYN_INVOKE_FAILED = "2-19"; + String CLUSTER_EXECUTE_FILTER_EXCEPTION = "2-19"; + + String CLUSTER_FAILED_GROUP_MERGE = "2-20"; // proxy module 3-1 String PROXY_FAILED_CONVERT_URL = "3-1"; - // protocol module 4-1 ~ 4-3 + String PROXY_FAILED_EXPORT_SERVICE = "3-2"; + + String PROXY_FAILED_JAVASSIST = "3-3"; + + String PROXY_TIMEOUT_REQUEST = "3-4"; + + String PROXY_ERROR_ASYNC_RESPONSE = "3-5"; + + String PROXY_UNSUPPORTED_INVOKER = "3-6"; + + String PROXY_TIMEOUT_RESPONSE = "3-7"; + + // protocol module String PROTOCOL_UNSUPPORTED = "4-1"; String PROTOCOL_FAILED_INIT_SERIALIZATION_OPTIMIZER = "4-2"; String PROTOCOL_FAILED_REFER_INVOKER = "4-3"; - // config module 5-1 ~ 5-20 + String PROTOCOL_UNSAFE_SERIALIZATION = "4-4"; + + String PROTOCOL_FAILED_CLOSE_STREAM = "4-5"; + + String PROTOCOL_ERROR_DESERIALIZE = "4-6"; + + String PROTOCOL_ERROR_CLOSE_CLIENT = "4-7"; + + String PROTOCOL_ERROR_CLOSE_SERVER = "4-8"; + + String PROTOCOL_FAILED_PARSE = "4-9"; + + String PROTOCOL_FAILED_SERIALIZE_TRIPLE = "4-10"; + + String PROTOCOL_FAILED_REQUEST = "4-11"; + + String PROTOCOL_FAILED_CREATE_STREAM_TRIPLE = "4-12"; + + String PROTOCOL_TIMEOUT_SERVER = "4-13"; + + String PROTOCOL_FAILED_RESPONSE = "4-14"; + + String PROTOCOL_STREAM_LISTENER = "4-15"; + + String PROTOCOL_CLOSED_SERVER = "4-16"; + + String PROTOCOL_FAILED_DESTROY_INVOKER = "4-17"; + + String PROTOCOL_FAILED_LOAD_MODEL = "4-18"; + + String PROTOCOL_INCORRECT_PARAMETER_VALUES = "4-19"; + + String PROTOCOL_FAILED_DECODE = "4-20"; + + // config module String CONFIG_FAILED_CONNECT_REGISTRY = "5-1"; String CONFIG_FAILED_SHUTDOWN_HOOK = "5-2"; @@ -163,12 +294,83 @@ public interface LoggerCodeConstants { String CONFIG_STOP_DUBBO_ERROR = "5-20"; - // transport module 6-1 ~ 6-2 + String CONFIG_FAILED_EXECUTE_DESTORY = "5-21"; + + String CONFIG_FAILED_INIT_CONFIG_CENTER = "5-22"; + + String CONFIG_FAILED_WAIT_EXPORT_REFER = "5-23"; + + String CONFIG_FAILED_REFER_SERVICE = "5-24"; + + String CONFIG_UNDEFINED_PROTOCOL = "5-25"; + + String CONFIG_METADATA_SERVICE_EXPORTED = "5-26"; + + String CONFIG_API_WRONG_USE = "5-27"; + + String CONFIG_NO_ANNOTATIONS_FOUND = "5-28"; + + String CONFIG_NO_BEANS_SCANNED = "5-29"; + + String CONFIG_DUPLICATED_BEAN_DEFINITION = "5-30"; + + String CONFIG_WARN_STATUS_CHECKER = "5-31"; + + String CONFIG_FAILED_CLOSE_CONNECT_APOLLO = "5-32"; + + String CONFIG_NOT_EFFECT_EMPTY_RULE_APOLLO = "5-33"; + + String CONFIG_ERROR_NACOS = "5-34"; + + String CONFIG_START_DUBBO_ERROR = "5-35"; + + String CONFIG_FILTER_VALIDATION_EXCEPTION = "5-36"; + + // transport module String TRANSPORT_FAILED_CONNECT_PROVIDER = "6-1"; String TRANSPORT_CLIENT_CONNECT_TIMEOUT = "6-2"; - String INTERNAL_SERVICE_CONFIG_ERROR = "6-3"; + String TRANSPORT_FAILED_CLOSE = "6-3"; + + String TRANSPORT_UNEXPECTED_EXCEPTION = "6-4"; + + String TRANSPORT_FAILED_DISCONNECT_PROVIDER = "6-5"; + + String TRANSPORT_UNSUPPORTED_MESSAGE = "6-6"; + + String TRANSPORT_CONNECTION_LIMIT_EXCEED = "6-7"; + + String TRANSPORT_FAILED_DECODE = "6-8"; + + String TRANSPORT_FAILED_SERIALIZATION = "6-9"; + + String TRANSPORT_EXCEED_PAYLOAD_LIMIT = "6-10"; + + String TRANSPORT_UNSUPPORTED_CHARSET = "6-11"; + + String TRANSPORT_FAILED_DESTROY_ZOOKEEPER = "6-12"; + + String TRANSPORT_FAILED_CLOSE_STREAM = "6-13"; + + String TRANSPORT_FAILED_RESPONSE = "6-14"; + + String TRANSPORT_SKIP_UNUSED_STREAM = "6-15"; + + String TRANSPORT_FAILED_RECONNECT = "6-3"; + + // qos plugin + String QOS_PROFILER_DISABLED = "7-1"; + + String QOS_PROFILER_ENABLED = "7-2"; + + String QOS_PROFILER_WARN_PERCENT = "7-3"; + + String QOS_FAILED_START_SERVER = "7-4"; + + String QOS_COMMAND_NOT_FOUND = "7-5"; + + String QOS_UNEXPECTED_EXCEPTION = "7-6"; // Internal unknown error. diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/AbstractDeployer.java b/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/AbstractDeployer.java index 95b74576d4..b9590e9def 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/AbstractDeployer.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/AbstractDeployer.java @@ -16,13 +16,14 @@ */ package org.apache.dubbo.common.deploy; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.model.ScopeModel; import java.util.ArrayList; import java.util.List; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_MONITOR_EXCEPTION; import static org.apache.dubbo.common.deploy.DeployState.FAILED; import static org.apache.dubbo.common.deploy.DeployState.PENDING; import static org.apache.dubbo.common.deploy.DeployState.STARTED; @@ -32,7 +33,7 @@ import static org.apache.dubbo.common.deploy.DeployState.STOPPING; public abstract class AbstractDeployer implements Deployer { - private static final Logger logger = LoggerFactory.getLogger(AbstractDeployer.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractDeployer.class); private volatile DeployState state = PENDING; @@ -108,7 +109,7 @@ public abstract class AbstractDeployer implements Deployer try { listener.onStarting(scopeModel); } catch (Throwable e) { - logger.error(getIdentifier() + " an exception occurred when handle starting event", e); + logger.error(COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle starting event", e); } } } @@ -119,17 +120,18 @@ public abstract class AbstractDeployer implements Deployer try { listener.onStarted(scopeModel); } catch (Throwable e) { - logger.error(getIdentifier() + " an exception occurred when handle started event", e); + logger.error(COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle started event", e); } } } + protected void setStopping() { this.state = STOPPING; for (DeployListener listener : listeners) { try { listener.onStopping(scopeModel); } catch (Throwable e) { - logger.error(getIdentifier() + " an exception occurred when handle stopping event", e); + logger.error(COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle stopping event", e); } } } @@ -140,7 +142,7 @@ public abstract class AbstractDeployer implements Deployer try { listener.onStopped(scopeModel); } catch (Throwable e) { - logger.error(getIdentifier() + " an exception occurred when handle stopped event", e); + logger.error(COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle stopped event", e); } } } @@ -152,7 +154,7 @@ public abstract class AbstractDeployer implements Deployer try { listener.onFailure(scopeModel, error); } catch (Throwable e) { - logger.error(getIdentifier() + " an exception occurred when handle failed event", e); + logger.error(COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle failed event", e); } } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java index 087d79256c..849cb4f981 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java @@ -23,7 +23,7 @@ import org.apache.dubbo.common.context.Lifecycle; import org.apache.dubbo.common.extension.support.ActivateComparator; import org.apache.dubbo.common.extension.support.WrapperComparator; import org.apache.dubbo.common.lang.Prioritized; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.Disposable; import org.apache.dubbo.common.utils.ArrayUtils; @@ -80,6 +80,8 @@ import static java.util.stream.StreamSupport.stream; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REMOVE_VALUE_PREFIX; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_ERROR_LOAD_EXTENSION; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_LOAD_ENV_VARIABLE; /** * {@link org.apache.dubbo.rpc.model.ApplicationModel}, {@code DubboBootstrap} and this class are @@ -101,7 +103,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.REMOVE_VALUE_PRE */ public class ExtensionLoader { - private static final Logger logger = LoggerFactory.getLogger(ExtensionLoader.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ExtensionLoader.class); private static final Pattern NAME_SEPARATOR = Pattern.compile("\\s*[,]+\\s*"); private static final String SPECIAL_SPI_PROPERTIES = "special_spi.properties"; @@ -131,9 +133,9 @@ public class ExtensionLoader { private static volatile LoadingStrategy[] strategies = loadLoadingStrategies(); - private static Map specialSPILoadingStrategyMap = getSpecialSPILoadingStrategyMap(); + private static Map specialSPILoadingStrategyMap = getSpecialSPILoadingStrategyMap(); - private static SoftReference>> urlListMapCache = new SoftReference<>(new ConcurrentHashMap<>()); + private static SoftReference>> urlListMapCache = new SoftReference<>(new ConcurrentHashMap<>()); private static List ignoredInjectMethodsDesc = getIgnoredInjectMethodsDesc(); @@ -169,6 +171,7 @@ public class ExtensionLoader { /** * some spi are implements by dubbo framework only and scan multi classloaders resources may cause * application startup very slow + * * @return */ private static Map getSpecialSPILoadingStrategyMap() { @@ -243,7 +246,7 @@ public class ExtensionLoader { try { disposable.destroy(); } catch (Exception e) { - logger.error("Error destroying extension " + disposable, e); + logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", "Error destroying extension " + disposable, e); } } }); @@ -257,7 +260,7 @@ public class ExtensionLoader { try { disposable.destroy(); } catch (Exception e) { - logger.error("Error destroying extension " + disposable, e); + logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", "Error destroying extension " + disposable, e); } } } @@ -875,12 +878,12 @@ public class ExtensionLoader { method.invoke(instance, object); } } catch (Exception e) { - logger.error("Failed to inject via method " + method.getName() + logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", "Failed to inject via method " + method.getName() + " of interface " + type.getName() + ": " + e.getMessage(), e); } } } catch (Exception e) { - logger.error(e.getMessage(), e); + logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", e.getMessage(), e); } return instance; } @@ -935,7 +938,7 @@ public class ExtensionLoader { try { classes = loadExtensionClasses(); } catch (InterruptedException e) { - logger.error("Exception occurred when loading extension class (interface: " + type + ")", e); + logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", "Exception occurred when loading extension class (interface: " + type + ")", e); throw new IllegalStateException("Exception occurred when loading extension class (interface: " + type + ")", e); } cachedClasses.set(classes); @@ -1017,16 +1020,16 @@ public class ExtensionLoader { } } - if (specialSPILoadingStrategyMap.containsKey(type)){ + if (specialSPILoadingStrategyMap.containsKey(type)) { String internalDirectoryType = specialSPILoadingStrategyMap.get(type); //skip to load spi when name don't match if (!LoadingStrategy.ALL.equals(internalDirectoryType) - && !internalDirectoryType.equals(loadingStrategy.getName())){ + && !internalDirectoryType.equals(loadingStrategy.getName())) { return; } classLoadersToLoad.clear(); classLoadersToLoad.add(ExtensionLoader.class.getClassLoader()); - }else { + } else { // load from scope model Set classLoaders = scopeModel.getClassLoaders(); @@ -1055,7 +1058,7 @@ public class ExtensionLoader { } catch (InterruptedException e) { throw e; } catch (Throwable t) { - logger.error("Exception occurred when loading extension class (interface: " + + logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", "Exception occurred when loading extension class (interface: " + type + ", description file: " + fileName + ").", t); } } @@ -1095,7 +1098,7 @@ public class ExtensionLoader { } } } catch (Throwable t) { - logger.error("Exception occurred when loading extension class (interface: " + + logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", "Exception occurred when loading extension class (interface: " + type + ", class file: " + resourceURL + ") in " + resourceURL, t); } } @@ -1111,7 +1114,7 @@ public class ExtensionLoader { } } - List contentList = urlListMap.computeIfAbsent(resourceURL,key->{ + List contentList = urlListMap.computeIfAbsent(resourceURL, key -> { List newContentList = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceURL.openStream(), StandardCharsets.UTF_8))) { @@ -1222,7 +1225,7 @@ public class ExtensionLoader { // duplicate implementation is unacceptable unacceptableExceptions.add(name); String duplicateMsg = "Duplicate extension " + type.getName() + " name " + name + " on " + c.getName() + " and " + clazz.getName(); - logger.error(duplicateMsg); + logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", duplicateMsg); throw new IllegalStateException(duplicateMsg); } } @@ -1360,7 +1363,7 @@ public class ExtensionLoader { } } } catch (IOException ex) { - logger.error("load properties failed.", ex); + logger.error(CONFIG_FAILED_LOAD_ENV_VARIABLE, "", "", "load properties failed.", ex); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/reference/ReferenceCountedResource.java b/dubbo-common/src/main/java/org/apache/dubbo/common/reference/ReferenceCountedResource.java index 3288a514d6..bc1f1cee88 100755 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/reference/ReferenceCountedResource.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/reference/ReferenceCountedResource.java @@ -16,16 +16,18 @@ */ package org.apache.dubbo.common.reference; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.util.concurrent.atomic.AtomicLongFieldUpdater; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT; + /** * inspired by Netty */ public abstract class ReferenceCountedResource implements AutoCloseable { - private static final Logger logger = LoggerFactory.getLogger(ReferenceCountedResource.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReferenceCountedResource.class); private static final AtomicLongFieldUpdater COUNTER_UPDATER = AtomicLongFieldUpdater.newUpdater(ReferenceCountedResource.class, "counter"); @@ -53,7 +55,7 @@ public abstract class ReferenceCountedResource implements AutoCloseable { destroy(); return true; } else if (remainingCount <= -1) { - logger.warn("This instance has been destroyed"); + logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", "This instance has been destroyed"); return false; } else { return false; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/resource/GlobalResourcesRepository.java b/dubbo-common/src/main/java/org/apache/dubbo/common/resource/GlobalResourcesRepository.java index 3f34a3e374..f0ad708336 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/resource/GlobalResourcesRepository.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/resource/GlobalResourcesRepository.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.common.resource; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NamedThreadFactory; @@ -26,13 +26,15 @@ import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; + /** * Global resource repository between all framework models. * It will be destroyed only after all framework model is destroyed. */ public class GlobalResourcesRepository { - private static final Logger logger = LoggerFactory.getLogger(GlobalResourcesRepository.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(GlobalResourcesRepository.class); private volatile static GlobalResourcesRepository instance; private volatile ExecutorService executorService; @@ -56,6 +58,7 @@ public class GlobalResourcesRepository { /** * Register a global reused disposable. The disposable will be executed when all dubbo FrameworkModels are destroyed. * Note: the global disposable should be registered in static code, it's reusable and will not be removed when dubbo shutdown. + * * @param disposable */ public static void registerGlobalDisposable(Disposable disposable) { @@ -107,7 +110,7 @@ public class GlobalResourcesRepository { try { disposable.destroy(); } catch (Exception e) { - logger.warn("destroy resources failed: " + e.getMessage(), e); + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "destroy resources failed: " + e.getMessage(), e); } } // clear one-off disposable @@ -118,7 +121,7 @@ public class GlobalResourcesRepository { try { disposable.destroy(); } catch (Exception e) { - logger.warn("destroy resources failed: " + e.getMessage(), e); + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "destroy resources failed: " + e.getMessage(), e); } } @@ -129,6 +132,7 @@ public class GlobalResourcesRepository { /** * Register a one-off disposable, the disposable is removed automatically on first shutdown. + * * @param disposable */ public void registerDisposable(Disposable disposable) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/system/OperatingSystemBeanManager.java b/dubbo-common/src/main/java/org/apache/dubbo/common/system/OperatingSystemBeanManager.java index a5bc51f630..f3de66fa87 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/system/OperatingSystemBeanManager.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/system/OperatingSystemBeanManager.java @@ -17,7 +17,7 @@ package org.apache.dubbo.common.system; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.MethodUtils; @@ -28,19 +28,21 @@ import java.util.Arrays; import java.util.List; import java.util.Objects; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_CLASS_NOT_FOUND; + /** * OperatingSystemBeanManager related. */ public class OperatingSystemBeanManager { - private static final Logger LOGGER = LoggerFactory.getLogger(OperatingSystemBeanManager.class); + private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(OperatingSystemBeanManager.class); /** * com.ibm for J9 * com.sun for HotSpot */ private static final List OPERATING_SYSTEM_BEAN_CLASS_NAMES = Arrays.asList( - "com.sun.management.OperatingSystemMXBean", "com.ibm.lang.management.OperatingSystemMXBean"); + "com.sun.management.OperatingSystemMXBean", "com.ibm.lang.management.OperatingSystemMXBean"); private static final OperatingSystemMXBean OPERATING_SYSTEM_BEAN; @@ -57,7 +59,8 @@ public class OperatingSystemBeanManager { PROCESS_CPU_USAGE_METHOD = deduceMethod("getProcessCpuLoad"); } - private OperatingSystemBeanManager() {} + private OperatingSystemBeanManager() { + } public static OperatingSystemMXBean getOperatingSystemBean() { return OPERATING_SYSTEM_BEAN; @@ -76,7 +79,7 @@ public class OperatingSystemBeanManager { try { return Class.forName(className); } catch (ClassNotFoundException e) { - LOGGER.warn("[OperatingSystemBeanManager] Failed to load operating system bean class.", e); + LOGGER.warn(COMMON_CLASS_NOT_FOUND, "", "", "[OperatingSystemBeanManager] Failed to load operating system bean class.", e); } } return null; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/DefaultExecutorRepository.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/DefaultExecutorRepository.java index f1d2c7ebd9..5abc993d01 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/DefaultExecutorRepository.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/DefaultExecutorRepository.java @@ -19,7 +19,7 @@ package org.apache.dubbo.common.threadpool.manager; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionAccessor; import org.apache.dubbo.common.extension.ExtensionAccessorAware; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.store.DataStore; import org.apache.dubbo.common.threadpool.ThreadPool; @@ -53,12 +53,15 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERNAL_EXECUTO import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_ERROR_USE_THREAD_POOL; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_EXECUTORS_NO_FOUND; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN; /** * Consider implementing {@code Lifecycle} to enable executors shutdown when the process stops. */ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionAccessorAware { - private static final Logger logger = LoggerFactory.getLogger(DefaultExecutorRepository.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultExecutorRepository.class); private volatile ScheduledExecutorService serviceExportExecutor; @@ -153,7 +156,7 @@ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionA } - if (CONSUMER_SIDE.equalsIgnoreCase(url.getParameter(SIDE_KEY))){ + if (CONSUMER_SIDE.equalsIgnoreCase(url.getParameter(SIDE_KEY))) { executorKey = CONSUMER_SHARED_EXECUTOR_SERVICE_COMPONENT_KEY; } return executorKey; @@ -172,7 +175,7 @@ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionA * have Executor instances generated and stored. */ if (executors == null) { - logger.warn("No available executors, this is not expected, framework should call createExecutorIfAbsent first " + + logger.warn(COMMON_EXECUTORS_NO_FOUND, "", "", "No available executors, this is not expected, framework should call createExecutorIfAbsent first" + "before coming to here."); return null; @@ -218,7 +221,7 @@ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionA } } } catch (Throwable t) { - logger.error(t.getMessage(), t); + logger.error(COMMON_ERROR_USE_THREAD_POOL, "", "", t.getMessage(), t); } } @@ -244,7 +247,7 @@ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionA serviceExportExecutor.shutdown(); } catch (Throwable ignored) { // ignored - logger.warn(ignored.getMessage(), ignored); + logger.warn(COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", ignored.getMessage(), ignored); } } serviceExportExecutor = null; @@ -272,7 +275,7 @@ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionA try { serviceReferExecutor.shutdown(); } catch (Throwable ignored) { - logger.warn(ignored.getMessage(), ignored); + logger.warn(COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", ignored.getMessage(), ignored); } } serviceReferExecutor = null; @@ -357,7 +360,7 @@ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionA ExecutorUtil.shutdownNow(executor, 100); } catch (Throwable ignored) { // ignored - logger.warn(ignored.getMessage(), ignored); + logger.warn(COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", ignored.getMessage(), ignored); } } }); @@ -371,7 +374,7 @@ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionA executorService.shutdownNow(); } catch (Exception e) { String msg = "shutdown executor service [" + name + "] failed: "; - logger.warn(msg + e.getMessage(), e); + logger.warn(COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", msg + e.getMessage(), e); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/FrameworkExecutorRepository.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/FrameworkExecutorRepository.java index d630ee473e..8679249d50 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/FrameworkExecutorRepository.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/FrameworkExecutorRepository.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.common.threadpool.manager; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.Disposable; import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory; @@ -30,8 +30,10 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN; + public class FrameworkExecutorRepository implements Disposable { - private static final Logger logger = LoggerFactory.getLogger(FrameworkExecutorRepository.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FrameworkExecutorRepository.class); private final ExecutorService sharedExecutor; private final ScheduledExecutorService sharedScheduledExecutor; @@ -211,7 +213,7 @@ public class FrameworkExecutorRepository implements Disposable { executorService.shutdownNow(); } catch (Exception e) { String msg = "shutdown executor service [" + name + "] failed: "; - logger.warn(msg + e.getMessage(), e); + logger.warn(COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", msg + e.getMessage(), e); } } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/serial/SerializingExecutor.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/serial/SerializingExecutor.java index 041ba56839..fea8619e84 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/serial/SerializingExecutor.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/serial/SerializingExecutor.java @@ -17,7 +17,7 @@ package org.apache.dubbo.common.threadpool.serial; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadlocal.InternalThreadLocal; @@ -26,6 +26,8 @@ import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_ERROR_RUN_THREAD_TASK; + /** * Executor ensuring that all {@link Runnable} tasks submitted are executed in order * using the provided {@link Executor}, and serially such that no two will ever be @@ -33,7 +35,7 @@ import java.util.concurrent.atomic.AtomicBoolean; */ public final class SerializingExecutor implements Executor, Runnable { - private static final Logger LOGGER = LoggerFactory.getLogger(SerializingExecutor.class); + private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(SerializingExecutor.class); /** * Use false to stop and true to run @@ -100,7 +102,7 @@ public final class SerializingExecutor implements Executor, Runnable { InternalThreadLocal.removeAll(); r.run(); } catch (RuntimeException e) { - LOGGER.error("Exception while executing runnable " + r, e); + LOGGER.error(COMMON_ERROR_RUN_THREAD_TASK, "", "", "Exception while executing runnable " + r, e); } finally { InternalThreadLocal.removeAll(); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReport.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReport.java index 19a1f967d9..d175ff4b3f 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReport.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReport.java @@ -46,6 +46,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.OS_NAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.OS_WIN_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_POOL_EXHAUSTED_LISTENERS_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_THREAD_POOL_EXHAUSTED; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_CREATE_DUMP; /** * Abort Policy. @@ -162,7 +163,7 @@ public class AbortPolicyWithReport extends ThreadPoolExecutor.AbortPolicy { new File(dumpPath, "Dubbo_JStack.log" + "." + dateStr))) { JVMUtil.jstack(jStackStream); } catch (Throwable t) { - logger.error("dump jStack error", t); + logger.error(COMMON_UNEXPECTED_CREATE_DUMP, "", "", "dump jStack error", t); } finally { guard.release(); } @@ -183,7 +184,7 @@ public class AbortPolicyWithReport extends ThreadPoolExecutor.AbortPolicy { if (dumpDirectory.mkdirs()) { logger.info(format("Dubbo dump directory[%s] created", dumpDirectory.getAbsolutePath())); } else { - logger.warn(format("Dubbo dump directory[%s] can't be created, use the 'user.home'[%s]", + logger.warn(COMMON_UNEXPECTED_CREATE_DUMP, "", "", format("Dubbo dump directory[%s] can't be created, use the 'user.home'[%s]", dumpDirectory.getAbsolutePath(), USER_HOME)); return USER_HOME; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/timer/HashedWheelTimer.java b/dubbo-common/src/main/java/org/apache/dubbo/common/timer/HashedWheelTimer.java index e6cb3cb51b..b6589949d4 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/timer/HashedWheelTimer.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/timer/HashedWheelTimer.java @@ -16,7 +16,7 @@ package org.apache.dubbo.common.timer; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ClassUtils; @@ -38,6 +38,8 @@ import java.util.concurrent.atomic.AtomicLong; import static org.apache.dubbo.common.constants.CommonConstants.OS_NAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.OS_WIN_PREFIX; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_ERROR_RUN_THREAD_TASK; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_ERROR_TOO_MANY_INSTANCES; /** * A {@link Timer} optimized for approximated I/O timeout scheduling. @@ -87,13 +89,13 @@ public class HashedWheelTimer implements Timer { */ public static final String NAME = "hased"; - private static final Logger logger = LoggerFactory.getLogger(HashedWheelTimer.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(HashedWheelTimer.class); private static final AtomicInteger INSTANCE_COUNTER = new AtomicInteger(); private static final AtomicBoolean WARNED_TOO_MANY_INSTANCES = new AtomicBoolean(); private static final int INSTANCE_COUNT_LIMIT = 64; private static final AtomicIntegerFieldUpdater WORKER_STATE_UPDATER = - AtomicIntegerFieldUpdater.newUpdater(HashedWheelTimer.class, "workerState"); + AtomicIntegerFieldUpdater.newUpdater(HashedWheelTimer.class, "workerState"); private final Worker worker = new Worker(); private final Thread workerThread; @@ -181,7 +183,7 @@ public class HashedWheelTimer implements Timer { * @throws IllegalArgumentException if {@code tickDuration} is <= 0 */ public HashedWheelTimer( - ThreadFactory threadFactory, long tickDuration, TimeUnit unit) { + ThreadFactory threadFactory, long tickDuration, TimeUnit unit) { this(threadFactory, tickDuration, unit, 512); } @@ -198,8 +200,8 @@ public class HashedWheelTimer implements Timer { * @throws IllegalArgumentException if either of {@code tickDuration} and {@code ticksPerWheel} is <= 0 */ public HashedWheelTimer( - ThreadFactory threadFactory, - long tickDuration, TimeUnit unit, int ticksPerWheel) { + ThreadFactory threadFactory, + long tickDuration, TimeUnit unit, int ticksPerWheel) { this(threadFactory, tickDuration, unit, ticksPerWheel, -1); } @@ -221,9 +223,9 @@ public class HashedWheelTimer implements Timer { * @throws IllegalArgumentException if either of {@code tickDuration} and {@code ticksPerWheel} is <= 0 */ public HashedWheelTimer( - ThreadFactory threadFactory, - long tickDuration, TimeUnit unit, int ticksPerWheel, - long maxPendingTimeouts) { + ThreadFactory threadFactory, + long tickDuration, TimeUnit unit, int ticksPerWheel, + long maxPendingTimeouts) { if (threadFactory == null) { throw new NullPointerException("threadFactory"); @@ -248,15 +250,15 @@ public class HashedWheelTimer implements Timer { // Prevent overflow. if (this.tickDuration >= Long.MAX_VALUE / wheel.length) { throw new IllegalArgumentException(String.format( - "tickDuration: %d (expected: 0 < tickDuration in nanos < %d", - tickDuration, Long.MAX_VALUE / wheel.length)); + "tickDuration: %d (expected: 0 < tickDuration in nanos < %d", + tickDuration, Long.MAX_VALUE / wheel.length)); } workerThread = threadFactory.newThread(worker); this.maxPendingTimeouts = maxPendingTimeouts; if (INSTANCE_COUNTER.incrementAndGet() > INSTANCE_COUNT_LIMIT && - WARNED_TOO_MANY_INSTANCES.compareAndSet(false, true)) { + WARNED_TOO_MANY_INSTANCES.compareAndSet(false, true)) { reportTooManyInstances(); } } @@ -277,11 +279,11 @@ public class HashedWheelTimer implements Timer { private static HashedWheelBucket[] createWheel(int ticksPerWheel) { if (ticksPerWheel <= 0) { throw new IllegalArgumentException( - "ticksPerWheel must be greater than 0: " + ticksPerWheel); + "ticksPerWheel must be greater than 0: " + ticksPerWheel); } if (ticksPerWheel > 1073741824) { throw new IllegalArgumentException( - "ticksPerWheel may not be greater than 2^30: " + ticksPerWheel); + "ticksPerWheel may not be greater than 2^30: " + ticksPerWheel); } ticksPerWheel = normalizeTicksPerWheel(ticksPerWheel); @@ -338,9 +340,9 @@ public class HashedWheelTimer implements Timer { public Set stop() { if (Thread.currentThread() == workerThread) { throw new IllegalStateException( - HashedWheelTimer.class.getSimpleName() + - ".stop() cannot be called from " + - TimerTask.class.getSimpleName()); + HashedWheelTimer.class.getSimpleName() + + ".stop() cannot be called from " + + TimerTask.class.getSimpleName()); } if (!WORKER_STATE_UPDATER.compareAndSet(this, WORKER_STATE_STARTED, WORKER_STATE_SHUTDOWN)) { @@ -391,8 +393,8 @@ public class HashedWheelTimer implements Timer { if (maxPendingTimeouts > 0 && pendingTimeoutsCount > maxPendingTimeouts) { pendingTimeouts.decrementAndGet(); throw new RejectedExecutionException("Number of pending timeouts (" - + pendingTimeoutsCount + ") is greater than or equal to maximum allowed pending " - + "timeouts (" + maxPendingTimeouts + ")"); + + pendingTimeoutsCount + ") is greater than or equal to maximum allowed pending " + + "timeouts (" + maxPendingTimeouts + ")"); } start(); @@ -419,9 +421,9 @@ public class HashedWheelTimer implements Timer { private static void reportTooManyInstances() { String resourceType = ClassUtils.simpleClassName(HashedWheelTimer.class); - logger.error("You are creating too many " + resourceType + " instances. " + - resourceType + " is a shared resource that must be reused across the JVM," + - "so that only a few instances are created."); + logger.error(COMMON_ERROR_TOO_MANY_INSTANCES, "", "", "You are creating too many " + resourceType + " instances. " + + resourceType + " is a shared resource that must be reused across the JVM," + + "so that only a few instances are created."); } private final class Worker implements Runnable { @@ -447,7 +449,7 @@ public class HashedWheelTimer implements Timer { int idx = (int) (tick & mask); processCancelledTasks(); HashedWheelBucket bucket = - wheel[idx]; + wheel[idx]; transferTimeoutsToBuckets(); bucket.expireTimeouts(deadline); tick++; @@ -507,7 +509,7 @@ public class HashedWheelTimer implements Timer { timeout.remove(); } catch (Throwable t) { if (logger.isWarnEnabled()) { - logger.warn("An exception was thrown while process a cancellation task", t); + logger.warn(COMMON_ERROR_RUN_THREAD_TASK, "", "", "An exception was thrown while process a cancellation task", t); } } } @@ -559,7 +561,7 @@ public class HashedWheelTimer implements Timer { private static final int ST_CANCELLED = 1; private static final int ST_EXPIRED = 2; private static final AtomicIntegerFieldUpdater STATE_UPDATER = - AtomicIntegerFieldUpdater.newUpdater(HashedWheelTimeout.class, "state"); + AtomicIntegerFieldUpdater.newUpdater(HashedWheelTimeout.class, "state"); private final HashedWheelTimer timer; private final TimerTask task; @@ -651,7 +653,7 @@ public class HashedWheelTimer implements Timer { task.run(this); } catch (Throwable t) { if (logger.isWarnEnabled()) { - logger.warn("An exception was thrown by " + TimerTask.class.getSimpleName() + '.', t); + logger.warn(COMMON_ERROR_RUN_THREAD_TASK, "", "", "An exception was thrown by " + TimerTask.class.getSimpleName() + '.', t); } } } @@ -663,15 +665,15 @@ public class HashedWheelTimer implements Timer { String simpleClassName = ClassUtils.simpleClassName(this.getClass()); StringBuilder buf = new StringBuilder(192) - .append(simpleClassName) - .append('(') - .append("deadline: "); + .append(simpleClassName) + .append('(') + .append("deadline: "); if (remaining > 0) { buf.append(remaining) - .append(" ns later"); + .append(" ns later"); } else if (remaining < 0) { buf.append(-remaining) - .append(" ns ago"); + .append(" ns ago"); } else { buf.append("now"); } @@ -681,9 +683,9 @@ public class HashedWheelTimer implements Timer { } return buf.append(", task: ") - .append(task()) - .append(')') - .toString(); + .append(task()) + .append(')') + .toString(); } } @@ -731,7 +733,7 @@ public class HashedWheelTimer implements Timer { } else { // The timeout was placed into a wrong slot. This should never happen. throw new IllegalStateException(String.format( - "timeout.deadline (%d) > deadline (%d)", timeout.deadline, deadline)); + "timeout.deadline (%d) > deadline (%d)", timeout.deadline, deadline)); } } else if (timeout.isCancelled()) { next = remove(timeout); @@ -808,9 +810,9 @@ public class HashedWheelTimer implements Timer { return head; } } - + private static final boolean IS_OS_WINDOWS = System.getProperty(OS_NAME_KEY, "").toLowerCase(Locale.US).contains(OS_WIN_PREFIX); - + private boolean isWindows() { return IS_OS_WINDOWS; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CollectionUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CollectionUtils.java index 48c4c4b0be..4bf027e434 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CollectionUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CollectionUtils.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.common.utils; +import java.lang.reflect.Field; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collection; @@ -237,6 +238,22 @@ public class CollectionUtils { return ret; } + @SuppressWarnings("unchecked") + public static Map objToMap(Object object) throws IllegalAccessException { + Map ret = new HashMap<>(); + if (object != null) { + Field[] fields = object.getClass().getDeclaredFields(); + for (Field field : fields) { + field.setAccessible(true); + Object value = field.get(object); + if (value != null) { + ret.put((K)field.getName(), (V)value); + } + } + } + return ret; + } + /** * Return {@code true} if the supplied Collection is {@code null} or empty. * Otherwise, return {@code false}. diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java index 1a5bf8b01a..e937098ce1 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java @@ -20,7 +20,7 @@ import org.apache.dubbo.common.config.Configuration; import org.apache.dubbo.common.config.InmemoryConfiguration; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.ExtensionDirector; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.io.BufferedReader; @@ -46,10 +46,11 @@ import java.util.regex.Pattern; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REMOVE_VALUE_PREFIX; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_IO_EXCEPTION; public class ConfigUtils { - private static final Logger logger = LoggerFactory.getLogger(ConfigUtils.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ConfigUtils.class); private static Pattern VARIABLE_PATTERN = Pattern.compile( "\\$\\s*\\{?\\s*([\\._0-9a-zA-Z]+)\\s*\\}?"); private static int PID = -1; @@ -136,7 +137,7 @@ public class ConfigUtils { } public static String replaceProperty(String expression, Configuration configuration) { - if (StringUtils.isEmpty(expression)|| expression.indexOf('$') < 0) { + if (StringUtils.isEmpty(expression) || expression.indexOf('$') < 0) { return expression; } Matcher matcher = VARIABLE_PATTERN.matcher(expression); @@ -221,7 +222,7 @@ public class ConfigUtils { input.close(); } } catch (Throwable e) { - logger.warn("Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); + logger.warn(COMMON_IO_EXCEPTION, "", "", "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); } return properties; } @@ -236,12 +237,12 @@ public class ConfigUtils { return a; }); } catch (Throwable t) { - logger.warn("Fail to load " + fileName + " file: " + t.getMessage(), t); + logger.warn(COMMON_IO_EXCEPTION, "", "", "Fail to load " + fileName + " file: " + t.getMessage(), t); } if (CollectionUtils.isEmpty(set)) { if (!optional) { - logger.warn("No " + fileName + " found on the class path."); + logger.warn(COMMON_IO_EXCEPTION, "", "", "No " + fileName + " found on the class path."); } return properties; } @@ -250,14 +251,14 @@ public class ConfigUtils { if (set.size() > 1) { String errMsg = String.format("only 1 %s file is expected, but %d dubbo.properties files found on class path: %s", fileName, set.size(), set); - logger.warn(errMsg); + logger.warn(COMMON_IO_EXCEPTION, "", "", errMsg); } // fall back to use method getResourceAsStream try { properties.load(ClassUtils.getClassLoader().getResourceAsStream(fileName)); } catch (Throwable e) { - logger.warn("Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); + logger.warn(COMMON_IO_EXCEPTION, "", "", "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); } return properties; } @@ -280,7 +281,7 @@ public class ConfigUtils { } } } catch (Throwable e) { - logger.warn("Fail to load " + fileName + " file from " + url + "(ignore this file): " + e.getMessage(), e); + logger.warn(COMMON_IO_EXCEPTION, "", "", "Fail to load " + fileName + " file from " + url + "(ignore this file): " + e.getMessage(), e); } } @@ -295,7 +296,7 @@ public class ConfigUtils { return readString(input); } } catch (Throwable e) { - logger.warn("Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); + logger.warn(COMMON_IO_EXCEPTION, "", "", "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); } } @@ -312,7 +313,7 @@ public class ConfigUtils { } } } catch (Throwable e) { - logger.warn("Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); + logger.warn(COMMON_IO_EXCEPTION, "", "", "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); } return rawRule; } @@ -330,7 +331,7 @@ public class ConfigUtils { buffer = new char[10]; } } catch (IOException e) { - logger.error("Read migration file error.", e); + logger.error(COMMON_IO_EXCEPTION, "", "", "Read migration file error.", e); } return stringBuilder.toString(); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java index c462ac4d7d..6c0bc148a1 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java @@ -17,7 +17,7 @@ package org.apache.dubbo.common.utils; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.util.concurrent.Executor; @@ -28,13 +28,14 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN; public class ExecutorUtil { - private static final Logger logger = LoggerFactory.getLogger(ExecutorUtil.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ExecutorUtil.class); private static final ThreadPoolExecutor SHUTDOWN_EXECUTOR = new ThreadPoolExecutor(0, 1, - 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue(100), - new NamedThreadFactory("Close-ExecutorService-Timer", true)); + 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue(100), + new NamedThreadFactory("Close-ExecutorService-Timer", true)); public static boolean isTerminated(Executor executor) { if (executor instanceof ExecutorService) { @@ -110,7 +111,7 @@ public class ExecutorUtil { } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", e.getMessage(), e); } }); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MD5Utils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MD5Utils.java index 2d4863149d..a79dffe811 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MD5Utils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MD5Utils.java @@ -17,23 +17,24 @@ package org.apache.dubbo.common.utils; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; /** * MD5 util. */ public class MD5Utils { - private static final Logger logger = LoggerFactory.getLogger(MD5Utils.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MD5Utils.class); private static final char[] hexDigits = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; private MessageDigest mdInst; @@ -42,12 +43,13 @@ public class MD5Utils { try { mdInst = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { - logger.error("Failed to obtain md5", e); + logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to obtain md5", e); } } /** * Calculation md5 value of specify string + * * @param input */ public String getMd5(String input) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java index b8abfa6533..a6a8b6444d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java @@ -18,7 +18,7 @@ package org.apache.dubbo.common.utils; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.CommonConstants; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.lang.reflect.Array; @@ -58,6 +58,7 @@ import java.util.concurrent.ConcurrentSkipListMap; import java.util.function.Consumer; import java.util.function.Supplier; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_REFLECT; import static org.apache.dubbo.common.utils.ClassUtils.isAssignableFrom; /** @@ -71,12 +72,12 @@ import static org.apache.dubbo.common.utils.ClassUtils.isAssignableFrom; * *

* Other type will be covert to a map which contains the attributes and value pair of object. - * + *

* TODO: exact PojoUtils to scope bean */ public class PojoUtils { - private static final Logger logger = LoggerFactory.getLogger(PojoUtils.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PojoUtils.class); private static final ConcurrentMap NAME_METHODS_CACHE = new ConcurrentHashMap(); private static final ConcurrentMap, ConcurrentMap> CLASS_FIELD_CACHE = new ConcurrentHashMap, ConcurrentMap>(); @@ -144,7 +145,7 @@ public class PojoUtils { if (ReflectUtils.isPrimitives(pojo.getClass())) { return pojo; } - + if (pojo instanceof LocalDate || pojo instanceof LocalDateTime || pojo instanceof LocalTime) { return pojo.toString(); } @@ -525,7 +526,7 @@ public class PojoUtils { } catch (Exception e) { String exceptionDescription = "Failed to set pojo " + dest.getClass().getSimpleName() + " property " + name + " value " + value.getClass() + ", cause: " + e.getMessage(); - logger.error(exceptionDescription, e); + logger.error(COMMON_FAILED_REFLECT, "", "", exceptionDescription, e); throw new RuntimeException(exceptionDescription, e); } } else if (field != null) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeClassChecker.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeClassChecker.java index 50ddfdcfc3..5b4eb04b38 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeClassChecker.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeClassChecker.java @@ -19,7 +19,7 @@ package org.apache.dubbo.common.utils; import org.apache.dubbo.common.beanutil.JavaBeanSerializeUtil; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.CommonConstants; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.io.IOException; @@ -32,9 +32,11 @@ import static org.apache.dubbo.common.constants.CommonConstants.CLASS_DESERIALIZ import static org.apache.dubbo.common.constants.CommonConstants.CLASS_DESERIALIZE_BLOCKED_LIST; import static org.apache.dubbo.common.constants.CommonConstants.CLASS_DESERIALIZE_BLOCK_ALL; import static org.apache.dubbo.common.constants.CommonConstants.SERIALIZE_BLOCKED_LIST_FILE_PATH; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_IO_EXCEPTION; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNSAFE_SERIALIZATION; public class SerializeClassChecker { - private static final Logger logger = LoggerFactory.getLogger(SerializeClassChecker.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SerializeClassChecker.class); private static volatile SerializeClassChecker INSTANCE = null; @@ -54,7 +56,7 @@ public class SerializeClassChecker { OPEN_CHECK_CLASS = Boolean.parseBoolean(openCheckClass); String blockAllClassExceptAllow = ConfigurationUtils.getProperty(CLASS_DESERIALIZE_BLOCK_ALL, "false"); - + BLOCK_ALL_CLASS_EXCEPT_ALLOW = Boolean.parseBoolean(blockAllClassExceptAllow); String[] lines; @@ -74,7 +76,7 @@ public class SerializeClassChecker { } } catch (IOException e) { - logger.error("Failed to load blocked class list! Will ignore default blocked list.", e); + logger.error(COMMON_IO_EXCEPTION, "", "", "Failed to load blocked class list! Will ignore default blocked list.", e); } String allowedClassList = ConfigurationUtils.getProperty(CLASS_DESERIALIZE_ALLOWED_LIST, "").trim().toLowerCase(Locale.ROOT); @@ -114,11 +116,11 @@ public class SerializeClassChecker { /** * Check if a class is in block list, using prefix match * - * @throws IllegalArgumentException if class is blocked * @param name class name ( all are convert to lower case ) + * @throws IllegalArgumentException if class is blocked */ public void validateClass(String name) { - if(!OPEN_CHECK_CLASS){ + if (!OPEN_CHECK_CLASS) { return; } @@ -150,14 +152,14 @@ public class SerializeClassChecker { private void error(String name) { String notice = "Trigger the safety barrier! " + - "Catch not allowed serialize class. " + - "Class name: " + name + " . " + - "This means currently maybe being attacking by others." + - "If you are sure this is a mistake, " + - "please add this class name to `" + CLASS_DESERIALIZE_ALLOWED_LIST + - "` as a system environment property."; + "Catch not allowed serialize class. " + + "Class name: " + name + " . " + + "This means currently maybe being attacking by others." + + "If you are sure this is a mistake, " + + "please add this class name to `" + CLASS_DESERIALIZE_ALLOWED_LIST + + "` as a system environment property."; if (counter.incrementAndGet() % 1000 == 0 || counter.get() < 100) { - logger.error(notice); + logger.error(PROTOCOL_UNSAFE_SERIALIZATION, "", "", notice); } throw new IllegalArgumentException(notice); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringUtils.java index 8d7100760c..695755a0a6 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringUtils.java @@ -17,7 +17,7 @@ package org.apache.dubbo.common.utils; import org.apache.dubbo.common.io.UnsafeStringWriter; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.io.PrintWriter; @@ -46,6 +46,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SEPARATOR_REGEX; import static org.apache.dubbo.common.constants.CommonConstants.UNDERLINE_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_JSON_CONVERT_EXCEPTION; /** * StringUtils @@ -57,7 +58,7 @@ public final class StringUtils { public static final int INDEX_NOT_FOUND = -1; public static final String[] EMPTY_STRING_ARRAY = new String[0]; - private static final Logger logger = LoggerFactory.getLogger(StringUtils.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(StringUtils.class); private static final Pattern KVP_PATTERN = Pattern.compile("([_.a-zA-Z0-9][-_.a-zA-Z0-9]*)[=](.*)"); //key value pair pattern. private static final Pattern NUM_PATTERN = Pattern.compile("^\\d+$"); private static final Pattern PARAMETERS_PATTERN = Pattern.compile("^\\[((\\s*\\{\\s*[\\w_\\-\\.]+\\s*:\\s*.+?\\s*\\}\\s*,?\\s*)+)\\s*\\]$"); @@ -1031,7 +1032,7 @@ public final class StringUtils { try { buf.append(JsonUtils.getJson().toJson(arg)); } catch (Exception e) { - logger.warn(e.getMessage(), e); + logger.warn(COMMON_JSON_CONVERT_EXCEPTION, "", "", e.getMessage(), e); buf.append(arg); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractConfig.java index 9996c919c3..53109a3564 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractConfig.java @@ -22,7 +22,7 @@ import org.apache.dubbo.common.config.Environment; import org.apache.dubbo.common.config.InmemoryConfiguration; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.CollectionUtils; @@ -60,6 +60,9 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_OVERRIDE_FIELD; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_REFLECT; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; import static org.apache.dubbo.common.utils.ClassUtils.isSimpleType; import static org.apache.dubbo.common.utils.ReflectUtils.findMethodByMethodSignature; import static org.apache.dubbo.config.Constants.PARAMETERS; @@ -71,7 +74,7 @@ import static org.apache.dubbo.config.Constants.PARAMETERS; */ public abstract class AbstractConfig implements Serializable { - protected static final Logger logger = LoggerFactory.getLogger(AbstractConfig.class); + protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractConfig.class); private static final long serialVersionUID = 4267533505537413570L; /** @@ -494,7 +497,7 @@ public abstract class AbstractConfig implements Serializable { } } } catch (Throwable e) { - logger.error(e.getMessage(), e); + logger.error(COMMON_FAILED_REFLECT, "", "", e.getMessage(), e); } } } @@ -648,7 +651,7 @@ public abstract class AbstractConfig implements Serializable { } } catch (Throwable t) { - logger.error("Failed to override field value of config bean: " + this, t); + logger.error(COMMON_FAILED_OVERRIDE_FIELD, "", "", "Failed to override field value of config bean: " + this, t); throw new IllegalStateException("Failed to override field value of config bean: " + this, t); } } @@ -703,7 +706,7 @@ public abstract class AbstractConfig implements Serializable { processExtraRefresh(preferredPrefix, subPropsConfiguration); } catch (Exception e) { - logger.error("Failed to override field value of config bean: " + this, e); + logger.error(COMMON_FAILED_OVERRIDE_FIELD, "", "", "Failed to override field value of config bean: " + this, e); throw new IllegalStateException("Failed to override field value of config bean: " + this, e); } @@ -811,7 +814,7 @@ public abstract class AbstractConfig implements Serializable { private boolean isPropertySet(Method[] methods, String propertyName) { try { String getterName = calculatePropertyToGetter(propertyName); - Method getterMethod = findGetMethod(methods,getterName); + Method getterMethod = findGetMethod(methods, getterName); if (getterMethod == null) { return false; } @@ -943,13 +946,13 @@ public abstract class AbstractConfig implements Serializable { buf.append('\"'); } } catch (Exception e) { - logger.warn(e.getMessage(), e); + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", e.getMessage(), e); } } buf.append(" />"); return buf.toString(); } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", t.getMessage(), t); return super.toString(); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java index 315dc36ae8..2122ebbbd1 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java @@ -53,6 +53,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_NO_METHOD_FOUND; import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; @@ -84,7 +85,7 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { * The remote service group the customer/provider side will reference */ protected String group; - + protected ServiceMetadata serviceMetadata; /** * Local impl class name for the service interface @@ -253,7 +254,7 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { for (RegistryConfig registryConfig : registries) { if (!registryConfig.isValid()) { throw new IllegalStateException("No registry config found or it's not a valid config! " + - "The registry config is: " + registryConfig); + "The registry config is: " + registryConfig); } } } @@ -285,6 +286,7 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { /** * To obtain the method list in the port, use reflection when in native mode and javassist otherwise. + * * @param interfaceClass * @return */ @@ -312,7 +314,7 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { return; } if (!interfaceClass.isInterface()) { - throw new IllegalStateException(interfaceName+" is not an interface"); + throw new IllegalStateException(interfaceName + " is not an interface"); } // Auto create MethodConfig/ArgumentConfig according to config props @@ -378,7 +380,7 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { "" + ""; if (ignoreInvalidMethodConfig) { - logger.warn(msg); + logger.warn(CONFIG_NO_METHOD_FOUND, "", "", msg); return false; } else { throw new IllegalStateException(msg); @@ -390,7 +392,7 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { String msg = "Found invalid method config, the interface " + interfaceClass.getName() + " not found method \"" + methodName + "\" : [" + methodConfig + "]"; if (ignoreInvalidMethodConfig) { - logger.warn(msg); + logger.warn(CONFIG_NO_METHOD_FOUND, "", "", msg); return false; } else { throw new IllegalStateException(msg); @@ -437,18 +439,18 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { verifyStubAndLocal(stub, "Stub", interfaceClass); } - private void verifyStubAndLocal(String className, String label, Class interfaceClass){ + private void verifyStubAndLocal(String className, String label, Class interfaceClass) { if (ConfigUtils.isNotEmpty(className)) { Class localClass = ConfigUtils.isDefault(className) ? - ReflectUtils.forName(interfaceClass.getName() + label) : ReflectUtils.forName(className); - verify(interfaceClass, localClass); - } + ReflectUtils.forName(interfaceClass.getName() + label) : ReflectUtils.forName(className); + verify(interfaceClass, localClass); + } } private void verify(Class interfaceClass, Class localClass) { if (!interfaceClass.isAssignableFrom(localClass)) { throw new IllegalStateException("The local implementation class " + localClass.getName() + - " not implement interface " + interfaceClass.getName()); + " not implement interface " + interfaceClass.getName()); } try { @@ -456,7 +458,7 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { ReflectUtils.findConstructor(localClass, interfaceClass); } catch (NoSuchMethodException e) { throw new IllegalStateException("No such constructor \"public " + localClass.getSimpleName() + - "(" + interfaceClass.getName() + ")\" in local implementation class " + localClass.getName()); + "(" + interfaceClass.getName() + ")\" in local implementation class " + localClass.getName()); } } @@ -524,7 +526,7 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { } } } - + protected void computeValidRegistryIds() { if (application != null && notHasSelfRegistryProperty()) { setRegistries(application.getRegistries()); @@ -640,8 +642,8 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { } /** - * @deprecated Use {@link AbstractInterfaceConfig#setScopeModel(ScopeModel)} * @param application + * @deprecated Use {@link AbstractInterfaceConfig#setScopeModel(ScopeModel)} */ @Deprecated public void setApplication(ApplicationConfig application) { @@ -659,8 +661,8 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { } /** - * @deprecated Use {@link AbstractInterfaceConfig#setScopeModel(ScopeModel)} * @param module + * @deprecated Use {@link AbstractInterfaceConfig#setScopeModel(ScopeModel)} */ @Deprecated public void setModule(ModuleConfig module) { @@ -877,7 +879,7 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { public String getVersion(AbstractInterfaceConfig interfaceConfig) { return StringUtils.isEmpty(getVersion()) ? (interfaceConfig != null ? interfaceConfig.getVersion() : getVersion()) : getVersion(); } - + public String getVersion() { return version; } @@ -893,11 +895,11 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { public void setGroup(String group) { this.group = group; } - + public String getInterface() { return interfaceName; } - + public void setInterface(String interfaceName) { this.interfaceName = interfaceName; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/ApplicationConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/ApplicationConfig.java index 3abf10682d..273ced4f23 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/ApplicationConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/ApplicationConfig.java @@ -32,6 +32,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.READINESS_PROBE_ import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_LOCAL_FILE_CACHE_ENABLED; import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.STARTUP_PROBE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP; import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP_COMPATIBLE; import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE; @@ -56,7 +57,7 @@ import java.util.Set; import org.apache.dubbo.common.compiler.support.AdaptiveCompiler; import org.apache.dubbo.common.infra.InfraAdapter; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; @@ -70,7 +71,7 @@ import org.apache.dubbo.rpc.model.ApplicationModel; * @export */ public class ApplicationConfig extends AbstractConfig { - private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationConfig.class); + private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(ApplicationConfig.class); private static final long serialVersionUID = 5508512956753757169L; @@ -236,7 +237,7 @@ public class ApplicationConfig extends AbstractConfig { try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { - LOGGER.warn("Failed to get the hostname of current instance.", e); + LOGGER.warn(COMMON_UNEXPECTED_EXCEPTION,"","","Failed to get the hostname of current instance.", e); hostname = "UNKNOWN"; } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/ProtocolConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/ProtocolConfig.java index 5821ac6442..0903ac94b8 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/ProtocolConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/ProtocolConfig.java @@ -16,11 +16,14 @@ */ package org.apache.dubbo.config; +import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.lang.reflect.Field; import java.util.Map; +import java.util.Optional; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.CommonConstants.SSL_ENABLED_KEY; @@ -579,4 +582,29 @@ public class ProtocolConfig extends AbstractConfig { public void setExtProtocol(String extProtocol) { this.extProtocol = extProtocol; } + + public void mergeProtocol(ProtocolConfig sourceConfig) { + if (sourceConfig == null) { + return; + } + Field[] targetFields = this.getClass().getDeclaredFields(); + try { + Map protocolConfigMap = CollectionUtils.objToMap(sourceConfig); + for (Field targetField : targetFields) { + Optional.ofNullable(protocolConfigMap.get(targetField.getName())).ifPresent(value -> { + try { + targetField.setAccessible(true); + if (targetField.get(this) == null) { + targetField.set(this, value); + } + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + }); + } + } catch (Exception e) { + logger.error("merge protocol config fail, error: ", e); + } + } + } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java b/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java index 0138e06117..493df6b2f0 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java @@ -39,6 +39,7 @@ import java.util.Properties; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; import static org.apache.dubbo.common.constants.CommonConstants.UNLOAD_CLUSTER_RELATED; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; /** * ReferenceConfig @@ -130,8 +131,8 @@ public abstract class ReferenceConfigBase extends AbstractReferenceConfig { super.preProcessRefresh(); if (consumer == null) { consumer = getModuleConfigManager() - .getDefaultConsumer() - .orElseThrow(() -> new IllegalStateException("Default consumer is not initialized")); + .getDefaultConsumer() + .orElseThrow(() -> new IllegalStateException("Default consumer is not initialized")); } } @@ -166,6 +167,7 @@ public abstract class ReferenceConfigBase extends AbstractReferenceConfig { /** * Get service interface class of this reference. * The actual service type of remote provider. + * * @return */ public Class getServiceInterfaceClass() { @@ -187,6 +189,7 @@ public abstract class ReferenceConfigBase extends AbstractReferenceConfig { /** * Get proxy interface class of this reference. * The proxy interface class is used to create proxy instance. + * * @return */ public Class getInterfaceClass() { @@ -208,6 +211,7 @@ public abstract class ReferenceConfigBase extends AbstractReferenceConfig { /** * Determine the interface of the proxy class + * * @param generic * @param interfaceName * @return @@ -303,9 +307,9 @@ public abstract class ReferenceConfigBase extends AbstractReferenceConfig { url = resolve; if (logger.isWarnEnabled()) { if (resolveFile != null) { - logger.warn("Using default dubbo resolve file " + resolveFile + " replace " + interfaceName + "" + resolve + " to p2p invoke remote service."); + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Using default dubbo resolve file " + resolveFile + " replace " + interfaceName + "" + resolve + " to p2p invoke remote service."); } else { - logger.warn("Using -D" + interfaceName + "=" + resolve + " to p2p invoke remote service."); + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Using -D" + interfaceName + "=" + resolve + " to p2p invoke remote service."); } } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/context/AbstractConfigManager.java b/dubbo-common/src/main/java/org/apache/dubbo/config/context/AbstractConfigManager.java index 2078bd9c29..de53b6d860 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/context/AbstractConfigManager.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/context/AbstractConfigManager.java @@ -22,7 +22,7 @@ import org.apache.dubbo.common.config.Environment; import org.apache.dubbo.common.config.PropertiesConfiguration; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.context.LifecycleAdapter; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashSet; @@ -60,13 +60,15 @@ import static java.lang.Boolean.TRUE; import static java.util.Collections.emptyMap; import static java.util.Optional.ofNullable; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_PROPERTY_MISSPELLING; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; import static org.apache.dubbo.config.AbstractConfig.getTagName; public abstract class AbstractConfigManager extends LifecycleAdapter { private static final String CONFIG_NAME_READ_METHOD = "getName"; - private static final Logger logger = LoggerFactory.getLogger(AbstractConfigManager.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractConfigManager.class); private static Set> uniqueConfigTypes = new ConcurrentHashSet<>(); final Map> configsCache = new ConcurrentHashMap<>(); @@ -119,7 +121,7 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { } } catch (Exception e) { String msg = "Illegal '" + ConfigKeys.DUBBO_CONFIG_MODE + "' config value [" + configModeStr + "], available values " + Arrays.toString(ConfigMode.values()); - logger.error(msg, e); + logger.error(COMMON_PROPERTY_MISSPELLING, "", "", msg, e); throw new IllegalArgumentException(msg, e); } @@ -213,7 +215,7 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { C existedConfig = configsMap.get(key); if (existedConfig != null && !isEquals(existedConfig, config)) { String type = config.getClass().getSimpleName(); - logger.warn(String.format("Duplicate %s found, there already has one default %s or more than two %ss have the same id, " + + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", String.format("Duplicate %s found, there already has one default %s or more than two %ss have the same id, " + "you can try to give each %s a different id, override previous config with later config. id: %s, prev: %s, later: %s", type, type, type, type, key, existedConfig, config)); } @@ -224,7 +226,7 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { } protected boolean removeIfAbsent(C config, Map configsMap) { - if(config.getId() != null) { + if (config.getId() != null) { return configsMap.remove(config.getId(), config); } return configsMap.values().removeIf(c -> config == c); @@ -439,7 +441,7 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { case IGNORE: { // ignore later config if (logger.isWarnEnabled() && duplicatedConfigs.add(config)) { - logger.warn(msgPrefix + "keep previous config and ignore later config"); + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", msgPrefix + "keep previous config and ignore later config"); } return Optional.of(oldOne); } @@ -447,7 +449,7 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { // clear previous config, add new config configsMap.clear(); if (logger.isWarnEnabled() && duplicatedConfigs.add(config)) { - logger.warn(msgPrefix + "override previous config with later config"); + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", msgPrefix + "override previous config with later config"); } break; } @@ -455,7 +457,7 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { // override old one's properties with the new one oldOne.overrideWithConfig(config, true); if (logger.isWarnEnabled() && duplicatedConfigs.add(config)) { - logger.warn(msgPrefix + "override previous config with later config"); + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", msgPrefix + "override previous config with later config"); } return Optional.of(oldOne); } @@ -463,7 +465,7 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { // override old one's properties with the new one oldOne.overrideWithConfig(config, false); if (logger.isWarnEnabled() && duplicatedConfigs.add(config)) { - logger.warn(msgPrefix + "override previous config with later config"); + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", msgPrefix + "override previous config with later config"); } return Optional.of(oldOne); } @@ -504,7 +506,7 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { this.addConfig(config); tmpConfigs.add(config); } catch (Exception e) { - logger.error("load config failed, id: " + id + ", type:" + cls.getSimpleName(), e); + logger.error(COMMON_PROPERTY_MISSPELLING, "", "", "load config failed, id: " + id + ", type:" + cls.getSimpleName(), e); throw new IllegalStateException("load config failed, id: " + id + ", type:" + cls.getSimpleName()); } finally { if (addDefaultNameConfig && key != null) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/context/ModuleConfigManager.java b/dubbo-common/src/main/java/org/apache/dubbo/config/context/ModuleConfigManager.java index c7af4f2454..884d060740 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/context/ModuleConfigManager.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/context/ModuleConfigManager.java @@ -18,7 +18,7 @@ package org.apache.dubbo.config.context; import org.apache.dubbo.common.context.ModuleExt; import org.apache.dubbo.common.extension.DisableInject; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.config.AbstractConfig; @@ -46,6 +46,7 @@ import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import static java.util.Optional.ofNullable; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; import static org.apache.dubbo.config.AbstractConfig.getTagName; /** @@ -53,7 +54,7 @@ import static org.apache.dubbo.config.AbstractConfig.getTagName; */ public class ModuleConfigManager extends AbstractConfigManager implements ModuleExt { - private static final Logger logger = LoggerFactory.getLogger(ModuleConfigManager.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ModuleConfigManager.class); public static final String NAME = "moduleConfig"; @@ -204,7 +205,7 @@ public class ModuleConfigManager extends AbstractConfigManager implements Module @Override protected boolean removeIfAbsent(C config, Map configsMap) { - if(super.removeIfAbsent(config, configsMap)) { + if (super.removeIfAbsent(config, configsMap)) { if (config instanceof ReferenceConfigBase || config instanceof ServiceConfigBase) { removeInterfaceConfig((AbstractInterfaceConfig) config); } @@ -240,7 +241,7 @@ public class ModuleConfigManager extends AbstractConfigManager implements Module if (prevConfig.equals(config)) { // Is there any problem with ignoring duplicate and equivalent but different ReferenceConfig instances? if (logger.isWarnEnabled() && duplicatedConfigs.add(config)) { - logger.warn("Ignore duplicated and equal config: " + config); + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Ignore duplicated and equal config: " + config); } return prevConfig; } @@ -252,7 +253,7 @@ public class ModuleConfigManager extends AbstractConfigManager implements Module "If multiple instances are required for the same interface, please use a different group or version."; if (logger.isWarnEnabled() && duplicatedConfigs.add(config)) { - logger.warn(msg); + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", msg); } if (!this.ignoreDuplicatedInterface) { throw new IllegalStateException(msg); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/EnumTypeBuilder.java b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/EnumTypeBuilder.java index 1f5d52a43d..ff926ca297 100755 --- a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/EnumTypeBuilder.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/EnumTypeBuilder.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.metadata.definition.builder; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder; import org.apache.dubbo.metadata.definition.model.TypeDefinition; @@ -25,11 +25,13 @@ import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Map; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; + /** * 2015/1/27. */ public class EnumTypeBuilder implements TypeBuilder { - private static final Logger logger = LoggerFactory.getLogger(TypeDefinitionBuilder.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TypeDefinitionBuilder.class); @Override public boolean accept(Class clazz) { @@ -61,7 +63,7 @@ public class EnumTypeBuilder implements TypeBuilder { } return td; } catch (Throwable t) { - logger.error("There is an error while process class " + clazz, t); + logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", "There is an error while process class " + clazz, t); } return td; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ReflectionMethodDescriptor.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ReflectionMethodDescriptor.java index 27cd407cc3..e63e47bb19 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ReflectionMethodDescriptor.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ReflectionMethodDescriptor.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.model; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.common.utils.ReflectUtils; @@ -32,9 +32,10 @@ import java.util.stream.Stream; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE_ASYNC; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_REFLECT; public class ReflectionMethodDescriptor implements MethodDescriptor { - private static final Logger logger = LoggerFactory.getLogger(ReflectionMethodDescriptor.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReflectionMethodDescriptor.class); private final ConcurrentMap attributeMap = new ConcurrentHashMap<>(); public final String methodName; @@ -57,7 +58,7 @@ public class ReflectionMethodDescriptor implements MethodDescriptor { try { returnTypesResult = ReflectUtils.getReturnTypes(method); } catch (Throwable throwable) { - logger.error( + logger.error(COMMON_FAILED_REFLECT, "", "", "fail to get return types. Method name: " + methodName + " Declaring class:" + method.getDeclaringClass() .getName(), throwable); returnTypesResult = new Type[]{returnClass, returnClass}; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModel.java index 514d3cabeb..a749fef584 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModel.java @@ -21,7 +21,7 @@ import org.apache.dubbo.common.config.Environment; import org.apache.dubbo.common.extension.ExtensionAccessor; import org.apache.dubbo.common.extension.ExtensionDirector; import org.apache.dubbo.common.extension.ExtensionScope; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.StringUtils; @@ -35,8 +35,10 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNABLE_DESTROY_MODEL; + public abstract class ScopeModel implements ExtensionAccessor { - protected static final Logger LOGGER = LoggerFactory.getLogger(ScopeModel.class); + protected static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(ScopeModel.class); /** * The internal id is used to represent the hierarchy of the model tree, such as: @@ -122,7 +124,7 @@ public abstract class ScopeModel implements ExtensionAccessor { extensionDirector.destroy(); } } catch (Throwable t) { - LOGGER.error("Error happened when destroying ScopeModel.", t); + LOGGER.error(CONFIG_UNABLE_DESTROY_MODEL, "", "", "Error happened when destroying ScopeModel.", t); } } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/logger/support/FailsafeErrorTypeAwareLoggerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/logger/support/FailsafeErrorTypeAwareLoggerTest.java index 6eb3605556..ce101f9c30 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/logger/support/FailsafeErrorTypeAwareLoggerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/logger/support/FailsafeErrorTypeAwareLoggerTest.java @@ -24,6 +24,7 @@ import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ADDRESS_INVALID; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; @@ -45,8 +46,8 @@ public class FailsafeErrorTypeAwareLoggerTest { doThrow(new RuntimeException()).when(failLogger).debug(anyString()); doThrow(new RuntimeException()).when(failLogger).trace(anyString()); - failsafeLogger.error("1-1", "Registry center", "May be it's offline.", "error"); - failsafeLogger.warn("1-1", "Registry center", "May be it's offline.", "warn"); + failsafeLogger.error(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "error"); + failsafeLogger.warn(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "warn"); doThrow(new RuntimeException()).when(failLogger).error(any(Throwable.class)); doThrow(new RuntimeException()).when(failLogger).warn(any(Throwable.class)); @@ -54,8 +55,8 @@ public class FailsafeErrorTypeAwareLoggerTest { doThrow(new RuntimeException()).when(failLogger).debug(any(Throwable.class)); doThrow(new RuntimeException()).when(failLogger).trace(any(Throwable.class)); - failsafeLogger.error("1-1", "Registry center", "May be it's offline.", "error", new Exception("error")); - failsafeLogger.warn("1-1", "Registry center", "May be it's offline.", "warn", new Exception("warn")); + failsafeLogger.error(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "error", new Exception("error")); + failsafeLogger.warn(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "warn", new Exception("warn")); } @Test @@ -63,14 +64,14 @@ public class FailsafeErrorTypeAwareLoggerTest { Logger successLogger = mock(Logger.class); FailsafeErrorTypeAwareLogger failsafeLogger = new FailsafeErrorTypeAwareLogger(successLogger); - failsafeLogger.error("1-1", "Registry center", "May be it's offline.", "error"); - failsafeLogger.warn("1-1", "Registry center", "May be it's offline.", "warn"); + failsafeLogger.error(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "error"); + failsafeLogger.warn(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "warn"); verify(successLogger).error(anyString()); verify(successLogger).warn(anyString()); - failsafeLogger.error("1-1", "Registry center", "May be it's offline.", "error", new Exception("error")); - failsafeLogger.warn("1-1", "Registry center", "May be it's offline.", "warn", new Exception("warn")); + failsafeLogger.error(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "error", new Exception("error")); + failsafeLogger.warn(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "warn", new Exception("warn")); } @Test @@ -90,10 +91,10 @@ public class FailsafeErrorTypeAwareLoggerTest { ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FailsafeErrorTypeAwareLoggerTest.class); - logger.error("1-1", "Registry center", "May be it's offline.", + logger.error(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "error message", new Exception("error")); - logger.error("-1", "Registry center", "May be it's offline.", + logger.error(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "error message", new Exception("error")); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CollectionUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CollectionUtilsTest.java index f128862cc3..d40ab82ab4 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CollectionUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CollectionUtilsTest.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.common.utils; +import org.apache.dubbo.config.ProtocolConfig; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -200,6 +201,14 @@ public class CollectionUtilsTest { assertEquals(expected, CollectionUtils.toMap("a", 1, "b", 2, "c", 3)); } + @Test + public void testObjectToMap() throws Exception { + ProtocolConfig protocolConfig=new ProtocolConfig(); + protocolConfig.setSerialization("fastjson2"); + + assertFalse(CollectionUtils.objToMap(protocolConfig).isEmpty()); + } + @Test public void testToMap2() throws Exception { Assertions.assertThrows(IllegalArgumentException.class, () -> toMap("a", "b", "c")); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/config/context/ConfigManagerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/config/context/ConfigManagerTest.java index 284c00c2e1..3a59d30ce0 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/config/context/ConfigManagerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/config/context/ConfigManagerTest.java @@ -41,6 +41,7 @@ import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMET import static org.apache.dubbo.config.context.ConfigManager.DUBBO_CONFIG_MODE; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; @@ -192,6 +193,14 @@ public class ConfigManagerTest { assertEquals(config, configs.iterator().next()); assertFalse(configManager.getDefaultProtocols().isEmpty()); assertEquals(configs, moduleConfigManager.getProtocols()); + assertNotEquals(20881, config.getPort()); + assertNotEquals(config.getSerialization(),"fastjson2"); + ProtocolConfig defaultConfig = new ProtocolConfig(); + defaultConfig.setPort(20881); + defaultConfig.setSerialization("fastjson2"); + config.mergeProtocol(defaultConfig); + assertEquals(config.getPort(),20881); + assertEquals(config.getSerialization(),"fastjson2"); } // Test RegistryConfig correlative methods diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java index 756e726280..6f50193e7f 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java @@ -80,6 +80,9 @@ import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_SPLIT_P import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_REFRESH_INSTANCE_ERROR; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_REGISTER_INSTANCE_ERROR; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_START_MODEL; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_EXECUTE_DESTORY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_INIT_CONFIG_CENTER; import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; import static org.apache.dubbo.common.utils.StringUtils.isEmpty; import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty; @@ -659,7 +662,7 @@ public class DefaultApplicationDeployer extends AbstractDeployer impleme // wait for refer finish waitReferFinish(); } catch (Throwable e) { - logger.warn("wait for export/refer services occurred an exception", e); + logger.warn(CONFIG_FAILED_WAIT_EXPORT_REFER, "", "", "wait for export/refer services occurred an exception", e); } finally { onModuleStarted(); } @@ -421,7 +423,7 @@ public class DefaultModuleDeployer extends AbstractDeployer impleme exportFuture = CompletableFuture.allOf(asyncExportingFutures.toArray(new CompletableFuture[0])); exportFuture.get(); } catch (Throwable e) { - logger.warn(getIdentifier() + " export services occurred an exception: " + e.toString()); + logger.warn(CONFIG_FAILED_EXPORT_SERVICE, "","",getIdentifier() + " export services occurred an exception: " + e.toString()); } finally { logger.info(getIdentifier() + " export services finished."); asyncExportingFutures.clear(); @@ -434,7 +436,7 @@ public class DefaultModuleDeployer extends AbstractDeployer impleme referFuture = CompletableFuture.allOf(asyncReferringFutures.toArray(new CompletableFuture[0])); referFuture.get(); } catch (Throwable e) { - logger.warn(getIdentifier() + " refer services occurred an exception: " + e.toString()); + logger.warn(CONFIG_FAILED_REFER_SERVICE, "", "", getIdentifier() + " refer services occurred an exception: " + e.toString()); } finally { logger.info(getIdentifier() + " refer services finished."); asyncReferringFutures.clear(); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/FrameworkModelCleaner.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/FrameworkModelCleaner.java index 473ddf7156..258181d2f2 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/FrameworkModelCleaner.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/FrameworkModelCleaner.java @@ -17,7 +17,7 @@ package org.apache.dubbo.config.deploy; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.model.FrameworkModel; @@ -25,12 +25,14 @@ import org.apache.dubbo.rpc.model.ScopeModelDestroyListener; import java.util.concurrent.atomic.AtomicBoolean; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_PROTOCOL; + /** * A cleaner to release resources of framework model */ public class FrameworkModelCleaner implements ScopeModelDestroyListener { - private static final Logger logger = LoggerFactory.getLogger(FrameworkModelCleaner.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FrameworkModelCleaner.class); private final AtomicBoolean protocolDestroyed = new AtomicBoolean(false); @@ -65,7 +67,7 @@ public class FrameworkModelCleaner implements ScopeModelDestroyListener) type); } else { - logger.warn("Using non-singleton ReferenceConfig and ReferenceCache at the same time may cause memory leak. " + + logger.warn(CONFIG_API_WRONG_USE, "the api method is being used incorrectly", "", "Using non-singleton ReferenceConfig and ReferenceCache at the same time may cause memory leak. " + "Call ReferenceConfig#get() directly for non-singleton ReferenceConfig instead of using ReferenceCache#get(ReferenceConfig)"); } if (proxy == null) { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/SimpleReferenceCache.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/SimpleReferenceCache.java index f97bf1655e..65389f95b5 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/SimpleReferenceCache.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/SimpleReferenceCache.java @@ -18,7 +18,7 @@ package org.apache.dubbo.config.utils; import org.apache.dubbo.common.BaseServiceMetadata; import org.apache.dubbo.common.config.ReferenceCache; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; @@ -33,6 +33,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_API_WRONG_USE; + /** * A simple util class for cache {@link ReferenceConfigBase}. *

@@ -42,7 +44,7 @@ import java.util.concurrent.atomic.AtomicInteger; * You can implement and use your own {@link ReferenceConfigBase} cache if you need use complicate strategy. */ public class SimpleReferenceCache implements ReferenceCache { - private static final Logger logger = LoggerFactory.getLogger(SimpleReferenceCache.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SimpleReferenceCache.class); public static final String DEFAULT_NAME = "_DEFAULT_"; /** * Create the key with the Group, Interface and version attribute of {@link ReferenceConfigBase}. @@ -117,7 +119,7 @@ public class SimpleReferenceCache implements ReferenceCache { if (singleton) { proxy = get(key, (Class) type); } else { - logger.warn("Using non-singleton ReferenceConfig and ReferenceCache at the same time may cause memory leak. " + + logger.warn(CONFIG_API_WRONG_USE, "", "", "Using non-singleton ReferenceConfig and ReferenceCache at the same time may cause memory leak. " + "Call ReferenceConfig#get() directly for non-singleton ReferenceConfig instead of using ReferenceCache#get(ReferenceConfig)"); } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessor.java index 95dc4b5457..9bb4cf90e6 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessor.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.config.spring.beans.factory.annotation; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.ReflectUtils; @@ -81,6 +81,9 @@ import java.util.Set; import static com.alibaba.spring.util.ObjectUtils.of; import static java.util.Arrays.asList; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_NO_ANNOTATIONS_FOUND; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_NO_BEANS_SCANNED; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUPLICATED_BEAN_DEFINITION; import static org.apache.dubbo.common.utils.AnnotationUtils.filterDefaultValues; import static org.apache.dubbo.config.spring.beans.factory.annotation.ServiceBeanNameBuilder.create; import static org.apache.dubbo.config.spring.util.DubboAnnotationUtils.resolveInterfaceName; @@ -111,7 +114,7 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos com.alibaba.dubbo.config.annotation.Service.class ); - private final Logger logger = LoggerFactory.getLogger(getClass()); + private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); protected final Set packagesToScan; @@ -187,7 +190,7 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos scanned = true; if (CollectionUtils.isEmpty(packagesToScan)) { if (logger.isWarnEnabled()) { - logger.warn("packagesToScan is empty , ServiceBean registry will be ignored!"); + logger.warn(CONFIG_NO_BEANS_SCANNED, "", "", "packagesToScan is empty , ServiceBean registry will be ignored!"); } return; } @@ -236,7 +239,7 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos } } else { if (logger.isWarnEnabled()) { - logger.warn("No class annotated by Dubbo @Service was found under package [" + logger.warn(CONFIG_NO_ANNOTATIONS_FOUND,"No annotations were found on the class","","No class annotated by Dubbo @Service was found under package [" + packageToScan + "], ignore re-scanned classes: " + scanExcludeFilter.getExcludedCount()); } } @@ -590,7 +593,7 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos String msg = "Found duplicated BeanDefinition of service interface [" + serviceInterface + "] with bean name [" + serviceBeanName + "], existing definition [ " + existingDefinition + "], new definition [" + serviceBeanDefinition + "]"; - logger.error(msg); + logger.error(CONFIG_DUPLICATED_BEAN_DEFINITION, "", "", msg); throw new BeanDefinitionStoreException(serviceBeanDefinition.getResourceDescription(), serviceBeanName, msg); } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboDeployApplicationListener.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboDeployApplicationListener.java index 7aa7dd2822..37c2343604 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboDeployApplicationListener.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboDeployApplicationListener.java @@ -17,6 +17,7 @@ package org.apache.dubbo.config.spring.context; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_STOP_DUBBO_ERROR; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_START_MODEL; import static org.springframework.util.ObjectUtils.nullSafeEquals; import java.util.concurrent.Future; @@ -116,9 +117,9 @@ public class DubboDeployApplicationListener implements ApplicationListener LOADER = ExtensionLoader.getExtensionLoader(Container.class); @@ -72,7 +75,7 @@ public class Main { container.stop(); logger.info("Dubbo " + container.getClass().getSimpleName() + " stopped!"); } catch (Throwable t) { - logger.error(t.getMessage(), t); + logger.error(CONFIG_STOP_DUBBO_ERROR, "", "", t.getMessage(), t); } try { LOCK.lock(); @@ -91,14 +94,14 @@ public class Main { } System.out.println(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]").format(new Date()) + " Dubbo service server started!"); } catch (RuntimeException e) { - logger.error(e.getMessage(), e); + logger.error(CONFIG_START_DUBBO_ERROR, "", "", e.getMessage(), e); System.exit(1); } try { LOCK.lock(); STOP.await(); } catch (InterruptedException e) { - logger.warn("Dubbo service server stopped, interrupted by other thread!", e); + logger.warn(COMMON_THREAD_INTERRUPTED_EXCEPTION, "", "", "Dubbo service server stopped, interrupted by other thread!", e); } finally { LOCK.unlock(); } diff --git a/dubbo-container/dubbo-container-spring/src/main/java/org/apache/dubbo/container/spring/SpringContainer.java b/dubbo-container/dubbo-container-spring/src/main/java/org/apache/dubbo/container/spring/SpringContainer.java index e3c0040328..94e094e6a4 100644 --- a/dubbo-container/dubbo-container-spring/src/main/java/org/apache/dubbo/container/spring/SpringContainer.java +++ b/dubbo-container/dubbo-container-spring/src/main/java/org/apache/dubbo/container/spring/SpringContainer.java @@ -16,13 +16,15 @@ */ package org.apache.dubbo.container.spring; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.container.Container; import org.springframework.context.support.ClassPathXmlApplicationContext; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_STOP_DUBBO_ERROR; + /** * SpringContainer. (SPI, Singleton, ThreadSafe) * @@ -32,7 +34,7 @@ public class SpringContainer implements Container { public static final String SPRING_CONFIG = "dubbo.spring.config"; public static final String DEFAULT_SPRING_CONFIG = "classpath*:META-INF/spring/*.xml"; - private static final Logger logger = LoggerFactory.getLogger(SpringContainer.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SpringContainer.class); static ClassPathXmlApplicationContext context; public static ClassPathXmlApplicationContext getContext() { @@ -59,7 +61,7 @@ public class SpringContainer implements Container { context = null; } } catch (Throwable e) { - logger.error(e.getMessage(), e); + logger.error(CONFIG_STOP_DUBBO_ERROR, "", "", e.getMessage(), e); } } diff --git a/dubbo-dependencies-bom/pom.xml b/dubbo-dependencies-bom/pom.xml index e80d03f62c..b5eaa81b39 100644 --- a/dubbo-dependencies-bom/pom.xml +++ b/dubbo-dependencies-bom/pom.xml @@ -14,7 +14,9 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - --> + --> + 4.0.0 @@ -139,7 +141,7 @@ 3.0.19.Final 8.5.78 0.5.3 - 2.1.0 + 2.1.2 1.47.0 0.8.1 1.2.1 @@ -193,6 +195,18 @@ pom import + + io.netty + netty-bom + ${netty4_version} + pom + import + + + io.netty + netty-all + ${netty4_version} + org.javassist javassist @@ -203,11 +217,6 @@ netty ${netty_version} - - io.netty - netty-all - ${netty4_version} - org.apache.mina mina-core diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java index d136e373fd..6c5e14e680 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java @@ -18,7 +18,7 @@ package org.apache.dubbo.validation.support.jvalidation; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.bytecode.ClassGenerator; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.validation.MethodValidated; @@ -67,6 +67,8 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION; + /** * Implementation of JValidation. JValidation is invoked if configuration validation attribute value is 'jvalidation'. *

@@ -75,7 +77,7 @@ import java.util.concurrent.ConcurrentHashMap;
  */
 public class JValidator implements Validator {
 
-    private static final Logger logger = LoggerFactory.getLogger(JValidator.class);
+    private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(JValidator.class);
 
     private final Class clazz;
 
@@ -116,7 +118,7 @@ public class JValidator implements Validator {
             }
             return parameterBean;
         } catch (Throwable e) {
-            logger.warn(e.getMessage(), e);
+            logger.warn(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", e.getMessage(), e);
             return null;
         }
     }
diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java
index bd2461f92e..542bf33e3c 100644
--- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java
+++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java
@@ -18,7 +18,7 @@ package org.apache.dubbo.validation.support.jvalidation;
 
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.bytecode.ClassGenerator;
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.common.utils.ReflectUtils;
 import org.apache.dubbo.validation.MethodValidated;
@@ -67,6 +67,8 @@ import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION;
+
 /**
  * Implementation of JValidationNew. JValidationNew is invoked if configuration validation attribute value is 'jvalidationNew'.
  * 
@@ -75,7 +77,7 @@ import java.util.concurrent.ConcurrentHashMap;
  */
 public class JValidatorNew implements Validator {
 
-    private static final Logger logger = LoggerFactory.getLogger(JValidatorNew.class);
+    private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(JValidatorNew.class);
 
     private final Class clazz;
 
@@ -116,7 +118,7 @@ public class JValidatorNew implements Validator {
             }
             return parameterBean;
         } catch (Throwable e) {
-            logger.warn(e.getMessage(), e);
+            logger.warn(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", e.getMessage(), e);
             return null;
         }
     }
diff --git a/dubbo-kubernetes/pom.xml b/dubbo-kubernetes/pom.xml
index f5250b30a3..286857ebcc 100644
--- a/dubbo-kubernetes/pom.xml
+++ b/dubbo-kubernetes/pom.xml
@@ -49,11 +49,6 @@
             dubbo-metadata-api
             ${project.parent.version}
         
-
-        
-            io.netty
-            netty-all
-        
         
             io.fabric8
             kubernetes-client
diff --git a/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesMeshEnvListener.java b/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesMeshEnvListener.java
index 300dae3b56..94a58b0d37 100644
--- a/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesMeshEnvListener.java
+++ b/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesMeshEnvListener.java
@@ -16,7 +16,7 @@
  */
 package org.apache.dubbo.registry.kubernetes;
 
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.rpc.cluster.router.mesh.route.MeshAppRuleListener;
 import org.apache.dubbo.rpc.cluster.router.mesh.route.MeshEnvListener;
@@ -32,8 +32,10 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
 
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_LISTEN_KUBERNETES;
+
 public class KubernetesMeshEnvListener implements MeshEnvListener {
-    public static final Logger logger = LoggerFactory.getLogger(KubernetesMeshEnvListener.class);
+    public static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(KubernetesMeshEnvListener.class);
     private volatile static boolean usingApiServer = false;
     private volatile static KubernetesClient kubernetesClient;
     private volatile static String namespace;
@@ -119,7 +121,7 @@ public class KubernetesMeshEnvListener implements MeshEnvListener {
 
             }
         } catch (Exception e) {
-            logger.error("Error occurred when listen kubernetes crd.", e);
+            logger.error(REGISTRY_ERROR_LISTEN_KUBERNETES, "", "", "Error occurred when listen kubernetes crd.", e);
         }
     }
 
@@ -178,7 +180,7 @@ public class KubernetesMeshEnvListener implements MeshEnvListener {
 
             }
         } catch (Exception e) {
-            logger.error("Error occurred when listen kubernetes crd.", e);
+            logger.error(REGISTRY_ERROR_LISTEN_KUBERNETES, "", "", "Error occurred when listen kubernetes crd.", e);
         }
     }
 
diff --git a/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesServiceDiscovery.java b/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesServiceDiscovery.java
index 087de56d31..9c6a49e5a4 100644
--- a/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesServiceDiscovery.java
+++ b/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesServiceDiscovery.java
@@ -17,7 +17,7 @@
 package org.apache.dubbo.registry.kubernetes;
 
 import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.common.utils.StringUtils;
 import org.apache.dubbo.registry.client.AbstractServiceDiscovery;
@@ -53,8 +53,12 @@ import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.stream.Collectors;
 
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNABLE_FIND_SERVICE_KUBERNETES;
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNABLE_MATCH_KUBERNETES;
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNABLE_ACCESS_KUBERNETES;
+
 public class KubernetesServiceDiscovery extends AbstractServiceDiscovery {
-    private final Logger logger = LoggerFactory.getLogger(getClass());
+    private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
 
     private KubernetesClient kubernetesClient;
 
@@ -96,7 +100,7 @@ public class KubernetesServiceDiscovery extends AbstractServiceDiscovery {
                     "Please check your url config." +
                     " Master URL: " + config.getMasterUrl() +
                     " Hostname: " + currentHostname;
-            logger.error(message);
+            logger.error(REGISTRY_UNABLE_ACCESS_KUBERNETES,"","",message);
         } else {
             KubernetesMeshEnvListener.injectKubernetesEnv(kubernetesClient, namespace);
         }
@@ -403,8 +407,8 @@ public class KubernetesServiceDiscovery extends AbstractServiceDiscovery {
                 Pod pod = pods.get(address.getTargetRef().getName());
                 String ip = address.getIp();
                 if (pod == null) {
-                    logger.warn("Unable to match Kubernetes Endpoint address with Pod. " +
-                            "EndpointAddress Hostname: " + address.getTargetRef().getName());
+                    logger.warn(REGISTRY_UNABLE_MATCH_KUBERNETES, "", "", "Unable to match Kubernetes Endpoint address with Pod. " +
+                        "EndpointAddress Hostname: " + address.getTargetRef().getName());
                     continue;
                 }
                 instancePorts.forEach(port -> {
@@ -415,7 +419,7 @@ public class KubernetesServiceDiscovery extends AbstractServiceDiscovery {
                         serviceInstance.getMetadata().putAll(JSONObject.parseObject(properties, Map.class));
                         instances.add(serviceInstance);
                     } else {
-                        logger.warn("Unable to find Service Instance metadata in Pod Annotations. " +
+                        logger.warn(REGISTRY_UNABLE_FIND_SERVICE_KUBERNETES, "", "", "Unable to find Service Instance metadata in Pod Annotations. " +
                                 "Possibly cause: provider has not been initialized successfully. " +
                                 "EndpointAddress Hostname: " + address.getTargetRef().getName());
                     }
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractCacheManager.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractCacheManager.java
index f299353474..73c041a06e 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractCacheManager.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractCacheManager.java
@@ -18,7 +18,7 @@ package org.apache.dubbo.metadata;
 
 import org.apache.dubbo.common.cache.FileCacheStore;
 import org.apache.dubbo.common.cache.FileCacheStoreFactory;
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.common.resource.Disposable;
 import org.apache.dubbo.common.utils.JsonUtils;
@@ -32,8 +32,10 @@ import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_LOAD_MAPPING_CACHE;
+
 public abstract class AbstractCacheManager implements Disposable {
-    protected final Logger logger = LoggerFactory.getLogger(getClass());
+    protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
 
     private ScheduledExecutorService executorService;
 
@@ -61,7 +63,7 @@ public abstract class AbstractCacheManager implements Disposable {
 
             this.executorService.scheduleWithFixedDelay(new CacheRefreshTask<>(this.cacheStore, this.cache, this, fileSize), 10, interval, TimeUnit.MINUTES);
         } catch (Exception e) {
-            logger.error("Load mapping from local cache file error ", e);
+            logger.error(COMMON_FAILED_LOAD_MAPPING_CACHE, "", "", "Load mapping from local cache file error ", e);
         }
     }
 
@@ -117,7 +119,7 @@ public abstract class AbstractCacheManager implements Disposable {
     }
 
     public static class CacheRefreshTask implements Runnable {
-        private final Logger logger = LoggerFactory.getLogger(getClass());
+        private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
         private static final String DEFAULT_COMMENT = "Dubbo cache";
         private final FileCacheStore cacheStore;
         private final LRUCache cache;
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractServiceNameMapping.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractServiceNameMapping.java
index dc4d1c7b6f..68bcfcc315 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractServiceNameMapping.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractServiceNameMapping.java
@@ -17,7 +17,7 @@
 package org.apache.dubbo.metadata;
 
 import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
 import org.apache.dubbo.common.utils.CollectionUtils;
@@ -43,6 +43,7 @@ import static java.util.Collections.emptySet;
 import static java.util.Collections.unmodifiableSet;
 import static java.util.stream.Collectors.toSet;
 import static java.util.stream.Stream.of;
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_LOAD_MAPPING_CACHE;
 import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDED_BY;
 import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBED_SERVICE_NAMES_KEY;
 import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty;
@@ -50,7 +51,7 @@ import static org.apache.dubbo.common.utils.CollectionUtils.toTreeSet;
 import static org.apache.dubbo.common.utils.StringUtils.isBlank;
 
 public abstract class AbstractServiceNameMapping implements ServiceNameMapping {
-    protected final Logger logger = LoggerFactory.getLogger(getClass());
+    protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
     protected ApplicationModel applicationModel;
     private final MappingCacheManager mappingCacheManager;
     private final Map> mappingListeners = new ConcurrentHashMap<>();
@@ -63,13 +64,13 @@ public abstract class AbstractServiceNameMapping implements ServiceNameMapping {
         this.applicationModel = applicationModel;
         boolean enableFileCache = true;
         Optional application = applicationModel.getApplicationConfigManager().getApplication();
-        if(application.isPresent()) {
+        if (application.isPresent()) {
             enableFileCache = Boolean.TRUE.equals(application.get().getEnableFileCache()) ? true : false;
         }
         this.mappingCacheManager = new MappingCacheManager(enableFileCache,
             applicationModel.tryGetApplicationName(),
             applicationModel.getFrameworkModel().getBeanFactory()
-            .getBean(FrameworkExecutorRepository.class).getCacheRefreshingScheduledExecutor());
+                .getBean(FrameworkExecutorRepository.class).getCacheRefreshingScheduledExecutor());
     }
 
     // just for test
@@ -293,7 +294,7 @@ public abstract class AbstractServiceNameMapping implements ServiceNameMapping {
                         }
                     }
                 } catch (Exception e) {
-                    logger.error("Failed getting mapping info from remote center. ", e);
+                    logger.error(COMMON_FAILED_LOAD_MAPPING_CACHE, "", "", "Failed getting mapping info from remote center. ", e);
                 }
                 return mappedServices;
             }
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java
index 9453f4b287..b8e39f9cb5 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java
@@ -17,7 +17,7 @@
 package org.apache.dubbo.metadata.report.support;
 
 import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.common.utils.CollectionUtils;
 import org.apache.dubbo.common.utils.ConfigUtils;
@@ -67,6 +67,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.REPORT_METADATA_
 import static org.apache.dubbo.common.constants.CommonConstants.RETRY_PERIOD_KEY;
 import static org.apache.dubbo.common.constants.CommonConstants.RETRY_TIMES_KEY;
 import static org.apache.dubbo.common.constants.CommonConstants.SYNC_REPORT_KEY;
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION;
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED_EXPORT_SERVICE;
 import static org.apache.dubbo.common.utils.StringUtils.replace;
 import static org.apache.dubbo.metadata.report.support.Constants.CACHE;
 import static org.apache.dubbo.metadata.report.support.Constants.DEFAULT_METADATA_REPORT_CYCLE_REPORT;
@@ -82,7 +84,7 @@ public abstract class AbstractMetadataReport implements MetadataReport {
     private static final int ONE_DAY_IN_MILLISECONDS = 60 * 24 * 60 * 1000;
     private static final int FOUR_HOURS_IN_MILLISECONDS = 60 * 4 * 60 * 1000;
     // Log output
-    protected final Logger logger = LoggerFactory.getLogger(getClass());
+    protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
 
     // Local disk cache, where the special key value.registries records the list of metadata centers, and the others are the list of notified service providers
     final Properties properties = new Properties();
@@ -203,7 +205,7 @@ public abstract class AbstractMetadataReport implements MetadataReport {
             } else {
                 reportCacheExecutor.execute(new SaveProperties(lastCacheChanged.incrementAndGet()));
             }
-            logger.warn("Failed to save service store file, cause: " + e.getMessage(), e);
+            logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to save service store file, cause: " + e.getMessage(), e);
         }
     }
 
@@ -215,7 +217,7 @@ public abstract class AbstractMetadataReport implements MetadataReport {
                     logger.info("Load service store file " + file + ", data: " + properties);
                 }
             } catch (Throwable e) {
-                logger.warn("Failed to load service store file " + file, e);
+                logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to load service store file" + file, e);
             }
         }
     }
@@ -239,7 +241,7 @@ public abstract class AbstractMetadataReport implements MetadataReport {
             }
 
         } catch (Throwable t) {
-            logger.warn(t.getMessage(), t);
+            logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", t.getMessage(), t);
         }
     }
 
@@ -284,7 +286,7 @@ public abstract class AbstractMetadataReport implements MetadataReport {
             // retry again. If failed again, throw exception.
             failedReports.put(providerMetadataIdentifier, serviceDefinition);
             metadataReportRetry.startRetryTask();
-            logger.error("Failed to put provider metadata " + providerMetadataIdentifier + " in  " + serviceDefinition + ", cause: " + e.getMessage(), e);
+            logger.error(PROXY_FAILED_EXPORT_SERVICE, "", "", "Failed to put provider metadata " + providerMetadataIdentifier + " in  " + serviceDefinition + ", cause: " + e.getMessage(), e);
         }
     }
 
@@ -312,7 +314,7 @@ public abstract class AbstractMetadataReport implements MetadataReport {
             // retry again. If failed again, throw exception.
             failedReports.put(consumerMetadataIdentifier, serviceParameterMap);
             metadataReportRetry.startRetryTask();
-            logger.error("Failed to put consumer metadata " + consumerMetadataIdentifier + ";  " + serviceParameterMap + ", cause: " + e.getMessage(), e);
+            logger.error(PROXY_FAILED_EXPORT_SERVICE, "", "", "Failed to put consumer metadata " + consumerMetadataIdentifier + ";  " + serviceParameterMap + ", cause: " + e.getMessage(), e);
         }
     }
 
@@ -435,7 +437,7 @@ public abstract class AbstractMetadataReport implements MetadataReport {
     }
 
     class MetadataReportRetry {
-        protected final Logger logger = LoggerFactory.getLogger(getClass());
+        protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
 
         final ScheduledExecutorService retryExecutor = Executors.newScheduledThreadPool(0, new NamedThreadFactory("DubboMetadataReportRetryTimer", true));
         volatile ScheduledFuture retryScheduledFuture;
@@ -468,7 +470,7 @@ public abstract class AbstractMetadataReport implements MetadataReport {
                                     cancelRetryTask();
                                 }
                             } catch (Throwable t) { // Defensive fault tolerance
-                                logger.error("Unexpected error occur at failed retry, cause: " + t.getMessage(), t);
+                                logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", "Unexpected error occur at failed retry, cause: " + t.getMessage(), t);
                             }
                         }, 500, retryPeriod, TimeUnit.MILLISECONDS);
                     }
diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactory.java
index b2a51422f1..7ac9aabdca 100644
--- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactory.java
+++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactory.java
@@ -17,7 +17,7 @@
 package org.apache.dubbo.metadata.report.support;
 
 import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.metadata.report.MetadataReport;
 import org.apache.dubbo.metadata.report.MetadataReportFactory;
@@ -27,10 +27,12 @@ import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.locks.ReentrantLock;
 
 import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY;
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION;
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED_EXPORT_SERVICE;
 
 public abstract class AbstractMetadataReportFactory implements MetadataReportFactory {
 
-    private static final Logger logger = LoggerFactory.getLogger(AbstractMetadataReportFactory.class);
+    private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractMetadataReportFactory.class);
     private static final String EXPORT_KEY = "export";
     private static final String REFER_KEY = "refer";
 
@@ -67,7 +69,7 @@ public abstract class AbstractMetadataReportFactory implements MetadataReportFac
                 metadataReport = createMetadataReport(url);
             } catch (Exception e) {
                 if (!check) {
-                    logger.warn("The metadata reporter failed to initialize", e);
+                    logger.warn(PROXY_FAILED_EXPORT_SERVICE, "", "", "The metadata reporter failed to initialize", e);
                 } else {
                     throw e;
                 }
@@ -91,11 +93,11 @@ public abstract class AbstractMetadataReportFactory implements MetadataReportFac
         lock.lock();
         try {
             for (MetadataReport metadataReport : serviceStoreMap.values()) {
-                try{
+                try {
                     metadataReport.destroy();
-                }catch (Throwable ignored){
+                } catch (Throwable ignored) {
                     // ignored
-                    logger.warn(ignored.getMessage(),ignored);
+                    logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", ignored.getMessage(), ignored);
                 }
             }
             serviceStoreMap.clear();
diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtils.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtils.java
index 416590ff35..9bac9d65dc 100644
--- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtils.java
+++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtils.java
@@ -17,10 +17,11 @@
 package org.apache.dubbo.metadata.annotation.processing.util;
 
 
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 
 import static java.lang.String.format;
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METADATA_PROCESSOR;
 
 /**
  * Logger Utils
@@ -29,7 +30,7 @@ import static java.lang.String.format;
  */
 public interface LoggerUtils {
 
-    Logger LOGGER = LoggerFactory.getLogger("dubbo-metadata-processor");
+    ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger("dubbo-metadata-processor");
 
     static void info(String format, Object... args) {
         if (LOGGER.isInfoEnabled()) {
@@ -39,7 +40,7 @@ public interface LoggerUtils {
 
     static void warn(String format, Object... args) {
         if (LOGGER.isWarnEnabled()) {
-            LOGGER.warn(format(format, args));
+            LOGGER.warn(COMMON_METADATA_PROCESSOR, "", "", format(format, args));
         }
     }
 }
diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java
index 677f0750c4..70e624e758 100644
--- a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java
+++ b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java
@@ -55,6 +55,7 @@ import java.util.concurrent.Executor;
 
 import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR;
 import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION;
 import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY;
 import static org.apache.dubbo.common.utils.StringConstantFieldValuePredicate.of;
 import static org.apache.dubbo.common.utils.StringUtils.HYPHEN_CHAR;
@@ -108,9 +109,9 @@ public class NacosMetadataReport extends AbstractMetadataReport {
 
     private void setServerAddr(URL url, Properties properties) {
         StringBuilder serverAddrBuilder =
-                new StringBuilder(url.getHost()) // Host
-                        .append(':')
-                        .append(url.getPort()); // Port
+            new StringBuilder(url.getHost()) // Host
+                .append(':')
+                .append(url.getPort()); // Port
         // Append backup parameter as other servers
         String backup = url.getParameter(BACKUP_KEY);
         if (backup != null) {
@@ -227,7 +228,7 @@ public class NacosMetadataReport extends AbstractMetadataReport {
             }
             return configService.publishConfigCas(key, group, content, (String) ticket);
         } catch (NacosException e) {
-            logger.warn("nacos publishConfigCas failed.", e);
+            logger.warn(REGISTRY_NACOS_EXCEPTION, "", "", "nacos publishConfigCas failed.", e);
             return false;
         }
     }
@@ -273,7 +274,7 @@ public class NacosMetadataReport extends AbstractMetadataReport {
         try {
             return configService.getConfig(dataId, group);
         } catch (NacosException e) {
-            logger.error(e.getMessage());
+            logger.error(REGISTRY_NACOS_EXCEPTION, "", "", e.getMessage());
         }
         return null;
     }
@@ -298,12 +299,12 @@ public class NacosMetadataReport extends AbstractMetadataReport {
     public void addListener(String key, String group, ConfigurationListener listener) {
         String listenerKey = buildListenerKey(key, group);
         NacosConfigListener nacosConfigListener =
-                watchListenerMap.computeIfAbsent(listenerKey, k -> createTargetListener(key, group));
+            watchListenerMap.computeIfAbsent(listenerKey, k -> createTargetListener(key, group));
         nacosConfigListener.addListener(listener);
         try {
             configService.addListener(key, group, nacosConfigListener);
         } catch (NacosException e) {
-            logger.error(e.getMessage());
+            logger.error(REGISTRY_NACOS_EXCEPTION, "", "", e.getMessage());
         }
     }
 
@@ -319,7 +320,7 @@ public class NacosMetadataReport extends AbstractMetadataReport {
                 }
             }
         } catch (NacosException e) {
-            logger.error(e.getMessage());
+            logger.error(REGISTRY_NACOS_EXCEPTION, "", "", e.getMessage());
         }
     }
 
@@ -341,7 +342,7 @@ public class NacosMetadataReport extends AbstractMetadataReport {
                 throw new RuntimeException("publish nacos metadata failed");
             }
         } catch (Throwable t) {
-            logger.error("Failed to put " + identifier + " to nacos " + value + ", cause: " + t.getMessage(), t);
+            logger.error(REGISTRY_NACOS_EXCEPTION, "", "", "Failed to put " + identifier + " to nacos " + value + ", cause: " + t.getMessage(), t);
             throw new RuntimeException("Failed to put " + identifier + " to nacos " + value + ", cause: " + t.getMessage(), t);
         }
     }
@@ -353,7 +354,7 @@ public class NacosMetadataReport extends AbstractMetadataReport {
                 throw new RuntimeException("remove nacos metadata failed");
             }
         } catch (Throwable t) {
-            logger.error("Failed to remove " + identifier + " from nacos , cause: " + t.getMessage(), t);
+            logger.error(REGISTRY_NACOS_EXCEPTION, "", "", "Failed to remove " + identifier + " from nacos , cause: " + t.getMessage(), t);
             throw new RuntimeException("Failed to remove " + identifier + " from nacos , cause: " + t.getMessage(), t);
         }
     }
@@ -362,7 +363,7 @@ public class NacosMetadataReport extends AbstractMetadataReport {
         try {
             return configService.getConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group, 3000L);
         } catch (Throwable t) {
-            logger.error("Failed to get " + identifier + " from nacos , cause: " + t.getMessage(), t);
+            logger.error(REGISTRY_NACOS_EXCEPTION, "", "", "Failed to get " + identifier + " from nacos , cause: " + t.getMessage(), t);
             throw new RuntimeException("Failed to get " + identifier + " from nacos , cause: " + t.getMessage(), t);
         }
     }
diff --git a/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java b/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java
index c6334429d9..b3e1e17a85 100644
--- a/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java
+++ b/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java
@@ -18,7 +18,7 @@ package org.apache.dubbo.metadata.store.zookeeper;
 
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.config.configcenter.ConfigItem;
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.common.utils.JsonUtils;
 import org.apache.dubbo.common.utils.StringUtils;
@@ -47,6 +47,7 @@ import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 
 import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR;
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION;
 import static org.apache.dubbo.metadata.ServiceNameMapping.DEFAULT_MAPPING_GROUP;
 import static org.apache.dubbo.metadata.ServiceNameMapping.getAppNames;
 
@@ -55,7 +56,7 @@ import static org.apache.dubbo.metadata.ServiceNameMapping.getAppNames;
  */
 public class ZookeeperMetadataReport extends AbstractMetadataReport {
 
-    private final static Logger logger = LoggerFactory.getLogger(ZookeeperMetadataReport.class);
+    private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ZookeeperMetadataReport.class);
 
     private final String root;
 
@@ -200,7 +201,7 @@ public class ZookeeperMetadataReport extends AbstractMetadataReport {
             zkClient.createOrUpdate(pathKey, content, false, ticket == null ? 0 : ((Stat) ticket).getVersion());
             return true;
         } catch (Exception e) {
-            logger.warn("zookeeper publishConfigCas failed.", e);
+            logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "zookeeper publishConfigCas failed.", e);
             return false;
         }
     }
diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/AbstractMetricsReporter.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/AbstractMetricsReporter.java
index 4e32c7e053..2b384c33b0 100644
--- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/AbstractMetricsReporter.java
+++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/AbstractMetricsReporter.java
@@ -28,7 +28,7 @@ import io.micrometer.core.instrument.binder.system.ProcessorMetrics;
 import io.micrometer.core.instrument.composite.CompositeMeterRegistry;
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.lang.ShutdownHookCallbacks;
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.common.metrics.MetricsReporter;
 import org.apache.dubbo.common.metrics.collector.DefaultMetricsCollector;
@@ -46,6 +46,7 @@ import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION;
 import static org.apache.dubbo.common.constants.MetricsConstants.ENABLE_JVM_METRICS_KEY;
 
 /**
@@ -53,7 +54,7 @@ import static org.apache.dubbo.common.constants.MetricsConstants.ENABLE_JVM_METR
  */
 public abstract class AbstractMetricsReporter implements MetricsReporter {
 
-    private final Logger logger = LoggerFactory.getLogger(AbstractMetricsReporter.class);
+    private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractMetricsReporter.class);
 
     private final AtomicBoolean initialized = new AtomicBoolean(false);
 
@@ -144,7 +145,7 @@ public abstract class AbstractMetricsReporter implements MetricsReporter {
                                 break;
                         }
                     } catch (Exception e) {
-                        logger.error("error occurred when synchronize metrics collector.", e);
+                        logger.error(COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", "error occurred when synchronize metrics collector.", e);
                     }
                 }
             });
diff --git a/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporter.java b/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporter.java
index 89684e7d30..f27b38a4af 100644
--- a/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporter.java
+++ b/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporter.java
@@ -23,7 +23,7 @@ import io.micrometer.prometheus.PrometheusMeterRegistry;
 import io.prometheus.client.exporter.BasicAuthHttpConnectionFactory;
 import io.prometheus.client.exporter.PushGateway;
 import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.common.utils.NamedThreadFactory;
 import org.apache.dubbo.common.utils.StringUtils;
@@ -37,6 +37,7 @@ import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION;
 import static org.apache.dubbo.common.constants.MetricsConstants.PROMETHEUS_EXPORTER_ENABLED_KEY;
 import static org.apache.dubbo.common.constants.MetricsConstants.PROMETHEUS_EXPORTER_METRICS_PORT_KEY;
 import static org.apache.dubbo.common.constants.MetricsConstants.PROMETHEUS_DEFAULT_METRICS_PORT;
@@ -56,7 +57,7 @@ import static org.apache.dubbo.common.constants.MetricsConstants.PROMETHEUS_PUSH
  */
 public class PrometheusMetricsReporter extends AbstractMetricsReporter {
 
-    private final Logger logger = LoggerFactory.getLogger(PrometheusMetricsReporter.class);
+    private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PrometheusMetricsReporter.class);
 
     private final PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
     private ScheduledExecutorService pushJobExecutor = null;
@@ -125,7 +126,7 @@ public class PrometheusMetricsReporter extends AbstractMetricsReporter {
         try {
             pushGateway.pushAdd(prometheusRegistry.getPrometheusRegistry(), job);
         } catch (IOException e) {
-            logger.error("Error occurred when pushing metrics to prometheus: ", e);
+            logger.error(COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", "Error occurred when pushing metrics to prometheus: ", e);
         }
     }
 
diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/AbstractMonitorFactory.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/AbstractMonitorFactory.java
index fe9c6a2aa3..c26c09cceb 100644
--- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/AbstractMonitorFactory.java
+++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/AbstractMonitorFactory.java
@@ -17,7 +17,7 @@
 package org.apache.dubbo.monitor.support;
 
 import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.common.utils.NamedThreadFactory;
 import org.apache.dubbo.monitor.Monitor;
@@ -36,12 +36,13 @@ import java.util.concurrent.TimeUnit;
 import java.util.concurrent.locks.ReentrantLock;
 
 import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_MONITOR_EXCEPTION;
 
 /**
  * AbstractMonitorFactory. (SPI, Singleton, ThreadSafe)
  */
 public abstract class AbstractMonitorFactory implements MonitorFactory {
-    private static final Logger logger = LoggerFactory.getLogger(AbstractMonitorFactory.class);
+    private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractMonitorFactory.class);
 
     /**
      * The lock for getting monitor center
@@ -90,7 +91,7 @@ public abstract class AbstractMonitorFactory implements MonitorFactory {
                     FUTURES.remove(key);
                     return m;
                 } catch (Throwable e) {
-                    logger.warn("Create monitor failed, monitor data will not be collected until you fix this problem. monitorUrl: " + monitorUrl, e);
+                    logger.warn(COMMON_MONITOR_EXCEPTION, "", "", "Create monitor failed, monitor data will not be collected until you fix this problem. monitorUrl: " + monitorUrl, e);
                     return null;
                 }
             });
diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java
index c80bed4b2a..61b80f3c9e 100644
--- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java
+++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java
@@ -18,7 +18,7 @@ package org.apache.dubbo.monitor.support;
 
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.extension.Activate;
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.common.url.component.ServiceConfigURL;
 import org.apache.dubbo.common.utils.NetUtils;
@@ -46,6 +46,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY;
 import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR;
 import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;
 import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_MONITOR_EXCEPTION;
 import static org.apache.dubbo.monitor.Constants.CONCURRENT_KEY;
 import static org.apache.dubbo.monitor.Constants.COUNT_PROTOCOL;
 import static org.apache.dubbo.monitor.Constants.ELAPSED_KEY;
@@ -60,7 +61,7 @@ import static org.apache.dubbo.rpc.Constants.OUTPUT_KEY;
 @Activate(group = {PROVIDER})
 public class MonitorFilter implements Filter, Filter.Listener {
 
-    private static final Logger logger = LoggerFactory.getLogger(MonitorFilter.class);
+    private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MonitorFilter.class);
     private static final String MONITOR_FILTER_START_TIME = "monitor_filter_start_time";
     private static final String MONITOR_REMOTE_HOST_STORE = "monitor_remote_host_store";
 
@@ -158,7 +159,7 @@ public class MonitorFilter implements Filter, Filter.Listener {
                 monitor.collect(statisticsUrl.toSerializableURL());
             }
         } catch (Throwable t) {
-            logger.warn("Failed to monitor count service " + invoker.getUrl() + ", cause: " + t.getMessage(), t);
+            logger.warn(COMMON_MONITOR_EXCEPTION, "", "", "Failed to monitor count service " + invoker.getUrl() + ", cause: " + t.getMessage(), t);
         }
     }
 
diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitor.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitor.java
index fb09d4ef92..e0a7d9c8b2 100644
--- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitor.java
+++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitor.java
@@ -17,7 +17,7 @@
 package org.apache.dubbo.monitor.dubbo;
 
 import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
 import org.apache.dubbo.common.utils.ExecutorUtil;
@@ -36,6 +36,7 @@ import java.util.concurrent.atomic.AtomicReference;
 
 import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL;
 import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_MONITOR_EXCEPTION;
 import static org.apache.dubbo.monitor.Constants.CONCURRENT_KEY;
 import static org.apache.dubbo.monitor.Constants.DEFAULT_MONITOR_SEND_DATA_INTERVAL;
 import static org.apache.dubbo.monitor.Constants.ELAPSED_KEY;
@@ -54,7 +55,7 @@ import static org.apache.dubbo.monitor.Constants.SUCCESS_KEY;
  */
 public class DubboMonitor implements Monitor {
 
-    private static final Logger logger = LoggerFactory.getLogger(DubboMonitor.class);
+    private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboMonitor.class);
 
     /**
      * The timer for sending statistics
@@ -85,7 +86,7 @@ public class DubboMonitor implements Monitor {
                 // collect data
                 send();
             } catch (Throwable t) {
-                logger.error("Unexpected error occur at send statistic, cause: " + t.getMessage(), t);
+                logger.error(COMMON_MONITOR_EXCEPTION, "", "", "Unexpected error occur at send statistic, cause: " + t.getMessage(), t);
             }
         }, monitorInterval, monitorInterval, TimeUnit.MILLISECONDS);
     }
@@ -196,7 +197,7 @@ public class DubboMonitor implements Monitor {
         try {
             ExecutorUtil.cancelScheduledFuture(sendFuture);
         } catch (Throwable t) {
-            logger.error("Unexpected error occur at cancel sender timer, cause: " + t.getMessage(), t);
+            logger.error(COMMON_MONITOR_EXCEPTION, "", "", "Unexpected error occur at cancel sender timer, cause: " + t.getMessage(), t);
         }
         monitorInvoker.destroy();
     }
diff --git a/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/ClassFinder.java b/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/ClassFinder.java
index c5c350e379..f05a20c2c8 100644
--- a/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/ClassFinder.java
+++ b/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/ClassFinder.java
@@ -56,15 +56,18 @@ public class ClassFinder {
     private void findClassesByFile(String packageName, String resource, Set result) {
         File directory = new File(resource);
         File[] listFiles = directory.listFiles();
-        for (File file : listFiles) {
-            if (file.isDirectory()) {
-                findClassesByFile(packageName, file.getPath(), result);
-            } else {
-                String path = file.getPath();
-                if (path.endsWith(".class")) {
-                    int packageIndex = path.indexOf(packageName.replace("/", File.separator));
-                    String classPath = path.substring(packageIndex, path.length() - 6);
-                    result.add(classPath.replace(File.separator, "."));
+        // null check
+        if (listFiles != null) {
+            for (File file : listFiles) {
+                if (file.isDirectory()) {
+                    findClassesByFile(packageName, file.getPath(), result);
+                } else {
+                    String path = file.getPath();
+                    if (path.endsWith(".class")) {
+                        int packageIndex = path.indexOf(packageName.replace("/", File.separator));
+                        String classPath = path.substring(packageIndex, path.length() - 6);
+                        result.add(classPath.replace(File.separator, "."));
+                    }
                 }
             }
         }
diff --git a/dubbo-native/src/main/java/org/apache/dubbo/utils/ClassFinder.java b/dubbo-native/src/main/java/org/apache/dubbo/utils/ClassFinder.java
index c78d108be8..75ef3277e8 100644
--- a/dubbo-native/src/main/java/org/apache/dubbo/utils/ClassFinder.java
+++ b/dubbo-native/src/main/java/org/apache/dubbo/utils/ClassFinder.java
@@ -56,15 +56,17 @@ public class ClassFinder {
     private void findClassesByFile(String packageName, String resource, Set result) {
         File directory = new File(resource);
         File[] listFiles = directory.listFiles();
-        for (File file : listFiles) {
-            if (file.isDirectory()) {
-                findClassesByFile(packageName, file.getPath(), result);
-            } else {
-                String path = file.getPath();
-                if (path.endsWith(".class")) {
-                    int packageIndex = path.indexOf(packageName.replace("/", File.separator));
-                    String classPath = path.substring(packageIndex, path.length() - 6);
-                    result.add(classPath.replace(File.separator, "."));
+        if (listFiles != null) {
+            for (File file : listFiles) {
+                if (file.isDirectory()) {
+                    findClassesByFile(packageName, file.getPath(), result);
+                } else {
+                    String path = file.getPath();
+                    if (path.endsWith(".class")) {
+                        int packageIndex = path.indexOf(packageName.replace("/", File.separator));
+                        String classPath = path.substring(packageIndex, path.length() - 6);
+                        result.add(classPath.replace(File.separator, "."));
+                    }
                 }
             }
         }
diff --git a/dubbo-plugin/dubbo-qos/pom.xml b/dubbo-plugin/dubbo-qos/pom.xml
index cdc6797bce..4586a6199a 100644
--- a/dubbo-plugin/dubbo-qos/pom.xml
+++ b/dubbo-plugin/dubbo-qos/pom.xml
@@ -70,9 +70,5 @@
             dubbo-serialization-fastjson2
             ${project.parent.version}
         
-        
-            io.netty
-            netty-all
-        
     
 
diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableDetailProfiler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableDetailProfiler.java
index 5ac413b356..82b01350ea 100644
--- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableDetailProfiler.java
+++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableDetailProfiler.java
@@ -16,21 +16,23 @@
  */
 package org.apache.dubbo.qos.command.impl;
 
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.common.profiler.ProfilerSwitch;
 import org.apache.dubbo.qos.command.BaseCommand;
 import org.apache.dubbo.qos.command.CommandContext;
 import org.apache.dubbo.qos.command.annotation.Cmd;
 
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_DISABLED;
+
 @Cmd(name = "disableDetailProfiler", summary = "Disable Dubbo Invocation Profiler.")
 public class DisableDetailProfiler implements BaseCommand {
-    private final static Logger logger = LoggerFactory.getLogger(DisableDetailProfiler.class);
+    private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DisableDetailProfiler.class);
 
     @Override
     public String execute(CommandContext commandContext, String[] args) {
         ProfilerSwitch.disableDetailProfiler();
-        logger.warn("Dubbo Invocation Profiler has been disabled.");
+        logger.warn(QOS_PROFILER_DISABLED, "", "", "Dubbo Invocation Profiler has been disabled.");
         return "OK";
     }
 }
diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableSimpleProfiler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableSimpleProfiler.java
index 22ffba5358..5bde9b3666 100644
--- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableSimpleProfiler.java
+++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableSimpleProfiler.java
@@ -16,21 +16,23 @@
  */
 package org.apache.dubbo.qos.command.impl;
 
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.common.profiler.ProfilerSwitch;
 import org.apache.dubbo.qos.command.BaseCommand;
 import org.apache.dubbo.qos.command.CommandContext;
 import org.apache.dubbo.qos.command.annotation.Cmd;
 
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_DISABLED;
+
 @Cmd(name = "disableSimpleProfiler", summary = "Disable Dubbo Invocation Profiler.")
 public class DisableSimpleProfiler implements BaseCommand {
-    private final static Logger logger = LoggerFactory.getLogger(DisableSimpleProfiler.class);
+    private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DisableSimpleProfiler.class);
 
     @Override
     public String execute(CommandContext commandContext, String[] args) {
         ProfilerSwitch.disableSimpleProfiler();
-        logger.warn("Dubbo Invocation Profiler has been disabled.");
+        logger.warn(QOS_PROFILER_DISABLED, "", "", "Dubbo Invocation Profiler has been disabled.");
         return "OK";
     }
 }
diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableDetailProfiler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableDetailProfiler.java
index 0800163170..a2589f0335 100644
--- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableDetailProfiler.java
+++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableDetailProfiler.java
@@ -16,21 +16,23 @@
  */
 package org.apache.dubbo.qos.command.impl;
 
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.common.profiler.ProfilerSwitch;
 import org.apache.dubbo.qos.command.BaseCommand;
 import org.apache.dubbo.qos.command.CommandContext;
 import org.apache.dubbo.qos.command.annotation.Cmd;
 
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_ENABLED;
+
 @Cmd(name = "enableDetailProfiler", summary = "Enable Dubbo Invocation Profiler.")
 public class EnableDetailProfiler implements BaseCommand {
-    private final static Logger logger = LoggerFactory.getLogger(EnableDetailProfiler.class);
+    private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(EnableDetailProfiler.class);
 
     @Override
     public String execute(CommandContext commandContext, String[] args) {
         ProfilerSwitch.enableDetailProfiler();
-        logger.warn("Dubbo Invocation Profiler has been enabled.");
+        logger.warn(QOS_PROFILER_ENABLED, "", "", "Dubbo Invocation Profiler has been enabled.");
         return "OK. This will cause performance degradation, please be careful!";
     }
 }
diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableSimpleProfiler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableSimpleProfiler.java
index d46df99ecb..14a40a74d1 100644
--- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableSimpleProfiler.java
+++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableSimpleProfiler.java
@@ -16,21 +16,23 @@
  */
 package org.apache.dubbo.qos.command.impl;
 
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.common.profiler.ProfilerSwitch;
 import org.apache.dubbo.qos.command.BaseCommand;
 import org.apache.dubbo.qos.command.CommandContext;
 import org.apache.dubbo.qos.command.annotation.Cmd;
 
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_ENABLED;
+
 @Cmd(name = "enableSimpleProfiler", summary = "Enable Dubbo Invocation Profiler.")
 public class EnableSimpleProfiler implements BaseCommand {
-    private final static Logger logger = LoggerFactory.getLogger(EnableSimpleProfiler.class);
+    private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(EnableSimpleProfiler.class);
 
     @Override
     public String execute(CommandContext commandContext, String[] args) {
         ProfilerSwitch.enableSimpleProfiler();
-        logger.warn("Dubbo Invocation Profiler has been enabled.");
+        logger.warn(QOS_PROFILER_ENABLED, "", "", "Dubbo Invocation Profiler has been enabled.");
         return "OK";
     }
 }
diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PublishMetadata.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PublishMetadata.java
index 7d43688ba8..64f33f7398 100644
--- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PublishMetadata.java
+++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PublishMetadata.java
@@ -16,7 +16,7 @@
  */
 package org.apache.dubbo.qos.command.impl;
 
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
 import org.apache.dubbo.common.utils.ArrayUtils;
@@ -30,12 +30,14 @@ import org.apache.dubbo.rpc.model.FrameworkModel;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
 
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_PARAMETER_FORMAT_ERROR;
+
 @Cmd(name = "publishMetadata", summary = "update service metadata and service instance", example = {
-        "publishMetadata",
-        "publishMetadata 5"
+    "publishMetadata",
+    "publishMetadata 5"
 })
-public class  PublishMetadata implements BaseCommand {
-    private static final Logger logger = LoggerFactory.getLogger(PublishMetadata.class);
+public class PublishMetadata implements BaseCommand {
+    private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PublishMetadata.class);
     private final FrameworkModel frameworkModel;
 
     public PublishMetadata(FrameworkModel frameworkModel) {
@@ -60,7 +62,7 @@ public class  PublishMetadata implements BaseCommand {
                     frameworkExecutorRepository.nextScheduledExecutor()
                         .schedule(() -> ServiceInstanceMetadataUtils.refreshMetadataAndInstance(applicationModel), delay, TimeUnit.SECONDS);
                 } catch (NumberFormatException e) {
-                    logger.error("Wrong delay param", e);
+                    logger.error(CONFIG_PARAMETER_FORMAT_ERROR, "", "", "Wrong delay param", e);
                     return "publishMetadata failed! Wrong delay param!";
                 }
                 stringBuilder.append("publish task submitted, will publish in ").append(args[0]).append(" seconds. App:").append(applicationModel.getApplicationName()).append("\n");
diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SetProfilerWarnPercent.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SetProfilerWarnPercent.java
index e6014f6cb2..789c5331e1 100644
--- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SetProfilerWarnPercent.java
+++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SetProfilerWarnPercent.java
@@ -16,16 +16,18 @@
  */
 package org.apache.dubbo.qos.command.impl;
 
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.common.profiler.ProfilerSwitch;
 import org.apache.dubbo.qos.command.BaseCommand;
 import org.apache.dubbo.qos.command.CommandContext;
 import org.apache.dubbo.qos.command.annotation.Cmd;
 
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_WARN_PERCENT;
+
 @Cmd(name = "setProfilerWarnPercent", example = "setProfilerWarnPercent 0.75", summary = "Disable Dubbo Invocation Profiler.")
 public class SetProfilerWarnPercent implements BaseCommand {
-    private final static Logger logger = LoggerFactory.getLogger(SetProfilerWarnPercent.class);
+    private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SetProfilerWarnPercent.class);
 
     @Override
     public String execute(CommandContext commandContext, String[] args) {
@@ -33,7 +35,7 @@ public class SetProfilerWarnPercent implements BaseCommand {
             return "args error. example: setProfilerWarnPercent 0.75";
         }
         ProfilerSwitch.setWarnPercent(Double.parseDouble(args[0]));
-        logger.warn("Dubbo Invocation Profiler warn percent has been set to " + args[0]);
+        logger.warn(QOS_PROFILER_WARN_PERCENT, "", "", "Dubbo Invocation Profiler warn percent has been set to " + args[0]);
         return "OK";
     }
 }
diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java
index 7fc369395c..18139f0fad 100644
--- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java
+++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java
@@ -18,7 +18,7 @@ package org.apache.dubbo.qos.protocol;
 
 import org.apache.dubbo.common.URL;
 import org.apache.dubbo.common.extension.Activate;
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.qos.common.QosConstants;
 import org.apache.dubbo.qos.pu.QosWireProtocol;
@@ -35,6 +35,7 @@ import org.apache.dubbo.rpc.model.ScopeModelAware;
 import java.util.List;
 import java.util.concurrent.atomic.AtomicBoolean;
 
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_FAILED_START_SERVER;
 import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP;
 import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE;
 import static org.apache.dubbo.common.constants.QosConstants.QOS_HOST;
@@ -43,7 +44,7 @@ import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT;
 @Activate(order = 200)
 public class QosProtocolWrapper implements Protocol, ScopeModelAware {
 
-    private final Logger logger = LoggerFactory.getLogger(QosProtocolWrapper.class);
+    private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(QosProtocolWrapper.class);
 
     private AtomicBoolean hasStarted = new AtomicBoolean(false);
 
@@ -99,7 +100,7 @@ public class QosProtocolWrapper implements Protocol, ScopeModelAware {
 
             boolean qosEnable = url.getParameter(QOS_ENABLE, true);
             WireProtocol qosWireProtocol = frameworkModel.getExtensionLoader(WireProtocol.class).getExtension("qos");
-            if(qosWireProtocol != null) {
+            if (qosWireProtocol != null) {
                 ((QosWireProtocol) qosWireProtocol).setQosEnable(qosEnable);
             }
             if (!qosEnable) {
@@ -124,7 +125,7 @@ public class QosProtocolWrapper implements Protocol, ScopeModelAware {
             server.start();
 
         } catch (Throwable throwable) {
-            logger.warn("Fail to start qos server: ", throwable);
+            logger.warn(QOS_FAILED_START_SERVER, "", "", "Fail to start qos server: ", throwable);
         }
     }
 
diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/Server.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/Server.java
index 2689ecd056..fa40444e61 100644
--- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/Server.java
+++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/Server.java
@@ -16,7 +16,7 @@
  */
 package org.apache.dubbo.qos.server;
 
-import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.common.utils.StringUtils;
 import org.apache.dubbo.qos.server.handler.QosProcessHandler;
@@ -33,6 +33,8 @@ import io.netty.util.concurrent.DefaultThreadFactory;
 
 import java.util.concurrent.atomic.AtomicBoolean;
 
+import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_FAILED_START_SERVER;
+
 /**
  * A server serves for both telnet access and http access
  * 
    @@ -43,7 +45,7 @@ import java.util.concurrent.atomic.AtomicBoolean; */ public class Server { - private static final Logger logger = LoggerFactory.getLogger(Server.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(Server.class); private String host; @@ -107,7 +109,7 @@ public class Server { logger.info("qos-server bind localhost:" + port); } catch (Throwable throwable) { - logger.error("qos-server can not bind localhost:" + port, throwable); + logger.error(QOS_FAILED_START_SERVER, "", "", "qos-server can not bind localhost:" + port, throwable); throw throwable; } } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/HttpProcessHandler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/HttpProcessHandler.java index 167f5ad737..6af1b5e9f3 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/HttpProcessHandler.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/HttpProcessHandler.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.qos.server.handler; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.qos.command.CommandContext; import org.apache.dubbo.qos.command.CommandExecutor; @@ -37,6 +37,9 @@ import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_COMMAND_NOT_FOUND; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_UNEXPECTED_EXCEPTION; + /** * Parse HttpRequest for uri and parameters *

    @@ -50,7 +53,7 @@ import io.netty.handler.codec.http.HttpVersion; */ public class HttpProcessHandler extends SimpleChannelInboundHandler { - private static final Logger log = LoggerFactory.getLogger(HttpProcessHandler.class); + private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(HttpProcessHandler.class); private CommandExecutor commandExecutor; public HttpProcessHandler(FrameworkModel frameworkModel) { @@ -59,7 +62,7 @@ public class HttpProcessHandler extends SimpleChannelInboundHandler private static FullHttpResponse http(int httpCode, String result) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(httpCode) - , Unpooled.wrappedBuffer(result.getBytes())); + , Unpooled.wrappedBuffer(result.getBytes())); HttpHeaders httpHeaders = response.headers(); httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, "text/plain"); httpHeaders.set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); @@ -79,7 +82,7 @@ public class HttpProcessHandler extends SimpleChannelInboundHandler CommandContext commandContext = HttpCommandDecoder.decode(msg); // return 404 when fail to construct command context if (commandContext == null) { - log.warn("can not found commandContext, url: " + msg.uri()); + log.warn(QOS_UNEXPECTED_EXCEPTION, "", "", "can not found commandContext, url: " + msg.uri()); FullHttpResponse response = http404(); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else { @@ -90,11 +93,11 @@ public class HttpProcessHandler extends SimpleChannelInboundHandler FullHttpResponse response = http(httpCode, result); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } catch (NoSuchCommandException ex) { - log.error("can not find command: " + commandContext, ex); + log.error(QOS_COMMAND_NOT_FOUND, "", "", "can not find command: " + commandContext, ex); FullHttpResponse response = http404(); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } catch (Exception qosEx) { - log.error("execute commandContext: " + commandContext + " got exception", qosEx); + log.error(QOS_UNEXPECTED_EXCEPTION, "", "", "execute commandContext: " + commandContext + " got exception", qosEx); FullHttpResponse response = http(500, qosEx.getMessage()); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandler.java index 4631401a45..54ed428614 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandler.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandler.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.qos.server.handler; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.command.CommandContext; @@ -31,12 +31,15 @@ import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_COMMAND_NOT_FOUND; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_UNEXPECTED_EXCEPTION; + /** * Telnet process handler */ public class TelnetProcessHandler extends SimpleChannelInboundHandler { - private static final Logger log = LoggerFactory.getLogger(TelnetProcessHandler.class); + private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(TelnetProcessHandler.class); private final CommandExecutor commandExecutor; public TelnetProcessHandler(FrameworkModel frameworkModel) { @@ -62,11 +65,11 @@ public class TelnetProcessHandler extends SimpleChannelInboundHandler { } catch (NoSuchCommandException ex) { ctx.writeAndFlush(msg + " :no such command"); ctx.writeAndFlush(QosConstants.BR_STR + QosProcessHandler.PROMPT); - log.error("can not found command " + commandContext, ex); + log.error(QOS_COMMAND_NOT_FOUND, "", "", "can not found command " + commandContext, ex); } catch (Exception ex) { ctx.writeAndFlush(msg + " :fail to execute commandContext by " + ex.getMessage()); ctx.writeAndFlush(QosConstants.BR_STR + QosProcessHandler.PROMPT); - log.error("execute commandContext got exception " + commandContext, ex); + log.error(QOS_UNEXPECTED_EXCEPTION, "", "", "execute commandContext got exception " + commandContext, ex); } } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/ListenerRegistryWrapper.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/ListenerRegistryWrapper.java index c9cdc67773..540e93f394 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/ListenerRegistryWrapper.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/ListenerRegistryWrapper.java @@ -26,6 +26,8 @@ import org.apache.dubbo.common.utils.UrlUtils; import java.util.List; import java.util.function.Consumer; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNEXPECTED_EXCEPTION; + public class ListenerRegistryWrapper implements Registry { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ListenerRegistryWrapper.class); @@ -123,7 +125,7 @@ public class ListenerRegistryWrapper implements Registry { try { consumer.accept(listener); } catch (RuntimeException t) { - logger.error(t.getMessage(), t); + logger.error(REGISTRY_UNEXPECTED_EXCEPTION, "", "", t.getMessage(), t); exception = t; } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryNotifier.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryNotifier.java index 452f919a03..168368690a 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryNotifier.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryNotifier.java @@ -27,6 +27,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_DELAY_EXECUTE_TIMES; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_NOTIFY_EVENT; public abstract class RegistryNotifier { @@ -111,7 +112,7 @@ public abstract class RegistryNotifier { } } } catch (Throwable t) { - logger.error("Error occurred when notify directory. ", t); + logger.error(REGISTRY_FAILED_NOTIFY_EVENT, "", "", "Error occurred when notify directory. ", t); } } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java index 0ccaa13043..fb6e8cb6d8 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java @@ -40,6 +40,8 @@ import java.util.Set; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE; import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_LOCAL_FILE_CACHE_ENABLED; import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_FETCH_INSTANCE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_LOAD_METADATA; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_KEY; import static org.apache.dubbo.metadata.RevisionResolver.EMPTY_REVISION; import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_PROPERTY_NAME; @@ -96,7 +98,7 @@ public abstract class AbstractServiceDiscovery implements ServiceDiscovery { } this.serviceInstance = createServiceInstance(this.metadataInfo); if (!isValidInstance(this.serviceInstance)) { - logger.warn("No valid instance found, stop registering instance address to registry."); + logger.warn(REGISTRY_FAILED_FETCH_INSTANCE, "", "", "No valid instance found, stop registering instance address to registry."); return; } @@ -195,7 +197,7 @@ public abstract class AbstractServiceDiscovery implements ServiceDiscovery { } if (metadata == MetadataInfo.EMPTY) { - logger.error("Failed to get metadata for revision after 3 retries, revision=" + revision); + logger.error(REGISTRY_FAILED_LOAD_METADATA, "", "", "Failed to get metadata for revision after 3 retries, revision=" + revision); } else { metaCacheManager.put(revision, metadata); } @@ -205,7 +207,7 @@ public abstract class AbstractServiceDiscovery implements ServiceDiscovery { @Override public MetadataInfo getRemoteMetadata(String revision) { - return metaCacheManager.get(revision); + return metaCacheManager.get(revision); } @Override @@ -242,7 +244,7 @@ public abstract class AbstractServiceDiscovery implements ServiceDiscovery { @Override public List lookup(URL url) { - throw new UnsupportedOperationException("Service discovery implementation does not support lookup of url list."); + throw new UnsupportedOperationException("Service discovery implementation does not support lookup of url list."); } protected void doUpdate(ServiceInstance serviceInstance) throws RuntimeException { @@ -310,7 +312,7 @@ public abstract class AbstractServiceDiscovery implements ServiceDiscovery { } StringBuilder stringBuilder = new StringBuilder(128); Optional application = applicationModel.getApplicationConfigManager().getApplication(); - if(application.isPresent()) { + if (application.isPresent()) { stringBuilder.append(application.get().getName()); stringBuilder.append("."); } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistry.java index 098f6453a5..81c138d6fa 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistry.java @@ -41,6 +41,7 @@ import java.util.concurrent.locks.ReentrantLock; import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNEXPECTED_EXCEPTION; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_TYPE; @@ -202,7 +203,7 @@ public class ServiceDiscoveryRegistry extends FailbackRegistry { subscribedServices = serviceNameMapping.getAndListen(this.getUrl(), url, mappingListener); mappingListeners.put(url.getProtocolServiceKey(), mappingListener); } catch (Exception e) { - logger.warn("Cannot find app mapping for service " + url.getServiceInterface() + ", will not migrate.", e); + logger.warn(REGISTRY_UNEXPECTED_EXCEPTION, "", "", "Cannot find app mapping for service " + url.getServiceInterface() + ", will not migrate.", e); } if (CollectionUtils.isEmpty(subscribedServices)) { @@ -365,7 +366,7 @@ public class ServiceDiscoveryRegistry extends FailbackRegistry { logger.info("Received mapping notification from meta server, " + event); if (stopped) { - logger.warn("Listener has been stopped, ignore mapping notification, check why listener is not removed."); + logger.warn(REGISTRY_UNEXPECTED_EXCEPTION, "", "", "Listener has been stopped, ignore mapping notification, check why listener is not removed."); return; } Set newApps = event.getApps(); diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryDirectory.java index a3e68cdbb6..fe98e100f4 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryDirectory.java @@ -61,6 +61,8 @@ import java.util.stream.Collectors; import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DESTROY_INVOKER; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REFER_INVOKER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNSUPPORTED; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_HASHMAP_LOAD_FACTOR; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; @@ -229,14 +231,14 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { this.originalUrls = invokerUrls; if (invokerUrls.size() == 1 && EMPTY_PROTOCOL.equals(invokerUrls.get(0).getProtocol())) { - logger.warn("Received url with EMPTY protocol, will clear all available addresses."); + logger.warn(PROTOCOL_UNSUPPORTED, "", "", "Received url with EMPTY protocol, will clear all available addresses."); this.forbidden = true; // Forbid to access routerChain.setInvokers(BitList.emptyList()); destroyAllInvokers(); // Close all invokers } else { this.forbidden = false; // Allow accessing if (CollectionUtils.isEmpty(invokerUrls)) { - logger.warn("Received empty url list, will ignore for protection purpose."); + logger.warn(PROTOCOL_UNSUPPORTED, "", "", "Received empty url list, will ignore for protection purpose."); return; } @@ -253,7 +255,7 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { logger.info("Refreshed invoker size " + newUrlInvokerMap.size()); if (CollectionUtils.isEmptyMap(newUrlInvokerMap)) { - logger.error(new IllegalStateException("Cannot create invokers from url address list (total " + invokerUrls.size() + ")")); + logger.error(PROTOCOL_UNSUPPORTED, "", "", "Unsupported protocol.", new IllegalStateException("Cannot create invokers from url address list (total " + invokerUrls.size() + ")")); return; } List> newInvokers = Collections.unmodifiableList(new ArrayList<>(newUrlInvokerMap.values())); @@ -266,7 +268,7 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { try { destroyUnusedInvokers(oldUrlInvokerMap, newUrlInvokerMap); // Close the unused Invoker } catch (Exception e) { - logger.warn("destroyUnusedInvokers error. ", e); + logger.warn(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", "destroyUnusedInvokers error. ", e); } } } @@ -300,9 +302,9 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { logger.error(PROTOCOL_UNSUPPORTED, "protocol extension does not installed", "", "Unsupported protocol.", new IllegalStateException("Unsupported protocol " + instanceAddressURL.getProtocol() + - " in notified url: " + instanceAddressURL + " from registry " + getUrl().getAddress() + - " to consumer " + NetUtils.getLocalHost() + ", supported protocol: " + - getUrl().getOrDefaultFrameworkModel().getExtensionLoader(Protocol.class).getSupportedExtensions())); + " in notified url: " + instanceAddressURL + " from registry " + getUrl().getAddress() + + " to consumer " + NetUtils.getLocalHost() + ", supported protocol: " + + getUrl().getOrDefaultFrameworkModel().getExtensionLoader(Protocol.class).getSupportedExtensions())); continue; } @@ -351,7 +353,7 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { } } } catch (Throwable t) { - logger.error("Failed to refer invoker for interface:" + serviceType + ",url:(" + instanceAddressURL + ")" + t.getMessage(), t); + logger.error(PROTOCOL_FAILED_REFER_INVOKER, "", "", "Failed to refer invoker for interface:" + serviceType + ",url:(" + instanceAddressURL + ")" + t.getMessage(), t); } if (invoker != null) { // Put new invoker in cache newUrlInvokerMap.put(protocolServiceKeyWithAddress, invoker); @@ -425,7 +427,7 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { try { invoker.destroyAll(); } catch (Throwable t) { - logger.warn("Failed to destroy service " + serviceKey + " to provider " + invoker.getUrl(), t); + logger.warn(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", "Failed to destroy service " + serviceKey + " to provider " + invoker.getUrl(), t); } } localUrlInvokerMap.clear(); @@ -461,7 +463,7 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { logger.debug("destroy invoker[" + invoker.getUrl() + "] success. "); } } catch (Exception e) { - logger.warn("destroy invoker[" + invoker.getUrl() + "] failed. " + e.getMessage(), e); + logger.warn(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", "destroy invoker[" + invoker.getUrl() + "]failed." + e.getMessage(), e); } } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java index 8cb30728a3..a28387ce6b 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java @@ -56,6 +56,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_REFRESH_ADDRESS; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNEXPECTED_EXCEPTION; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.ENABLE_EMPTY_PROTECTION_KEY; import static org.apache.dubbo.metadata.RevisionResolver.EMPTY_REVISION; @@ -178,9 +179,9 @@ public class ServiceInstancesChangedListener { try { retryFuture = scheduler.schedule(new AddressRefreshRetryTask(retryPermission, event.getServiceName()), 10_000L, TimeUnit.MILLISECONDS); } catch (Exception e) { - logger.error("Error submitting async retry task."); + logger.error(REGISTRY_UNEXPECTED_EXCEPTION, "", "", "Error submitting async retry task."); } - logger.warn("Address refresh try task submitted"); + logger.warn(REGISTRY_UNEXPECTED_EXCEPTION, "", "", "Address refresh try task submitted"); } // return if all metadata is empty, this notification will not take effect. @@ -290,12 +291,12 @@ public class ServiceInstancesChangedListener { protected boolean isRetryAndExpired(ServiceInstancesChangedEvent event) { if (event instanceof RetryServiceInstancesChangedEvent) { RetryServiceInstancesChangedEvent retryEvent = (RetryServiceInstancesChangedEvent) event; - logger.warn("Received address refresh retry event, " + retryEvent.getFailureRecordTime()); + logger.warn(REGISTRY_UNEXPECTED_EXCEPTION, "", "", "Received address refresh retry event, " + retryEvent.getFailureRecordTime()); if (retryEvent.getFailureRecordTime() < lastRefreshTime && !hasEmptyMetadata) { - logger.warn("Ignore retry event, event time: " + retryEvent.getFailureRecordTime() + ", last refresh time: " + lastRefreshTime); + logger.warn(REGISTRY_UNEXPECTED_EXCEPTION, "", "", "Ignore retry event, event time: " + retryEvent.getFailureRecordTime() + ", last refresh time: " + lastRefreshTime); return true; } - logger.warn("Retrying address notification..."); + logger.warn(REGISTRY_UNEXPECTED_EXCEPTION, "", "", "Retrying address notification..."); } return false; } @@ -339,7 +340,7 @@ public class ServiceInstancesChangedListener { if (emptyMetadataNum > 0) { builder.insert(0, emptyMetadataNum + "/" + revisionToInstances.size() + " revisions failed to get metadata from remote: "); - logger.error(builder.toString()); + logger.error(REGISTRY_UNEXPECTED_EXCEPTION, "", "", builder.toString()); } else { builder.insert(0, revisionToInstances.size() + " unique working revisions: "); logger.info(builder.toString()); diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceDelegation.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceDelegation.java index 5cd7556450..6047632919 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceDelegation.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceDelegation.java @@ -44,6 +44,7 @@ import static java.util.Collections.emptySortedSet; import static java.util.Collections.unmodifiableSortedSet; import static org.apache.dubbo.common.URL.buildKey; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_LOAD_METADATA; import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty; /** @@ -137,7 +138,7 @@ public class MetadataServiceDelegation implements MetadataService, Disposable { return unmodifiableSortedSet(getServiceURLs(getAllServiceURLs(), serviceKey, protocol)); } - private Map> getAllServiceURLs () { + private Map> getAllServiceURLs() { List serviceDiscoveries = registryManager.getServiceDiscoveries(); Map> allServiceURLs = new HashMap<>(); for (ServiceDiscovery sd : serviceDiscoveries) { @@ -182,7 +183,7 @@ public class MetadataServiceDelegation implements MetadataService, Disposable { } if (logger.isWarnEnabled()) { - logger.warn("metadata not found for revision: " + revision); + logger.warn(REGISTRY_FAILED_LOAD_METADATA, "", "", "metadata not found for revision: " + revision); } return null; } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMapping.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMapping.java index d8cf5284e2..10f6fe1db3 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMapping.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMapping.java @@ -37,6 +37,8 @@ import java.util.Set; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ADDRESS_INVALID; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNEXPECTED_EXCEPTION; public class MetadataServiceNameMapping extends AbstractServiceNameMapping { @@ -58,7 +60,7 @@ public class MetadataServiceNameMapping extends AbstractServiceNameMapping { @Override public boolean map(URL url) { if (CollectionUtils.isEmpty(applicationModel.getApplicationConfigManager().getMetadataConfigs())) { - logger.warn("No valid metadata config center found for mapping report."); + logger.warn(REGISTRY_ADDRESS_INVALID, "", "", "No valid metadata config center found for mapping report."); return false; } String serviceInterface = url.getServiceInterface(); @@ -99,7 +101,7 @@ public class MetadataServiceNameMapping extends AbstractServiceNameMapping { } } catch (Exception e) { result = false; - logger.warn("Failed registering mapping to remote." + metadataReport, e); + logger.warn(REGISTRY_UNEXPECTED_EXCEPTION, "", "", "Failed registering mapping to remote." + metadataReport, e); } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataUtils.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataUtils.java index c5129b2f88..91bbdfbec6 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataUtils.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataUtils.java @@ -18,7 +18,7 @@ package org.apache.dubbo.registry.client.metadata; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; @@ -48,16 +48,18 @@ import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.PROXY_CLASS_REF; import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_CREATE_INSTANCE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_LOAD_METADATA; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_KEY; import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_SERVICE_URLS_PROPERTY_NAME; public class MetadataUtils { - public static final Logger logger = LoggerFactory.getLogger(MetadataUtils.class); + public static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MetadataUtils.class); public static void publishServiceDefinition(URL url, ServiceDescriptor serviceDescriptor, ApplicationModel applicationModel) { if (getMetadataReports(applicationModel).size() == 0) { String msg = "Remote Metadata Report Server is not provided or unavailable, will stop registering service definition to remote center!"; - logger.warn(msg); + logger.warn(REGISTRY_FAILED_LOAD_METADATA, "", "", msg); return; } @@ -104,7 +106,7 @@ public class MetadataUtils { } } catch (Exception e) { //ignore error - logger.error("publish service definition metadata error.", e); + logger.error(REGISTRY_FAILED_CREATE_INSTANCE, "", "", "publish service definition metadata error.", e); } } @@ -174,7 +176,7 @@ public class MetadataUtils { } } } catch (Exception e) { - logger.error("Failed to get app metadata for revision " + revision + " for type " + metadataType + " from instance " + instance.getAddress(), e); + logger.error(REGISTRY_FAILED_LOAD_METADATA, "", "", "Failed to get app metadata for revision " + revision + " for type " + metadataType + " from instance " + instance.getAddress(), e); metadataInfo = null; } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/DefaultMigrationAddressComparator.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/DefaultMigrationAddressComparator.java index 0c3d90a827..ca2cb524dd 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/DefaultMigrationAddressComparator.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/DefaultMigrationAddressComparator.java @@ -29,6 +29,8 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_INCORRECT_PARAMETER_VALUES; + public class DefaultMigrationAddressComparator implements MigrationAddressComparator { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultMigrationAddressComparator.class); private static final String MIGRATION_THRESHOLD = "dubbo.application.migration.threshold"; @@ -73,7 +75,7 @@ public class DefaultMigrationAddressComparator implements MigrationAddressCompar try { threshold = Float.parseFloat(rawThreshold); } catch (Exception e) { - logger.error("Invalid migration threshold " + rawThreshold); + logger.error(PROTOCOL_INCORRECT_PARAMETER_VALUES, "", "", "Invalid migration threshold " + rawThreshold); threshold = DEFAULT_THREAD; } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationInvoker.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationInvoker.java index fc525e9f87..9fbe66fa0a 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationInvoker.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationInvoker.java @@ -18,7 +18,7 @@ package org.apache.dubbo.registry.client.migration; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.status.reporter.FrameworkStatusReportService; import org.apache.dubbo.common.utils.CollectionUtils; @@ -44,11 +44,12 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_NOTIFY_EVENT; import static org.apache.dubbo.registry.client.migration.model.MigrationStep.APPLICATION_FIRST; import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; public class MigrationInvoker implements MigrationClusterInvoker { - private Logger logger = LoggerFactory.getLogger(MigrationInvoker.class); + private ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MigrationInvoker.class); private URL url; private URL consumerUrl; @@ -255,7 +256,7 @@ public class MigrationInvoker implements MigrationClusterInvoker { try { Thread.sleep(delay * 1000L); } catch (InterruptedException e) { - logger.error("Interrupted when waiting for address notify!" + e); + logger.error(REGISTRY_FAILED_NOTIFY_EVENT, "", "", "Interrupted when waiting for address notify!" + e); } } else { // do not wait address notify by default @@ -264,7 +265,7 @@ public class MigrationInvoker implements MigrationClusterInvoker { try { latch.await(delay, TimeUnit.SECONDS); } catch (InterruptedException e) { - logger.error("Interrupted when waiting for address notify!" + e); + logger.error(REGISTRY_FAILED_NOTIFY_EVENT, "", "", "Interrupted when waiting for address notify!" + e); } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandler.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandler.java index 6ce0f270e5..9f923f29f9 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandler.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandler.java @@ -23,6 +23,9 @@ import org.apache.dubbo.common.status.reporter.FrameworkStatusReportService; import org.apache.dubbo.registry.client.migration.model.MigrationRule; import org.apache.dubbo.registry.client.migration.model.MigrationStep; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NO_PARAMETERS_URL; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNEXPECTED_EXCEPTION; + public class MigrationRuleHandler { public static final String DUBBO_SERVICEDISCOVERY_MIGRATION = "dubbo.application.migration.step"; private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MigrationRuleHandler.class); @@ -51,7 +54,7 @@ public class MigrationRuleHandler { step = rule.getStep(consumerURL); threshold = rule.getThreshold(consumerURL); } catch (Exception e) { - logger.error("Failed to get step and threshold info from rule: " + rule, e); + logger.error(REGISTRY_NO_PARAMETERS_URL, "", "", "Failed to get step and threshold info from rule: " + rule, e); } if (refreshInvoker(step, threshold, rule)) { @@ -86,8 +89,8 @@ public class MigrationRuleHandler { report(step, originStep, "true"); } else { // migrate failed, do not save new step and rule - logger.warn("Migrate to " + step + " mode failed. Probably not satisfy the threshold you set " - + threshold + ". Please try re-publish configuration if you still after check."); + logger.warn(REGISTRY_UNEXPECTED_EXCEPTION, "", "", "Migrate to " + step + " mode failed. Probably not satisfy the threshold you set " + + threshold + ". Please try re-publish configuration if you still after check."); report(step, originStep, "false"); } @@ -104,7 +107,7 @@ public class MigrationRuleHandler { if (reportService.hasReporter()) { reportService.reportMigrationStepStatus( reportService.createMigrationStepReport(consumerURL.getServiceInterface(), consumerURL.getVersion(), - consumerURL.getGroup(), String.valueOf(originStep), String.valueOf(step), success)); + consumerURL.getGroup(), String.valueOf(originStep), String.valueOf(step), success)); } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleListener.java index 9623e8ae7e..946eea7bb5 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleListener.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleListener.java @@ -49,14 +49,18 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_THREAD_INTERRUPTED_EXCEPTION; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_INCORRECT_PARAMETER_VALUES; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_EMPTY_ADDRESS; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNEXPECTED_EXCEPTION; import static org.apache.dubbo.common.constants.RegistryConstants.INIT; /** * Listens to {@MigrationRule} from Config Center. - * + *

    * - Migration rule is of consumer application scope. * - Listener is shared among all invokers (interfaces), it keeps the relation between interface and handler. - * + *

    * There are two execution points: * - Refer, invoker behaviour is determined with default rule. * - Rule change, invoker behaviour is changed according to the newly received rule. @@ -104,7 +108,7 @@ public class MigrationRuleListener implements RegistryProtocolListener, Configur setRawRule(rawRule); } else { if (logger.isWarnEnabled()) { - logger.warn("Using default configuration rule because config center is not configured!"); + logger.warn(REGISTRY_EMPTY_ADDRESS, "", "", "Using default configuration rule because config center is not configured!"); } setRawRule(INIT); } @@ -131,7 +135,7 @@ public class MigrationRuleListener implements RegistryProtocolListener, Configur try { delay = Integer.parseInt(delayStr); } catch (Exception e) { - logger.warn("Invalid migration delay param " + delayStr); + logger.warn(PROTOCOL_INCORRECT_PARAMETER_VALUES, "", "", "Invalid migration delay param " + delayStr); } return delay; } @@ -142,12 +146,12 @@ public class MigrationRuleListener implements RegistryProtocolListener, Configur if (StringUtils.isEmpty(rawRule)) { // fail back to startup status rawRule = INIT; - //logger.warn("Received empty migration rule, will ignore."); + //logger.warn(PROTOCOL_INCORRECT_PARAMETER_VALUES, "", "", "Received empty migration rule, will ignore."); } try { ruleQueue.put(rawRule); } catch (InterruptedException e) { - logger.error("Put rawRule to rule management queue failed. rawRule: " + rawRule, e); + logger.error(COMMON_THREAD_INTERRUPTED_EXCEPTION, "", "", "Put rawRule to rule management queue failed. rawRule: " + rawRule, e); } if (executorSubmit.compareAndSet(false, true)) { @@ -160,7 +164,7 @@ public class MigrationRuleListener implements RegistryProtocolListener, Configur Thread.sleep(1000); } } catch (InterruptedException e) { - logger.error("Poll Rule from config center failed.", e); + logger.error(COMMON_THREAD_INTERRUPTED_EXCEPTION, "", "", "Poll Rule from config center failed.", e); } if (StringUtils.isEmpty(rule)) { continue; @@ -179,10 +183,10 @@ public class MigrationRuleListener implements RegistryProtocolListener, Configur ExecutorService executorService = Executors.newFixedThreadPool(100, new NamedThreadFactory("Dubbo-Invoker-Migrate")); List> migrationFutures = new ArrayList<>(handlers.size()); handlers.forEach((_key, handler) -> { - Future future = executorService.submit(() -> { + Future future = executorService.submit(() -> { handler.doMigrate(this.rule); }); - migrationFutures.add(future); + migrationFutures.add(future); }); Throwable migrationException = null; @@ -190,18 +194,18 @@ public class MigrationRuleListener implements RegistryProtocolListener, Configur try { future.get(); } catch (InterruptedException ie) { - logger.warn("Interrupted while waiting for migration async task to finish."); + logger.warn(REGISTRY_UNEXPECTED_EXCEPTION, "", "", "Interrupted while waiting for migration async task to finish."); } catch (ExecutionException ee) { migrationException = ee.getCause(); } } if (migrationException != null) { - logger.error("Migration async task failed.", migrationException); + logger.error(REGISTRY_UNEXPECTED_EXCEPTION, "", "", "Migration async task failed.", migrationException); } executorService.shutdown(); } } catch (Throwable t) { - logger.error("Error occurred when migration.", t); + logger.error(REGISTRY_UNEXPECTED_EXCEPTION, "", "", "Error occurred when migration.", t); } } }); @@ -222,7 +226,7 @@ public class MigrationRuleListener implements RegistryProtocolListener, Configur try { tmpRule = MigrationRule.parse(rawRule); } catch (Exception e) { - logger.error("Failed to parse migration rule...", e); + logger.error(PROTOCOL_INCORRECT_PARAMETER_VALUES, "", "", "Failed to parse migration rule...", e); } } return tmpRule; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java index 25389e35e4..53fd6840fe 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java @@ -290,7 +290,7 @@ public class RegistryDirectory extends DynamicDirectory { try { destroyUnusedInvokers(oldUrlInvokerMap, newUrlInvokerMap); // Close the unused Invoker } catch (Exception e) { - logger.warn("destroyUnusedInvokers error. ", e); + logger.warn(REGISTRY_FAILED_DESTROY_SERVICE, "", "", "destroyUnusedInvokers error. ", e); } // notify invokers refreshed @@ -346,7 +346,7 @@ public class RegistryDirectory extends DynamicDirectory { routers.add(router); } } catch (Throwable t) { - logger.error("convert router url to router error, url: " + url, t); + logger.error(PROXY_FAILED_CONVERT_URL, "", "", "convert router url to router error, url:" + url, t); } } @@ -441,9 +441,9 @@ public class RegistryDirectory extends DynamicDirectory { logger.error(PROTOCOL_UNSUPPORTED, "protocol extension does not installed", "", "Unsupported protocol.", new IllegalStateException("Unsupported protocol " + providerUrl.getProtocol() + - " in notified url: " + providerUrl + " from registry " + getUrl().getAddress() + - " to consumer " + NetUtils.getLocalHost() + ", supported protocol: " + - getUrl().getOrDefaultFrameworkModel().getExtensionLoader(Protocol.class).getSupportedExtensions())); + " in notified url: " + providerUrl + " from registry " + getUrl().getAddress() + + " to consumer " + NetUtils.getLocalHost() + ", supported protocol: " + + getUrl().getOrDefaultFrameworkModel().getExtensionLoader(Protocol.class).getSupportedExtensions())); return false; } @@ -578,7 +578,7 @@ public class RegistryDirectory extends DynamicDirectory { logger.debug("destroy invoker[" + invoker.getUrl() + "] success. "); } } catch (Exception e) { - logger.warn("destroy invoker[" + invoker.getUrl() + "] failed. " + e.getMessage(), e); + logger.warn(REGISTRY_FAILED_DESTROY_SERVICE, "", "", "destroy invoker[" + invoker.getUrl() + "] failed. " + e.getMessage(), e); } } } @@ -605,7 +605,7 @@ public class RegistryDirectory extends DynamicDirectory { // 1-16 - Unsupported category in NotifyListener logger.warn(REGISTRY_UNSUPPORTED_CATEGORY, "", "", "Unsupported category " + category + " in notified url: " + url + " from registry " + - getUrl().getAddress() + " to consumer " + NetUtils.getLocalHost()); + getUrl().getAddress() + " to consumer " + NetUtils.getLocalHost()); return false; } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index caf5f5d1ee..42073fec71 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -90,6 +90,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNEXPECTED_EXCEPTION; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNSUPPORTED_CATEGORY; import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP; import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE; import static org.apache.dubbo.common.constants.QosConstants.QOS_HOST; @@ -571,7 +573,7 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { public void reRefer(ClusterInvoker invoker, URL newSubscribeUrl) { if (!(invoker instanceof MigrationClusterInvoker)) { - logger.error("Only invoker type of MigrationClusterInvoker supports reRefer, current invoker is " + invoker.getClass()); + logger.error(REGISTRY_UNSUPPORTED_CATEGORY, "", "", "Only invoker type of MigrationClusterInvoker supports reRefer, current invoker is " + invoker.getClass()); return; } @@ -744,7 +746,7 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { String key = getCacheKey(originInvoker); ExporterChangeableWrapper exporter = bounds.get(key); if (exporter == null) { - logger.warn(new IllegalStateException("error state, exporter should not be null")); + logger.warn(REGISTRY_UNEXPECTED_EXCEPTION, "", "", "error state, exporter should not be null", new IllegalStateException("error state, exporter should not be null")); return; } //The current, may have been merged many times @@ -891,7 +893,7 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { try { registry.unregister(registerUrl); } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(REGISTRY_UNEXPECTED_EXCEPTION, "", "", t.getMessage(), t); } try { if (subscribeUrl != null) { @@ -914,7 +916,7 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { } } } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(REGISTRY_UNEXPECTED_EXCEPTION, "", "", t.getMessage(), t); } //TODO wait for shutdown timeout is a bit strange @@ -923,7 +925,7 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { try { exporter.unexport(); } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(REGISTRY_UNEXPECTED_EXCEPTION, "", "", t.getMessage(), t); } }, timeout, TimeUnit.MILLISECONDS); } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java index 01a3e3e356..5749da821e 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java @@ -66,6 +66,7 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAI import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_DESTROY_UNREGISTER_URL; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_READ_WRITE_CACHE_FILE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_DELETE_LOCKFILE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNEXPECTED_EXCEPTION; import static org.apache.dubbo.common.constants.RegistryConstants.ACCEPTS_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; @@ -78,7 +79,7 @@ import static org.apache.dubbo.registry.Constants.USER_HOME; /** *

    * Provides a fail-safe registry service backed by cache file. The consumer/provider can still find each other when registry center crashed. - * + *

    * (SPI, Prototype, ThreadSafe) */ public abstract class AbstractRegistry implements Registry { @@ -222,7 +223,7 @@ public abstract class AbstractRegistry implements Registry { } try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw"); - FileChannel channel = raf.getChannel()) { + FileChannel channel = raf.getChannel()) { FileLock lock = channel.tryLock(); if (lock == null) { @@ -565,7 +566,7 @@ public abstract class AbstractRegistry implements Registry { registryCacheExecutor.schedule(() -> doSaveProperties(version), DEFAULT_INTERVAL_SAVE_PROPERTIES, TimeUnit.MILLISECONDS); } } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(REGISTRY_UNEXPECTED_EXCEPTION, "", "", t.getMessage(), t); } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java index d17c0dae35..fa906cf4ca 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java @@ -36,6 +36,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_NOTIFY_EVENT; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNEXPECTED_EXCEPTION; import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY_RETRY_PERIOD; import static org.apache.dubbo.registry.Constants.REGISTRY_RETRY_PERIOD_KEY; @@ -208,8 +210,8 @@ public abstract class FailbackRegistry extends AbstractRegistry { // If the startup detection is opened, the Exception is thrown directly. boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) - && url.getParameter(Constants.CHECK_KEY, true) - && (url.getPort() != 0); + && url.getParameter(Constants.CHECK_KEY, true) + && (url.getPort() != 0); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { @@ -217,7 +219,7 @@ public abstract class FailbackRegistry extends AbstractRegistry { } throw new IllegalStateException("Failed to register " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t); } else { - logger.error("Failed to register " + url + ", waiting for retry, cause: " + t.getMessage(), t); + logger.error(REGISTRY_UNEXPECTED_EXCEPTION, "", "", "Failed to register " + url + ", waiting for retry, cause: " + t.getMessage(), t); } // Record a failed registration request to a failed list, retry regularly @@ -257,8 +259,8 @@ public abstract class FailbackRegistry extends AbstractRegistry { // If the startup detection is opened, the Exception is thrown directly. boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) - && url.getParameter(Constants.CHECK_KEY, true) - && (url.getPort() != 0); + && url.getParameter(Constants.CHECK_KEY, true) + && (url.getPort() != 0); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { @@ -266,7 +268,7 @@ public abstract class FailbackRegistry extends AbstractRegistry { } throw new IllegalStateException("Failed to unregister " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t); } else { - logger.error("Failed to unregister " + url + ", waiting for retry, cause: " + t.getMessage(), t); + logger.error(REGISTRY_UNEXPECTED_EXCEPTION, "", "", "Failed to unregister " + url + ", waiting for retry, cause: " + t.getMessage(), t); } // Record a failed registration request to a failed list, retry regularly @@ -302,11 +304,11 @@ public abstract class FailbackRegistry extends AbstractRegistry { List urls = getCacheUrls(url); if (CollectionUtils.isNotEmpty(urls)) { notify(url, listener, urls); - logger.error("Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getCacheFile().getName() + ", cause: " + t.getMessage(), t); + logger.error(REGISTRY_FAILED_NOTIFY_EVENT, "", "", "Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getCacheFile().getName() + ", cause: " + t.getMessage(), t); } else { // If the startup detection is opened, the Exception is thrown directly. boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) - && url.getParameter(Constants.CHECK_KEY, true); + && url.getParameter(Constants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { @@ -314,7 +316,7 @@ public abstract class FailbackRegistry extends AbstractRegistry { } throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t); } else { - logger.error("Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t); + logger.error(REGISTRY_FAILED_NOTIFY_EVENT, "", "", "Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t); } } @@ -335,7 +337,7 @@ public abstract class FailbackRegistry extends AbstractRegistry { // If the startup detection is opened, the Exception is thrown directly. boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) - && url.getParameter(Constants.CHECK_KEY, true); + && url.getParameter(Constants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { @@ -343,7 +345,7 @@ public abstract class FailbackRegistry extends AbstractRegistry { } throw new IllegalStateException("Failed to unsubscribe " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t); } else { - logger.error("Failed to unsubscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t); + logger.error(REGISTRY_FAILED_NOTIFY_EVENT, "", "", "Failed to unsubscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t); } // Record a failed registration request to a failed list, retry regularly @@ -363,7 +365,7 @@ public abstract class FailbackRegistry extends AbstractRegistry { doNotify(url, listener, urls); } catch (Exception t) { // Record a failed registration request to a failed list - logger.error("Failed to notify addresses for subscribe " + url + ", cause: " + t.getMessage(), t); + logger.error(REGISTRY_FAILED_NOTIFY_EVENT, "", "", "Failed to notify addresses for subscribe " + url + ", cause: " + t.getMessage(), t); } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/RegistryManager.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/RegistryManager.java index 7a2e187a3f..9d46730594 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/RegistryManager.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/RegistryManager.java @@ -37,6 +37,7 @@ import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_FETCH_INSTANCE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNEXPECTED_EXCEPTION; /** * Application Level, used to collect Registries @@ -79,7 +80,7 @@ public class RegistryManager { registries.put(key, registry); } - public List getServiceDiscoveries() { + public List getServiceDiscoveries() { return getRegistries() .stream() .filter(registry -> registry instanceof ServiceDiscoveryRegistry) @@ -106,7 +107,7 @@ public class RegistryManager { try { registry.destroy(); } catch (Throwable e) { - LOGGER.warn(e.getMessage(), e); + LOGGER.warn(REGISTRY_UNEXPECTED_EXCEPTION, "", "", e.getMessage(), e); } } registries.clear(); @@ -129,7 +130,7 @@ public class RegistryManager { // 1-12 Failed to fetch (server) instance since the registry instances have been destroyed. LOGGER.warn(REGISTRY_FAILED_FETCH_INSTANCE, "misuse of the methods", "", "All registry instances have been destroyed, failed to fetch any instance. " + - "Usually, this means no need to try to do unnecessary redundant resource clearance, all registries has been taken care of."); + "Usually, this means no need to try to do unnecessary redundant resource clearance, all registries has been taken care of."); return DEFAULT_NOP_REGISTRY; } diff --git a/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java b/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java index 48b3f668a7..0bbdf57679 100644 --- a/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java +++ b/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java @@ -52,6 +52,7 @@ import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_SOCKET_EXCEPTION; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.OVERRIDE_PROTOCOL; @@ -122,7 +123,7 @@ public class MulticastRegistry extends FailbackRegistry { Arrays.fill(buf, (byte) 0); } catch (Throwable e) { if (!multicastSocket.isClosed()) { - logger.error(e.getMessage(), e); + logger.error(REGISTRY_SOCKET_EXCEPTION, "", "", e.getMessage(), e); } } } @@ -138,7 +139,7 @@ public class MulticastRegistry extends FailbackRegistry { try { clean(); // Remove the expired } catch (Throwable t) { // Defensive fault tolerance - logger.error("Unexpected exception occur at clean expired provider, cause: " + t.getMessage(), t); + logger.error(REGISTRY_SOCKET_EXCEPTION, "", "", "Unexpected exception occur at clean expired provider, cause: " + t.getMessage(), t); } }, cleanPeriod, cleanPeriod, TimeUnit.MILLISECONDS); } else { @@ -151,10 +152,10 @@ public class MulticastRegistry extends FailbackRegistry { String message = "Invalid multicast address " + multicastAddress; if (multicastAddress instanceof Inet4Address) { throw new IllegalArgumentException(message + ", " + - "ipv4 multicast address scope: 224.0.0.0 - 239.255.255.255."); + "ipv4 multicast address scope: 224.0.0.0 - 239.255.255.255."); } else { throw new IllegalArgumentException(message + ", " + "ipv6 multicast address must start with ff, " + - "for example: ff01::1"); + "for example: ff01::1"); } } } @@ -168,7 +169,7 @@ public class MulticastRegistry extends FailbackRegistry { for (URL url : new HashSet(providers)) { if (isExpired(url)) { if (logger.isWarnEnabled()) { - logger.warn("Clean expired provider " + url); + logger.warn(REGISTRY_SOCKET_EXCEPTION, "", "", "Clean expired provider " + url); } doUnregister(url); } @@ -213,7 +214,7 @@ public class MulticastRegistry extends FailbackRegistry { if (UrlUtils.isMatch(url, u)) { String host = remoteAddress != null && remoteAddress.getAddress() != null ? remoteAddress.getAddress().getHostAddress() : url.getIp(); if (url.getParameter("unicast", true) // Whether the consumer's machine has only one process - && !NetUtils.getLocalHost().equals(host)) { // Multiple processes in the same machine cannot be unicast with unicast or there will be only one process receiving information + && !NetUtils.getLocalHost().equals(host)) { // Multiple processes in the same machine cannot be unicast with unicast or there will be only one process receiving information unicast(REGISTER + " " + u.toFullString(), host); } else { multicast(REGISTER + " " + u.toFullString()); @@ -301,13 +302,13 @@ public class MulticastRegistry extends FailbackRegistry { try { ExecutorUtil.cancelScheduledFuture(cleanFuture); } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(REGISTRY_SOCKET_EXCEPTION, "", "", t.getMessage(), t); } try { multicastSocket.leaveGroup(multicastAddress); multicastSocket.close(); } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(REGISTRY_SOCKET_EXCEPTION, "", "", t.getMessage(), t); } ExecutorUtil.gracefulShutdown(cleanExecutor, cleanPeriod); } diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java index fa47d05216..2b5cb33804 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java @@ -64,6 +64,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; @@ -279,7 +280,7 @@ public class NacosRegistry extends FailbackRegistry { } else { Map listenerMap = originToAggregateListener.get(url); if (listenerMap == null) { - logger.warn(String.format("No aggregate listener found for url %s, this service might have already been unsubscribed.", url)); + logger.warn(REGISTRY_NACOS_EXCEPTION, "", "", String.format("No aggregate listener found for url %s, this service might have already been unsubscribed.", url)); return; } NacosAggregateListener nacosAggregateListener = listenerMap.remove(listener); @@ -291,7 +292,7 @@ public class NacosRegistry extends FailbackRegistry { NacosInstanceManageUtil.removeCorrespondingServiceNames(serviceName); } } catch (NacosException e) { - logger.error("Failed to unsubscribe " + url + " to nacos " + getUrl() + ", cause: " + e.getMessage(), e); + logger.error(REGISTRY_NACOS_EXCEPTION, "", "", "Failed to unsubscribe " + url + " to nacos " + getUrl() + ", cause: " + e.getMessage(), e); } } if (listenerMap.isEmpty()) { @@ -353,7 +354,7 @@ public class NacosRegistry extends FailbackRegistry { try { Set serviceNames = new LinkedHashSet<>(); serviceNames.addAll(namingService.getServicesOfServer(1, Integer.MAX_VALUE, - getUrl().getGroup(Constants.DEFAULT_GROUP)).getData() + getUrl().getGroup(Constants.DEFAULT_GROUP)).getData() .stream() .filter(this::isConformRules) .map(NacosServiceName::new) @@ -530,11 +531,22 @@ public class NacosRegistry extends FailbackRegistry { return serviceNames; } + @Override + public void destroy() { + super.destroy(); + try { + this.namingService.shutdown(); + } catch (NacosException e) { + logger.warn(REGISTRY_NACOS_EXCEPTION, "", "", "Unable to shutdown nacos naming service", e); + } + this.nacosListeners.clear(); + } + private List toUrlWithEmpty(URL consumerURL, Collection instances) { List urls = buildURLs(consumerURL, instances); // Nacos does not support configurators and routers from registry, so all notifications are of providers type. if (urls.size() == 0 && !getUrl().getParameter(ENABLE_EMPTY_PROTECTION_KEY, true)) { - logger.warn("Received empty url address list and empty protection is disabled, will clear current available addresses"); + logger.warn(REGISTRY_NACOS_EXCEPTION, "", "", "Received empty url address list and empty protection is disabled, will clear current available addresses"); URL empty = URLBuilder.from(consumerURL) .setProtocol(EMPTY_PROTOCOL) .addParameter(CATEGORY_KEY, DEFAULT_CATEGORY) diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.java index 6435111df7..559314e69a 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.java @@ -19,7 +19,7 @@ package org.apache.dubbo.registry.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.function.ThrowableFunction; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.registry.client.AbstractServiceDiscovery; @@ -44,6 +44,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION; import static org.apache.dubbo.common.function.ThrowableConsumer.execute; import static org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils.createNamingService; import static org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils.getGroup; @@ -57,7 +58,7 @@ import static org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils.toIns */ public class NacosServiceDiscovery extends AbstractServiceDiscovery { - private final Logger logger = LoggerFactory.getLogger(getClass()); + private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final String group; @@ -72,7 +73,7 @@ public class NacosServiceDiscovery extends AbstractServiceDiscovery { this.namingService = createNamingService(registryURL); // backward compatibility for 3.0.x this.group = Boolean.parseBoolean(ConfigurationUtils.getProperty(applicationModel, NACOS_SD_USE_DEFAULT_GROUP_KEY, "false")) ? - DEFAULT_GROUP: getGroup(registryURL); + DEFAULT_GROUP : getGroup(registryURL); } @Override @@ -132,7 +133,7 @@ public class NacosServiceDiscovery extends AbstractServiceDiscovery { namingService.subscribe(serviceName, group, nacosEventListener); eventListeners.put(serviceName, nacosEventListener); } catch (NacosException e) { - logger.error("add nacos service instances changed listener fail ", e); + logger.error(REGISTRY_NACOS_EXCEPTION, "", "", "add nacos service instances changed listener fail ", e); } } } @@ -152,7 +153,7 @@ public class NacosServiceDiscovery extends AbstractServiceDiscovery { try { namingService.unsubscribe(serviceName, group, nacosEventListener); } catch (NacosException e) { - logger.error("remove nacos service instances changed listener fail ", e); + logger.error(REGISTRY_NACOS_EXCEPTION, "", "", "remove nacos service instances changed listener fail ", e); } } } diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java index 6771bf0e64..08f046a76b 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java @@ -42,6 +42,7 @@ import static com.alibaba.nacos.api.PropertyKeyConst.USERNAME; import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static com.alibaba.nacos.client.naming.utils.UtilAndComs.NACOS_NAMING_LOG_NAME; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION; import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; import static org.apache.dubbo.common.utils.StringConstantFieldValuePredicate.of; @@ -119,7 +120,7 @@ public class NacosNamingServiceUtils { namingService = NacosFactory.createNamingService(nacosProperties); } catch (NacosException e) { if (logger.isErrorEnabled()) { - logger.error(e.getErrMsg(), e); + logger.error(REGISTRY_NACOS_EXCEPTION, "", "", e.getErrMsg(), e); } throw new IllegalStateException(e); } @@ -157,10 +158,10 @@ public class NacosNamingServiceUtils { Map parameters = url.getParameters(of(PropertyKeyConst.class)); // Put all parameters properties.putAll(parameters); - if (StringUtils.isNotEmpty(url.getUsername())){ + if (StringUtils.isNotEmpty(url.getUsername())) { properties.put(USERNAME, url.getUsername()); } - if (StringUtils.isNotEmpty(url.getPassword())){ + if (StringUtils.isNotEmpty(url.getPassword())) { properties.put(PASSWORD, url.getPassword()); } diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java index d427cea98b..08fa381866 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java @@ -46,6 +46,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; @@ -87,20 +88,20 @@ public class ZookeeperRegistry extends CacheableFailbackRegistry { this.zkClient.addStateListener((state) -> { if (state == StateListener.RECONNECTED) { - logger.warn("Trying to fetch the latest urls, in case there are provider changes during connection loss.\n" + + logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Trying to fetch the latest urls, in case there are provider changes during connection loss.\n" + " Since ephemeral ZNode will not get deleted for a connection lose, " + "there's no need to re-register url of this instance."); ZookeeperRegistry.this.fetchLatestAddresses(); } else if (state == StateListener.NEW_SESSION_CREATED) { - logger.warn("Trying to re-register urls and re-subscribe listeners of this instance to registry..."); + logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Trying to re-register urls and re-subscribe listeners of this instance to registry..."); try { ZookeeperRegistry.this.recover(); } catch (Exception e) { - logger.error(e.getMessage(), e); + logger.error(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", e.getMessage(), e); } } else if (state == StateListener.SESSION_LOST) { - logger.warn("Url of this instance will be deleted from registry soon. " + + logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Url of this instance will be deleted from registry soon. " + "Dubbo client will try to re-register once a new session is created."); } else if (state == StateListener.SUSPENDED) { @@ -360,7 +361,7 @@ public class ZookeeperRegistry extends CacheableFailbackRegistry { /** * Triggered when children get changed. It will be invoked by implementation of CuratorWatcher. - * + *

    * 'org.apache.dubbo.remoting.zookeeper.curator5.Curator5ZookeeperClient.CuratorWatcherImpl' (Curator 5) */ private class RegistryChildListenerImpl implements ChildListener { @@ -382,7 +383,7 @@ public class ZookeeperRegistry extends CacheableFailbackRegistry { try { latch.await(); } catch (InterruptedException e) { - logger.warn("Zookeeper children listener thread was interrupted unexpectedly, may cause race condition with the main thread."); + logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Zookeeper children listener thread was interrupted unexpectedly, may cause race condition with the main thread."); } notifier.notify(path, children); diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java index 9e2aea232e..91520cd87f 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java @@ -19,7 +19,7 @@ package org.apache.dubbo.registry.zookeeper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.function.ThrowableConsumer; import org.apache.dubbo.common.function.ThrowableFunction; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.registry.client.AbstractServiceDiscovery; import org.apache.dubbo.registry.client.ServiceDiscovery; @@ -40,6 +40,7 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION; import static org.apache.dubbo.common.function.ThrowableFunction.execute; import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkUtils.build; import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkUtils.buildCuratorFramework; @@ -55,7 +56,7 @@ import static org.apache.dubbo.rpc.RpcException.REGISTRY_EXCEPTION; */ public class ZookeeperServiceDiscovery extends AbstractServiceDiscovery { - private final Logger logger = LoggerFactory.getLogger(getClass()); + private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); public static final String DEFAULT_GROUP = "/services"; @@ -165,7 +166,7 @@ public class ZookeeperServiceDiscovery extends AbstractServiceDiscovery { } catch (KeeperException.NoNodeException e) { // ignored if (logger.isErrorEnabled()) { - logger.error(e.getMessage()); + logger.error(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", e.getMessage()); } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); @@ -189,7 +190,7 @@ public class ZookeeperServiceDiscovery extends AbstractServiceDiscovery { watcher.setLatch(latch); curatorFramework.getChildren().usingWatcher(watcher).forPath(path); } catch (Exception e) { - logger.error("Trying to recover from new zkClient session failed, path is " + path + ", error msg: " + e.getMessage()); + logger.error(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Trying to recover from new zkClient session failed, path is " + path + ", error msg: " + e.getMessage()); } List instances = this.getInstances(watcher.getServiceName()); diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtils.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtils.java index 12e6fa03b7..93fe405931 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtils.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtils.java @@ -49,6 +49,7 @@ import static org.apache.curator.x.discovery.ServiceInstance.builder; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.SESSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION; import static org.apache.dubbo.registry.zookeeper.ZookeeperServiceDiscovery.DEFAULT_GROUP; import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.BASE_SLEEP_TIME; import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.BLOCK_UNTIL_CONNECTED_UNIT; @@ -120,7 +121,7 @@ public abstract class CuratorFrameworkUtils { public static List build(URL registryUrl, Collection> instances) { - return instances.stream().map((i)->build(registryUrl, i)).collect(Collectors.toList()); + return instances.stream().map((i) -> build(registryUrl, i)).collect(Collectors.toList()); } public static ServiceInstance build(URL registryUrl, org.apache.curator.x.discovery.ServiceInstance instance) { @@ -192,24 +193,24 @@ public abstract class CuratorFrameworkUtils { try { sessionId = client.getZookeeperClient().getZooKeeper().getSessionId(); } catch (Exception e) { - logger.warn("Curator client state changed, but failed to get the related zk session instance."); + logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator client state changed, but failed to get the related zk session instance."); } if (state == ConnectionState.LOST) { - logger.warn("Curator zookeeper session " + Long.toHexString(lastSessionId) + " expired."); + logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator zookeeper session " + Long.toHexString(lastSessionId) + " expired."); } else if (state == ConnectionState.SUSPENDED) { - logger.warn("Curator zookeeper connection of session " + Long.toHexString(sessionId) + " timed out. " + + logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator zookeeper connection of session " + Long.toHexString(sessionId) + " timed out. " + "connection timeout value is " + timeout + ", session expire timeout value is " + sessionExpireMs); } else if (state == ConnectionState.CONNECTED) { lastSessionId = sessionId; logger.info("Curator zookeeper client instance initiated successfully, session id is " + Long.toHexString(sessionId)); } else if (state == ConnectionState.RECONNECTED) { if (lastSessionId == sessionId && sessionId != UNKNOWN_SESSION_ID) { - logger.warn("Curator zookeeper connection recovered from connection lose, " + + logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator zookeeper connection recovered from connection lose, " + "reuse the old session " + Long.toHexString(sessionId)); serviceDiscovery.recover(); } else { - logger.warn("New session created after old session lost, " + + logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "New session created after old session lost, " + "old session " + Long.toHexString(lastSessionId) + ", new session " + Long.toHexString(sessionId)); lastSessionId = sessionId; serviceDiscovery.recover(); diff --git a/dubbo-remoting/dubbo-remoting-api/pom.xml b/dubbo-remoting/dubbo-remoting-api/pom.xml index c9b06822ce..6ac711e3e3 100644 --- a/dubbo-remoting/dubbo-remoting-api/pom.xml +++ b/dubbo-remoting/dubbo-remoting-api/pom.xml @@ -42,7 +42,41 @@ io.netty - netty-all + netty-codec + compile + + + io.netty + netty-handler + compile + + + io.netty + netty-transport + compile + + + io.netty + netty-transport-classes-epoll + compile + + + io.netty + netty-transport-native-epoll + linux-aarch_64 + runtime + + + io.netty + netty-transport-native-kqueue + osx-x86_64 + runtime + + + io.netty + netty-transport-native-kqueue + osx-aarch_64 + runtime org.apache.dubbo diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingScopeModelInitializer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingScopeModelInitializer.java index 706d7ccbfc..30f6cdf309 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingScopeModelInitializer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingScopeModelInitializer.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.remoting; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter; import org.apache.dubbo.rpc.model.ApplicationModel; @@ -26,12 +26,14 @@ import org.apache.dubbo.rpc.model.ScopeModelInitializer; import java.util.List; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_DESTROY_ZOOKEEPER; + /** * Scope model initializer for remoting-api */ public class RemotingScopeModelInitializer implements ScopeModelInitializer { - private static final Logger logger = LoggerFactory.getLogger(RemotingScopeModelInitializer.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RemotingScopeModelInitializer.class); @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) { @@ -48,7 +50,7 @@ public class RemotingScopeModelInitializer implements ScopeModelInitializer { zkTransporter.destroy(); } } catch (Exception e) { - logger.error("Error encountered while destroying ZookeeperTransporter: " + e.getMessage(), e); + logger.error(TRANSPORT_FAILED_DESTROY_ZOOKEEPER, "", "", "Error encountered while destroying ZookeeperTransporter: " + e.getMessage(), e); } }); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/ConnectionHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/ConnectionHandler.java index c9270a1740..6f0baa6158 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/ConnectionHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/ConnectionHandler.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.remoting.api; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import io.netty.channel.Channel; @@ -29,9 +29,11 @@ import io.netty.util.AttributeKey; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNEXPECTED_EXCEPTION; + @ChannelHandler.Sharable public class ConnectionHandler extends ChannelInboundHandlerAdapter { - private static final Logger log = LoggerFactory.getLogger(ConnectionHandler.class); + private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(ConnectionHandler.class); private static final AttributeKey GO_AWAY_KEY = AttributeKey.valueOf("dubbo_channel_goaway"); private final Connection connection; @@ -68,7 +70,7 @@ public class ConnectionHandler extends ChannelInboundHandlerAdapter { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - log.warn(String.format("Channel error:%s", ctx.channel()), cause); + log.warn(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", String.format("Channel error:%s", ctx.channel()), cause); ctx.close(); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/SslClientTlsHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/SslClientTlsHandler.java index 683412cc7d..5a7239c16a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/SslClientTlsHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/SslClientTlsHandler.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.api; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import io.netty.channel.ChannelHandlerContext; @@ -29,10 +29,12 @@ import io.netty.handler.ssl.SslHandshakeCompletionEvent; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSession; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNEXPECTED_EXCEPTION; -public class SslClientTlsHandler extends ChannelInboundHandlerAdapter { - private static final Logger logger = LoggerFactory.getLogger(SslClientTlsHandler.class); +public class SslClientTlsHandler extends ChannelInboundHandlerAdapter { + + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SslClientTlsHandler.class); private final SslContext sslContext; @@ -59,7 +61,7 @@ public class SslClientTlsHandler extends ChannelInboundHandlerAdapter { logger.info("TLS negotiation succeed with session: " + session); ctx.pipeline().remove(this); } else { - logger.error("TLS negotiation failed when trying to accept new connection.", handshakeEvent.cause()); + logger.error(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", "TLS negotiation failed when trying to accept new connection.", handshakeEvent.cause()); ctx.fireExceptionCaught(handshakeEvent.cause()); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/SslContexts.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/SslContexts.java index e937c8de03..ab7a2ff20b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/SslContexts.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/SslContexts.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.api; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.SslConfig; import org.apache.dubbo.config.context.ConfigManager; @@ -34,9 +34,11 @@ import java.io.InputStream; import java.security.Provider; import java.security.Security; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE_STREAM; + public class SslContexts { - private static final Logger logger = LoggerFactory.getLogger(SslContexts.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SslContexts.class); public static SslContext buildServerSslContext(URL url) { ConfigManager globalConfigManager = url.getOrDefaultApplicationModel().getApplicationConfigManager(); @@ -128,8 +130,8 @@ public class SslContexts { return SslProvider.JDK; } throw new IllegalStateException( - "Could not find any valid TLS provider, please check your dependency or deployment environment, " + - "usually netty-tcnative, Conscrypt, or Jetty NPN/ALPN is needed."); + "Could not find any valid TLS provider, please check your dependency or deployment environment, " + + "usually netty-tcnative, Conscrypt, or Jetty NPN/ALPN is needed."); } private static boolean checkJdkProvider() { @@ -144,7 +146,7 @@ public class SslContexts { try { stream.close(); } catch (IOException e) { - logger.warn("Failed to close a stream.", e); + logger.warn(TRANSPORT_FAILED_CLOSE_STREAM, "", "", "Failed to close a stream.", e); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/SslServerTlsHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/SslServerTlsHandler.java index 24e326af33..ee926f06d6 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/SslServerTlsHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/SslServerTlsHandler.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.api; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import io.netty.buffer.ByteBuf; @@ -31,8 +31,10 @@ import io.netty.handler.ssl.SslHandshakeCompletionEvent; import javax.net.ssl.SSLSession; import java.util.List; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNEXPECTED_EXCEPTION; + public class SslServerTlsHandler extends ByteToMessageDecoder { - private static final Logger logger = LoggerFactory.getLogger(SslServerTlsHandler.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SslServerTlsHandler.class); private final SslContext sslContext; private final boolean detectSsl; @@ -57,7 +59,7 @@ public class SslServerTlsHandler extends ByteToMessageDecoder { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - logger.error("TLS negotiation failed when trying to accept new connection.", cause); + logger.error(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", "TLS negotiation failed when trying to accept new connection.", cause); } @Override @@ -70,7 +72,7 @@ public class SslServerTlsHandler extends ByteToMessageDecoder { // Remove after handshake success. ctx.pipeline().remove(this); } else { - logger.error("TLS negotiation failed when trying to accept new connection.", handshakeEvent.cause()); + logger.error(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", "TLS negotiation failed when trying to accept new connection.", handshakeEvent.cause()); ctx.close(); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/PortUnificationExchanger.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/PortUnificationExchanger.java index 10fec10a96..0e56046c6d 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/PortUnificationExchanger.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/PortUnificationExchanger.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.exchange; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; @@ -29,9 +29,11 @@ import java.util.ArrayList; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_SERVER; + public class PortUnificationExchanger { - private static final Logger log = LoggerFactory.getLogger(PortUnificationExchanger.class); + private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(PortUnificationExchanger.class); private static final ConcurrentMap servers = new ConcurrentHashMap<>(); public static RemotingServer bind(URL url, ChannelHandler handler) { @@ -60,7 +62,7 @@ public class PortUnificationExchanger { try { server.close(); } catch (Throwable throwable) { - log.error("Close all port unification server failed", throwable); + log.error(PROTOCOL_ERROR_CLOSE_SERVER, "", "", "Close all port unification server failed", throwable); } } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/codec/ExchangeCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/codec/ExchangeCodec.java index 44cd564f57..d631030637 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/codec/ExchangeCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/codec/ExchangeCodec.java @@ -20,7 +20,7 @@ import org.apache.dubbo.common.Version; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.io.Bytes; import org.apache.dubbo.common.io.StreamUtils; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.Cleanable; import org.apache.dubbo.common.serialize.ObjectInput; @@ -43,6 +43,10 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_EXCEED_PAYLOAD_LIMIT; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RESPONSE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_SKIP_UNUSED_STREAM; + /** * ExchangeCodec. */ @@ -59,7 +63,7 @@ public class ExchangeCodec extends TelnetCodec { protected static final byte FLAG_TWOWAY = (byte) 0x40; protected static final byte FLAG_EVENT = (byte) 0x20; protected static final int SERIALIZATION_MASK = 0x1f; - private static final Logger logger = LoggerFactory.getLogger(ExchangeCodec.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ExchangeCodec.class); public Short getMagicCode() { return MAGIC; @@ -88,7 +92,7 @@ public class ExchangeCodec extends TelnetCodec { protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byte[] header) throws IOException { // check magic number. if (readable > 0 && header[0] != MAGIC_HIGH - || readable > 1 && header[1] != MAGIC_LOW) { + || readable > 1 && header[1] != MAGIC_LOW) { int length = header.length; if (header.length < readable) { header = Bytes.copyOf(header, readable); @@ -132,11 +136,11 @@ public class ExchangeCodec extends TelnetCodec { if (is.available() > 0) { try { if (logger.isWarnEnabled()) { - logger.warn("Skip input stream " + is.available()); + logger.warn(TRANSPORT_SKIP_UNUSED_STREAM, "", "", "Skip input stream " + is.available()); } StreamUtils.skipUnusedStream(is); } catch (IOException e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_SKIP_UNUSED_STREAM, "", "", e.getMessage(), e); } } } @@ -298,10 +302,10 @@ public class ExchangeCodec extends TelnetCodec { // encode response data or error message. if (status == Response.OK) { - if(res.isHeartbeat()){ + if (res.isHeartbeat()) { // heartbeat response data is always null bos.write(CodecSupport.getNullBytesOf(serialization)); - }else { + } else { ObjectOutput out = serialization.serialize(channel.getUrl(), bos); if (res.isEvent()) { encodeEventData(channel, out, res.getResult()); @@ -341,23 +345,23 @@ public class ExchangeCodec extends TelnetCodec { r.setStatus(Response.BAD_RESPONSE); if (t instanceof ExceedPayloadLimitException) { - logger.warn(t.getMessage(), t); + logger.warn(TRANSPORT_EXCEED_PAYLOAD_LIMIT, "", "", t.getMessage(), t); try { r.setErrorMessage(t.getMessage()); channel.send(r); return; } catch (RemotingException e) { - logger.warn("Failed to send bad_response info back: " + t.getMessage() + ", cause: " + e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_RESPONSE, "", "", "Failed to send bad_response info back: " + t.getMessage() + ", cause: " + e.getMessage(), e); } } else { // FIXME log error message in Codec and handle in caught() of IoHanndler? - logger.warn("Fail to encode response: " + res + ", send bad_response info instead, cause: " + t.getMessage(), t); + logger.warn(TRANSPORT_FAILED_RESPONSE, "", "", "Fail to encode response: " + res + ", send bad_response info instead, cause: " + t.getMessage(), t); try { r.setErrorMessage("Failed to send response: " + res + ", cause: " + StringUtils.toString(t)); channel.send(r); return; } catch (RemotingException e) { - logger.warn("Failed to send bad_response info back: " + res + ", cause: " + e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_RESPONSE, "", "", "Failed to send bad_response info back: " + res + ", cause: " + e.getMessage(), e); } } } @@ -493,7 +497,7 @@ public class ExchangeCodec extends TelnetCodec { } res.setStatus(Response.CLIENT_ERROR); String errorMsg = "Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel; - logger.error(errorMsg); + logger.error(TRANSPORT_EXCEED_PAYLOAD_LIMIT, "", "", errorMsg); res.setErrorMessage(errorMsg); return res; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java index d2edbbe15d..9ca69e9df1 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.remoting.exchange.support; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.GlobalResourceInitializer; import org.apache.dubbo.common.threadpool.ThreadlessExecutor; @@ -41,13 +41,14 @@ import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_TIMEOUT_SERVER; /** * DefaultFuture. */ public class DefaultFuture extends CompletableFuture { - private static final Logger logger = LoggerFactory.getLogger(DefaultFuture.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultFuture.class); /** * in-flight channels @@ -184,11 +185,11 @@ public class DefaultFuture extends CompletableFuture { } future.doReceived(response); } else { - logger.warn("The timeout response finally returned at " - + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) - + ", response status is " + response.getStatus() - + (channel == null ? "" : ", channel: " + channel.getLocalAddress() - + " -> " + channel.getRemoteAddress()) + ", please check provider side for detailed result."); + logger.warn(PROTOCOL_TIMEOUT_SERVER, "", "", "The timeout response finally returned at " + + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) + + ", response status is " + response.getStatus() + + (channel == null ? "" : ", channel: " + channel.getLocalAddress() + + " -> " + channel.getRemoteAddress()) + ", please check provider side for detailed result."); } } finally { CHANNELS.remove(response.getId()); @@ -229,7 +230,7 @@ public class DefaultFuture extends CompletableFuture { ThreadlessExecutor threadlessExecutor = (ThreadlessExecutor) executor; if (threadlessExecutor.isWaiting()) { threadlessExecutor.notifyReturn(new IllegalStateException("The result has returned, but the biz thread is still waiting" + - " which is not an expected state, interrupt the thread manually by returning an exception.")); + " which is not an expected state, interrupt the thread manually by returning an exception.")); } } } @@ -261,14 +262,14 @@ public class DefaultFuture extends CompletableFuture { private String getTimeoutMessage(boolean scan) { long nowTimestamp = System.currentTimeMillis(); return (sent > 0 ? "Waiting server-side response timeout" : "Sending request timeout in client-side") - + (scan ? " by scan timer" : "") + ". start time: " - + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(start))) + ", end time: " - + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(nowTimestamp))) + "," - + (sent > 0 ? " client elapsed: " + (sent - start) - + " ms, server elapsed: " + (nowTimestamp - sent) - : " elapsed: " + (nowTimestamp - start)) + " ms, timeout: " - + timeout + " ms, request: " + (logger.isDebugEnabled() ? request : request.copyWithoutData()) + ", channel: " + channel.getLocalAddress() - + " -> " + channel.getRemoteAddress(); + + (scan ? " by scan timer" : "") + ". start time: " + + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(start))) + ", end time: " + + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(nowTimestamp))) + "," + + (sent > 0 ? " client elapsed: " + (sent - start) + + " ms, server elapsed: " + (nowTimestamp - sent) + : " elapsed: " + (nowTimestamp - start)) + " ms, timeout: " + + timeout + " ms, request: " + (logger.isDebugEnabled() ? request : request.copyWithoutData()) + ", channel: " + channel.getLocalAddress() + + " -> " + channel.getRemoteAddress(); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/CloseTimerTask.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/CloseTimerTask.java index c4c8dc7531..a1c850f619 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/CloseTimerTask.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/CloseTimerTask.java @@ -17,16 +17,19 @@ package org.apache.dubbo.remoting.exchange.support.header; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_RESPONSE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; + /** * CloseTimerTask */ public class CloseTimerTask extends AbstractTimerTask { - private static final Logger logger = LoggerFactory.getLogger(CloseTimerTask.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CloseTimerTask.class); private final int idleTimeout; @@ -43,12 +46,12 @@ public class CloseTimerTask extends AbstractTimerTask { Long now = now(); // check ping & pong at server if ((lastRead != null && now - lastRead > idleTimeout) - || (lastWrite != null && now - lastWrite > idleTimeout)) { - logger.warn("Close channel " + channel + ", because idleCheck timeout: " + idleTimeout + "ms"); + || (lastWrite != null && now - lastWrite > idleTimeout)) { + logger.warn(PROTOCOL_FAILED_RESPONSE, "", "", "Close channel " + channel + ", because idleCheck timeout: " + idleTimeout + "ms"); channel.close(); } } catch (Throwable t) { - logger.warn("Exception when close remote channel " + channel.getRemoteAddress(), t); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", "Exception when close remote channel " + channel.getRemoteAddress(), t); } } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java index f41e6faea1..787130ed56 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java @@ -18,7 +18,7 @@ package org.apache.dubbo.remoting.exchange.support.header; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; @@ -35,13 +35,14 @@ import java.util.concurrent.ExecutorService; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; /** * ExchangeReceiver */ final class HeaderExchangeChannel implements ExchangeChannel { - private static final Logger logger = LoggerFactory.getLogger(HeaderExchangeChannel.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(HeaderExchangeChannel.class); private static final String CHANNEL_KEY = HeaderExchangeChannel.class.getName() + ".CHANNEL"; @@ -93,8 +94,8 @@ final class HeaderExchangeChannel implements ExchangeChannel { throw new RemotingException(this.getLocalAddress(), null, "Failed to send message " + message + ", cause: The channel " + this + " is closed!"); } if (message instanceof Request - || message instanceof Response - || message instanceof String) { + || message instanceof Response + || message instanceof String) { channel.send(message, sent); } else { Request request = new Request(); @@ -156,7 +157,7 @@ final class HeaderExchangeChannel implements ExchangeChannel { DefaultFuture.closeChannel(channel); channel.close(); } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } @@ -169,11 +170,11 @@ final class HeaderExchangeChannel implements ExchangeChannel { if (timeout > 0) { long start = System.currentTimeMillis(); while (DefaultFuture.hasFuture(channel) - && System.currentTimeMillis() - start < timeout) { + && System.currentTimeMillis() - start < timeout) { try { Thread.sleep(10); } catch (InterruptedException e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java index f6c348b2da..ef0420f8f4 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.exchange.support.header; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; @@ -38,6 +38,8 @@ import java.net.InetSocketAddress; import java.util.concurrent.CompletionStage; import static org.apache.dubbo.common.constants.CommonConstants.READONLY_EVENT; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RESPONSE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNSUPPORTED_MESSAGE; /** @@ -45,7 +47,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.READONLY_EVENT; */ public class HeaderExchangeHandler implements ChannelHandlerDelegate { - protected static final Logger logger = LoggerFactory.getLogger(HeaderExchangeHandler.class); + protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(HeaderExchangeHandler.class); private final ExchangeHandler handler; @@ -66,8 +68,8 @@ public class HeaderExchangeHandler implements ChannelHandlerDelegate { InetSocketAddress address = channel.getRemoteAddress(); URL url = channel.getUrl(); return url.getPort() == address.getPort() && - NetUtils.filterLocalHost(url.getIp()) - .equals(NetUtils.filterLocalHost(address.getAddress().getHostAddress())); + NetUtils.filterLocalHost(url.getIp()) + .equals(NetUtils.filterLocalHost(address.getAddress().getHostAddress())); } void handlerEvent(Channel channel, Request req) throws RemotingException { @@ -110,7 +112,7 @@ public class HeaderExchangeHandler implements ChannelHandlerDelegate { } channel.send(res); } catch (RemotingException e) { - logger.warn("Send result to consumer failed, channel is " + channel + ", msg is " + e); + logger.warn(TRANSPORT_FAILED_RESPONSE, "", "", "Send result to consumer failed, channel is " + channel + ", msg is " + e); } }); } catch (Throwable e) { @@ -166,7 +168,7 @@ public class HeaderExchangeHandler implements ChannelHandlerDelegate { throw (RemotingException) exception; } else { throw new RemotingException(channel.getLocalAddress(), channel.getRemoteAddress(), - exception.getMessage(), exception); + exception.getMessage(), exception); } } } @@ -191,7 +193,7 @@ public class HeaderExchangeHandler implements ChannelHandlerDelegate { } else if (message instanceof String) { if (isClientSide(channel)) { Exception e = new Exception("Dubbo client can not supported string message: " + message + " in channel: " + channel + ", url: " + channel.getUrl()); - logger.error(e.getMessage(), e); + logger.error(TRANSPORT_UNSUPPORTED_MESSAGE, "", "", e.getMessage(), e); } else { String echo = handler.telnet(channel, (String) message); if (StringUtils.isNotEmpty(echo)) { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java index 37214cf29f..aab03f6f44 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java @@ -18,7 +18,7 @@ package org.apache.dubbo.remoting.exchange.support.header; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.GlobalResourceInitializer; import org.apache.dubbo.common.timer.HashedWheelTimer; @@ -44,6 +44,9 @@ import java.util.concurrent.atomic.AtomicBoolean; import static java.util.Collections.unmodifiableCollection; import static org.apache.dubbo.common.constants.CommonConstants.READONLY_EVENT; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RESPONSE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNEXPECTED_EXCEPTION; import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK; import static org.apache.dubbo.remoting.Constants.LEAST_HEARTBEAT_DURATION; import static org.apache.dubbo.remoting.Constants.TICKS_PER_WHEEL; @@ -55,7 +58,7 @@ import static org.apache.dubbo.remoting.utils.UrlUtils.getIdleTimeout; */ public class HeaderExchangeServer implements ExchangeServer { - protected final Logger logger = LoggerFactory.getLogger(getClass()); + protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final RemotingServer server; @@ -111,7 +114,7 @@ public class HeaderExchangeServer implements ExchangeServer { try { Thread.sleep(10); } catch (InterruptedException e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } } @@ -141,7 +144,7 @@ public class HeaderExchangeServer implements ExchangeServer { // ignore ClosedChannelException which means the connection has been closed. continue; } - logger.warn("send cannot write message error.", e); + logger.warn(TRANSPORT_FAILED_RESPONSE, "", "", "send cannot write message error.", e); } } } @@ -218,7 +221,7 @@ public class HeaderExchangeServer implements ExchangeServer { startIdleCheckTask(url); } } catch (Throwable t) { - logger.error(t.getMessage(), t); + logger.error(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", t.getMessage(), t); } } @@ -232,7 +235,7 @@ public class HeaderExchangeServer implements ExchangeServer { public void send(Object message) throws RemotingException { if (closed.get()) { throw new RemotingException(this.getLocalAddress(), null, "Failed to send message " + message - + ", cause: The server " + getLocalAddress() + " is closed!"); + + ", cause: The server " + getLocalAddress() + " is closed!"); } server.send(message); } @@ -241,7 +244,7 @@ public class HeaderExchangeServer implements ExchangeServer { public void send(Object message, boolean sent) throws RemotingException { if (closed.get()) { throw new RemotingException(this.getLocalAddress(), null, "Failed to send message " + message - + ", cause: The server " + getLocalAddress() + " is closed!"); + + ", cause: The server " + getLocalAddress() + " is closed!"); } server.send(message, sent); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatTimerTask.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatTimerTask.java index f814c6c593..79e2efe876 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatTimerTask.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatTimerTask.java @@ -18,19 +18,20 @@ package org.apache.dubbo.remoting.exchange.support.header; import org.apache.dubbo.common.Version; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.exchange.Request; import static org.apache.dubbo.common.constants.CommonConstants.HEARTBEAT_EVENT; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RESPONSE; /** * HeartbeatTimerTask */ public class HeartbeatTimerTask extends AbstractTimerTask { - private static final Logger logger = LoggerFactory.getLogger(HeartbeatTimerTask.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(HeartbeatTimerTask.class); private final int heartbeat; @@ -46,7 +47,7 @@ public class HeartbeatTimerTask extends AbstractTimerTask { Long lastWrite = lastWrite(channel); Long now = now(); if ((lastRead != null && now - lastRead > heartbeat) - || (lastWrite != null && now - lastWrite > heartbeat)) { + || (lastWrite != null && now - lastWrite > heartbeat)) { Request req = new Request(); req.setVersion(Version.getProtocolVersion()); req.setTwoWay(true); @@ -54,12 +55,12 @@ public class HeartbeatTimerTask extends AbstractTimerTask { channel.send(req); if (logger.isDebugEnabled()) { logger.debug("Send heartbeat to remote channel " + channel.getRemoteAddress() - + ", cause: The channel has no data-transmission exceeds a heartbeat period: " - + heartbeat + "ms"); + + ", cause: The channel has no data-transmission exceeds a heartbeat period: " + + heartbeat + "ms"); } } } catch (Throwable t) { - logger.warn("Exception when heartbeat to remote channel " + channel.getRemoteAddress(), t); + logger.warn(TRANSPORT_FAILED_RESPONSE, "", "", "Exception when heartbeat to remote channel " + channel.getRemoteAddress(), t); } } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTask.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTask.java index 5fd8c90b95..9306f3aaf1 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTask.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTask.java @@ -17,17 +17,20 @@ package org.apache.dubbo.remoting.exchange.support.header; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Client; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RECONNECT; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNEXPECTED_EXCEPTION; + /** * ReconnectTimerTask */ public class ReconnectTimerTask extends AbstractTimerTask { - private static final Logger logger = LoggerFactory.getLogger(ReconnectTimerTask.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReconnectTimerTask.class); private final int idleTimeout; @@ -48,20 +51,20 @@ public class ReconnectTimerTask extends AbstractTimerTask { logger.info("Initial connection to " + channel); ((Client) channel).reconnect(); } catch (Exception e) { - logger.error("Fail to connect to " + channel, e); + logger.error(TRANSPORT_FAILED_RECONNECT, "", "", "Fail to connect to" + channel, e); } - // check pong at client + // check pong at client } else if (lastRead != null && now - lastRead > idleTimeout) { - logger.warn("Reconnect to channel " + channel + ", because heartbeat read idle time out: " - + idleTimeout + "ms"); + logger.warn(TRANSPORT_FAILED_RECONNECT, "", "", "Reconnect to channel " + channel + ", because heartbeat read idle time out: " + + idleTimeout + "ms"); try { ((Client) channel).reconnect(); } catch (Exception e) { - logger.error(channel + "reconnect failed during idle time.", e); + logger.error(TRANSPORT_FAILED_RECONNECT, "", "", channel + "reconnect failed during idle time.", e); } } } catch (Throwable t) { - logger.warn("Exception when reconnect to remote channel " + channel.getRemoteAddress(), t); + logger.warn(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", "Exception when reconnect to remote channel " + channel.getRemoteAddress(), t); } } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java index 6ecfbf2ae0..9cfd979e17 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.telnet.codec; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; @@ -33,6 +33,7 @@ import java.util.Arrays; import java.util.LinkedList; import java.util.List; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNSUPPORTED_CHARSET; import static org.apache.dubbo.remoting.Constants.CHARSET_KEY; import static org.apache.dubbo.remoting.Constants.DEFAULT_CHARSET; @@ -41,7 +42,7 @@ import static org.apache.dubbo.remoting.Constants.DEFAULT_CHARSET; */ public class TelnetCodec extends TransportCodec { - private static final Logger logger = LoggerFactory.getLogger(TelnetCodec.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TelnetCodec.class); private static final String HISTORY_LIST_KEY = "telnet.history.list"; @@ -52,13 +53,13 @@ public class TelnetCodec extends TransportCodec { private static final byte[] DOWN = new byte[]{27, 91, 66}; private static final List ENTER = Arrays.asList( - new byte[]{'\r', '\n'} /* Windows Enter */, - new byte[]{'\n'} /* Linux Enter */); + new byte[]{'\r', '\n'} /* Windows Enter */, + new byte[]{'\n'} /* Linux Enter */); private static final List EXIT = Arrays.asList( - new byte[]{3} /* Windows Ctrl+C */, - new byte[]{-1, -12, -1, -3, 6} /* Linux Ctrl+C */, - new byte[]{-1, -19, -1, -3, 6} /* Linux Pause */); + new byte[]{3} /* Windows Ctrl+C */, + new byte[]{-1, -12, -1, -3, 6} /* Linux Ctrl+C */, + new byte[]{-1, -19, -1, -3, 6} /* Linux Pause */); private static Charset getCharset(Channel channel) { if (channel != null) { @@ -67,7 +68,7 @@ public class TelnetCodec extends TransportCodec { try { return Charset.forName((String) attribute); } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(TRANSPORT_UNSUPPORTED_CHARSET, "", "", t.getMessage(), t); } } else if (attribute instanceof Charset) { return (Charset) attribute; @@ -79,7 +80,7 @@ public class TelnetCodec extends TransportCodec { try { return Charset.forName(parameter); } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(TRANSPORT_UNSUPPORTED_CHARSET, "", "", t.getMessage(), t); } } } @@ -87,7 +88,7 @@ public class TelnetCodec extends TransportCodec { try { return Charset.forName(DEFAULT_CHARSET); } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(TRANSPORT_UNSUPPORTED_CHARSET, "", "", t.getMessage(), t); } return Charset.defaultCharset(); } @@ -115,7 +116,7 @@ public class TelnetCodec extends TransportCodec { i = i + 2; } } else if (b == -1 && i < message.length - 2 - && (message[i + 1] == -3 || message[i + 1] == -5)) { // handshake + && (message[i + 1] == -3 || message[i + 1] == -5)) { // handshake i = i + 2; } else { copy[index++] = message[i]; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java index f265a71246..a2cba73bc4 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java @@ -18,7 +18,7 @@ package org.apache.dubbo.remoting.transport; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.common.utils.NetUtils; @@ -38,6 +38,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CLIENT_T import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.LAZY_CONNECT_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CONNECT_PROVIDER; /** * AbstractClient @@ -46,7 +48,7 @@ public abstract class AbstractClient extends AbstractEndpoint implements Client protected static final String CLIENT_THREAD_POOL_NAME = "DubboClientHandler"; - private static final Logger logger = LoggerFactory.getLogger(AbstractClient.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractClient.class); private final Lock connectLock = new ReentrantLock(); @@ -80,7 +82,7 @@ public abstract class AbstractClient extends AbstractEndpoint implements Client // If lazy connect client fails to establish a connection, the client instance will still be created, // and the reconnection will be initiated by ReconnectTask, so there is no need to throw an exception if (url.getParameter(LAZY_CONNECT_KEY, false)) { - logger.warn("Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + + logger.warn(TRANSPORT_FAILED_CONNECT_PROVIDER, "", "", "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + " connect to the server " + getRemoteAddress() + " (the connection request is initiated by lazy connect client, ignore and retry later!), cause: " + t.getMessage(), t); @@ -91,7 +93,7 @@ public abstract class AbstractClient extends AbstractEndpoint implements Client close(); throw t; } else { - logger.warn("Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + logger.warn(TRANSPORT_FAILED_CONNECT_PROVIDER, "", "", "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + " connect to the server " + getRemoteAddress() + " (check == false, ignore and retry later!), cause: " + t.getMessage(), t); } } catch (Throwable t) { @@ -209,7 +211,7 @@ public abstract class AbstractClient extends AbstractEndpoint implements Client } if (isClosed() || isClosing()) { - logger.warn("No need to connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " + logger.warn(TRANSPORT_FAILED_CONNECT_PROVIDER, "", "", "No need to connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + ", cause: client status is closed or closing."); return; } @@ -251,12 +253,12 @@ public abstract class AbstractClient extends AbstractEndpoint implements Client channel.close(); } } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { doDisConnect(); } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } finally { connectLock.unlock(); @@ -277,33 +279,33 @@ public abstract class AbstractClient extends AbstractEndpoint implements Client @Override public void close() { if (isClosed()) { - logger.warn("No need to close connection to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + ", cause: the client status is closed."); + logger.warn(TRANSPORT_FAILED_CONNECT_PROVIDER, "", "", "No need to close connection to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + ", cause: the client status is closed."); return; } connectLock.lock(); try { if (isClosed()) { - logger.warn("No need to close connection to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + ", cause: the client status is closed."); + logger.warn(TRANSPORT_FAILED_CONNECT_PROVIDER, "", "", "No need to close connection to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + ", cause: the client status is closed."); return; } try { super.close(); } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { disconnect(); } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { doClose(); } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } finally { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java index 93061dbffd..aabf6ee3b0 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.transport; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.utils.NetUtils; @@ -33,13 +33,14 @@ import java.io.IOException; import java.net.InetSocketAddress; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_EXCEED_PAYLOAD_LIMIT; /** * AbstractCodec */ public abstract class AbstractCodec implements Codec2, ScopeModelAware { - private static final Logger logger = LoggerFactory.getLogger(AbstractCodec.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractCodec.class); private static final String CLIENT_SIDE = "client"; @@ -56,8 +57,8 @@ public abstract class AbstractCodec implements Codec2, ScopeModelAware { boolean overPayload = isOverPayload(payload, size); if (overPayload) { ExceedPayloadLimitException e = new ExceedPayloadLimitException( - "Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); - logger.error(e); + "Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); + logger.error(TRANSPORT_EXCEED_PAYLOAD_LIMIT, "", "", e.getMessage(), e); throw e; } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java index 4e0af746d9..ed4004bdd1 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java @@ -18,7 +18,7 @@ package org.apache.dubbo.remoting.transport; import org.apache.dubbo.common.Resetable; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.ChannelHandler; @@ -28,6 +28,7 @@ import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.transport.codec.CodecAdapter; import org.apache.dubbo.rpc.model.FrameworkModel; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNEXPECTED_EXCEPTION; import static org.apache.dubbo.rpc.model.ScopeModelUtil.getFrameworkModel; /** @@ -35,7 +36,7 @@ import static org.apache.dubbo.rpc.model.ScopeModelUtil.getFrameworkModel; */ public abstract class AbstractEndpoint extends AbstractPeer implements Resetable { - private static final Logger logger = LoggerFactory.getLogger(AbstractEndpoint.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractEndpoint.class); private Codec2 codec; @@ -56,10 +57,10 @@ public abstract class AbstractEndpoint extends AbstractPeer implements Resetable FrameworkModel frameworkModel = getFrameworkModel(url.getScopeModel()); if (frameworkModel.getExtensionLoader(Codec2.class).hasExtension(codecName)) { return frameworkModel.getExtensionLoader(Codec2.class).getExtension(codecName); - } else if(frameworkModel.getExtensionLoader(Codec.class).hasExtension(codecName)){ + } else if (frameworkModel.getExtensionLoader(Codec.class).hasExtension(codecName)) { return new CodecAdapter(frameworkModel.getExtensionLoader(Codec.class) .getExtension(codecName)); - }else { + } else { return frameworkModel.getExtensionLoader(Codec2.class).getExtension("default"); } } @@ -79,7 +80,7 @@ public abstract class AbstractEndpoint extends AbstractPeer implements Resetable } } } catch (Throwable t) { - logger.error(t.getMessage(), t); + logger.error(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", t.getMessage(), t); } try { @@ -87,7 +88,7 @@ public abstract class AbstractEndpoint extends AbstractPeer implements Resetable this.codec = getChannelCodec(url); } } catch (Throwable t) { - logger.error(t.getMessage(), t); + logger.error(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", t.getMessage(), t); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java index 9ed96920a0..0f434e3c27 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.transport; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.common.utils.ConcurrentHashSet; @@ -36,6 +36,7 @@ import java.util.concurrent.ExecutorService; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNEXPECTED_EXCEPTION; import static org.apache.dubbo.remoting.Constants.ACCEPTS_KEY; import static org.apache.dubbo.remoting.Constants.DEFAULT_ACCEPTS; @@ -45,7 +46,7 @@ import static org.apache.dubbo.remoting.Constants.DEFAULT_ACCEPTS; public abstract class AbstractServer extends AbstractEndpoint implements RemotingServer { protected static final String SERVER_THREAD_POOL_NAME = "DubboServerHandler"; - private static final Logger logger = LoggerFactory.getLogger(AbstractServer.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractServer.class); private Set executors = new ConcurrentHashSet<>(); private InetSocketAddress localAddress; private InetSocketAddress bindAddress; @@ -72,7 +73,7 @@ public abstract class AbstractServer extends AbstractEndpoint implements Remotin } } catch (Throwable t) { throw new RemotingException(url.toInetSocketAddress(), null, "Failed to bind " + getClass().getSimpleName() - + " on " + bindAddress + ", cause: " + t.getMessage(), t); + + " on " + bindAddress + ", cause: " + t.getMessage(), t); } executors.add(executorRepository.createExecutorIfAbsent(url)); } @@ -95,7 +96,7 @@ public abstract class AbstractServer extends AbstractEndpoint implements Remotin } } } catch (Throwable t) { - logger.error(t.getMessage(), t); + logger.error(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", t.getMessage(), t); } ExecutorService executor = executorRepository.createExecutorIfAbsent(url); @@ -127,13 +128,13 @@ public abstract class AbstractServer extends AbstractEndpoint implements Remotin try { super.close(); } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", e.getMessage(), e); } try { doClose(); } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", e.getMessage(), e); } } @@ -162,13 +163,13 @@ public abstract class AbstractServer extends AbstractEndpoint implements Remotin public void connected(Channel ch) throws RemotingException { // If the server has entered the shutdown process, reject any new connection if (this.isClosing() || this.isClosed()) { - logger.warn("Close new channel " + ch + ", cause: server is closing or has been closed. For example, receive a new connect request while in shutdown process."); + logger.warn(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", "Close new channel " + ch + ", cause: server is closing or has been closed. For example, receive a new connect request while in shutdown process."); ch.close(); return; } if (accepts > 0 && getChannels().size() > accepts) { - logger.error("Close channel " + ch + ", cause: The server " + ch.getLocalAddress() + " connections greater than max config " + accepts); + logger.error(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", "Close channel " + ch + ", cause: The server " + ch.getLocalAddress() + " connections greater than max config " + accepts); ch.close(); return; } @@ -179,7 +180,7 @@ public abstract class AbstractServer extends AbstractEndpoint implements Remotin public void disconnected(Channel ch) throws RemotingException { Collection channels = getChannels(); if (channels.isEmpty()) { - logger.warn("All clients has disconnected from " + ch.getLocalAddress() + ". You can graceful shutdown now."); + logger.warn(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", "All clients has disconnected from " + ch.getLocalAddress() + ". You can graceful shutdown now."); } super.disconnected(ch); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcher.java index f8b04eeba6..f425eb3ce0 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcher.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.remoting.transport; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.remoting.Channel; @@ -26,12 +26,14 @@ import java.util.Arrays; import java.util.Collection; import java.util.concurrent.CopyOnWriteArraySet; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNEXPECTED_EXCEPTION; + /** * ChannelListenerDispatcher */ public class ChannelHandlerDispatcher implements ChannelHandler { - private static final Logger logger = LoggerFactory.getLogger(ChannelHandlerDispatcher.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ChannelHandlerDispatcher.class); private final Collection channelHandlers = new CopyOnWriteArraySet<>(); @@ -68,7 +70,7 @@ public class ChannelHandlerDispatcher implements ChannelHandler { try { listener.connected(channel); } catch (Throwable t) { - logger.error(t.getMessage(), t); + logger.error(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", t.getMessage(), t); } } } @@ -79,7 +81,7 @@ public class ChannelHandlerDispatcher implements ChannelHandler { try { listener.disconnected(channel); } catch (Throwable t) { - logger.error(t.getMessage(), t); + logger.error(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", t.getMessage(), t); } } } @@ -90,7 +92,7 @@ public class ChannelHandlerDispatcher implements ChannelHandler { try { listener.sent(channel, message); } catch (Throwable t) { - logger.error(t.getMessage(), t); + logger.error(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", t.getMessage(), t); } } } @@ -101,7 +103,7 @@ public class ChannelHandlerDispatcher implements ChannelHandler { try { listener.received(channel, message); } catch (Throwable t) { - logger.error(t.getMessage(), t); + logger.error(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", t.getMessage(), t); } } } @@ -112,7 +114,7 @@ public class ChannelHandlerDispatcher implements ChannelHandler { try { listener.caught(channel, exception); } catch (Throwable t) { - logger.error(t.getMessage(), t); + logger.error(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", t.getMessage(), t); } } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java index bdbbb57707..0c7861e34a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java @@ -19,7 +19,7 @@ package org.apache.dubbo.remoting.transport; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -40,9 +40,10 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import static org.apache.dubbo.common.BaseServiceMetadata.keyWithoutGroup; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_SERIALIZATION; public class CodecSupport { - private static final Logger logger = LoggerFactory.getLogger(CodecSupport.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CodecSupport.class); private static Map ID_SERIALIZATION_MAP = new HashMap(); private static Map ID_SERIALIZATIONNAME_MAP = new HashMap(); private static Map SERIALIZATIONNAME_ID_MAP = new HashMap(); @@ -58,10 +59,10 @@ public class CodecSupport { Serialization serialization = extensionLoader.getExtension(name); byte idByte = serialization.getContentTypeId(); if (ID_SERIALIZATION_MAP.containsKey(idByte)) { - logger.error("Serialization extension " + serialization.getClass().getName() - + " has duplicate id to Serialization extension " - + ID_SERIALIZATION_MAP.get(idByte).getClass().getName() - + ", ignore this Serialization extension"); + logger.error(TRANSPORT_FAILED_SERIALIZATION, "", "", "Serialization extension " + serialization.getClass().getName() + + " has duplicate id to Serialization extension " + + ID_SERIALIZATION_MAP.get(idByte).getClass().getName() + + ", ignore this Serialization extension"); continue; } ID_SERIALIZATION_MAP.put(idByte, serialization); @@ -117,7 +118,7 @@ public class CodecSupport { nullBytes = baos.toByteArray(); baos.close(); } catch (Exception e) { - logger.warn("Serialization extension " + s.getClass().getName() + " not support serializing null object, return an empty bytes instead."); + logger.warn(TRANSPORT_FAILED_SERIALIZATION, "", "", "Serialization extension " + s.getClass().getName() + " not support serializing null object, return an empty bytes instead."); } return nullBytes; }); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/DecodeHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/DecodeHandler.java index c34c02341c..11b93b8494 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/DecodeHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/DecodeHandler.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.transport; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; @@ -26,9 +26,11 @@ import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_DECODE; + public class DecodeHandler extends AbstractChannelHandlerDelegate { - private static final Logger log = LoggerFactory.getLogger(DecodeHandler.class); + private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(DecodeHandler.class); public DecodeHandler(ChannelHandler handler) { super(handler); @@ -63,7 +65,7 @@ public class DecodeHandler extends AbstractChannelHandlerDelegate { } } catch (Throwable e) { if (log.isWarnEnabled()) { - log.warn("Call Decodeable.decode failed: " + e.getMessage(), e); + log.warn(TRANSPORT_FAILED_DECODE, "", "", "Call Decodeable.decode failed: " + e.getMessage(), e); } } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/MultiMessageHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/MultiMessageHandler.java index 0dad522ab5..7d65fdd757 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/MultiMessageHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/MultiMessageHandler.java @@ -16,19 +16,21 @@ */ package org.apache.dubbo.remoting.transport; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.support.MultiMessage; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNEXPECTED_EXCEPTION; + /** * @see MultiMessage */ public class MultiMessageHandler extends AbstractChannelHandlerDelegate { - protected static final Logger logger = LoggerFactory.getLogger(MultiMessageHandler.class); + protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MultiMessageHandler.class); public MultiMessageHandler(ChannelHandler handler) { super(handler); @@ -43,11 +45,11 @@ public class MultiMessageHandler extends AbstractChannelHandlerDelegate { try { handler.received(channel, obj); } catch (Throwable t) { - logger.error("MultiMessageHandler received fail.", t); + logger.error(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", "MultiMessageHandler received fail.", t); try { handler.caught(channel, t); } catch (Throwable t1) { - logger.error("MultiMessageHandler caught fail.", t1); + logger.error(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", "MultiMessageHandler caught fail.", t1); } } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java index 64a41253d0..9af07d3b38 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java @@ -16,14 +16,16 @@ */ package org.apache.dubbo.remoting.transport.dispatcher; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadlocal.InternalThreadLocal; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNEXPECTED_EXCEPTION; + public class ChannelEventRunnable implements Runnable { - private static final Logger logger = LoggerFactory.getLogger(ChannelEventRunnable.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ChannelEventRunnable.class); private final ChannelHandler handler; private final Channel channel; @@ -58,43 +60,43 @@ public class ChannelEventRunnable implements Runnable { try { handler.received(channel, message); } catch (Exception e) { - logger.warn("ChannelEventRunnable handle " + state + " operation error, channel is " + channel - + ", message is " + message, e); + logger.warn(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", "ChannelEventRunnable handle " + state + " operation error, channel is " + channel + + ", message is " + message, e); } } else { switch (state) { - case CONNECTED: - try { - handler.connected(channel); - } catch (Exception e) { - logger.warn("ChannelEventRunnable handle " + state + " operation error, channel is " + channel, e); - } - break; - case DISCONNECTED: - try { - handler.disconnected(channel); - } catch (Exception e) { - logger.warn("ChannelEventRunnable handle " + state + " operation error, channel is " + channel, e); - } - break; - case SENT: - try { - handler.sent(channel, message); - } catch (Exception e) { - logger.warn("ChannelEventRunnable handle " + state + " operation error, channel is " + channel + case CONNECTED: + try { + handler.connected(channel); + } catch (Exception e) { + logger.warn(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", "ChannelEventRunnable handle " + state + " operation error, channel is " + channel, e); + } + break; + case DISCONNECTED: + try { + handler.disconnected(channel); + } catch (Exception e) { + logger.warn(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", "ChannelEventRunnable handle " + state + " operation error, channel is " + channel, e); + } + break; + case SENT: + try { + handler.sent(channel, message); + } catch (Exception e) { + logger.warn(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", "ChannelEventRunnable handle " + state + " operation error, channel is " + channel + ", message is " + message, e); - } - break; - case CAUGHT: - try { - handler.caught(channel, exception); - } catch (Exception e) { - logger.warn("ChannelEventRunnable handle " + state + " operation error, channel is " + channel + } + break; + case CAUGHT: + try { + handler.caught(channel, exception); + } catch (Exception e) { + logger.warn(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", "ChannelEventRunnable handle " + state + " operation error, channel is " + channel + ", message is: " + message + ", exception is " + exception, e); - } - break; - default: - logger.warn("unknown state: " + state + ", message is " + message); + } + break; + default: + logger.warn(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", "unknown state: " + state + ", message is " + message); } } InternalThreadLocal.removeAll(); @@ -102,8 +104,6 @@ public class ChannelEventRunnable implements Runnable { /** * ChannelState - * - * */ public enum ChannelState { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java index 00d41742f5..325f53625b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.transport.dispatcher; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.GlobalResourcesRepository; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; @@ -36,7 +36,7 @@ import java.util.concurrent.ExecutorService; public class WrappedChannelHandler implements ChannelHandlerDelegate { - protected static final Logger logger = LoggerFactory.getLogger(WrappedChannelHandler.class); + protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(WrappedChannelHandler.class); protected final ChannelHandler handler; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java index cca7a93cbb..77fb6bb9ba 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java @@ -36,6 +36,7 @@ import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREAD_NAME; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_CONNECTION_LIMIT_EXCEED; import static org.apache.dubbo.remoting.Constants.CONNECT_QUEUE_CAPACITY; import static org.apache.dubbo.remoting.Constants.CONNECT_QUEUE_WARNING_SIZE; import static org.apache.dubbo.remoting.Constants.DEFAULT_CONNECT_QUEUE_WARNING_SIZE; @@ -49,10 +50,10 @@ public class ConnectionOrderedChannelHandler extends WrappedChannelHandler { super(handler, url); String threadName = url.getParameter(THREAD_NAME_KEY, DEFAULT_THREAD_NAME); connectionExecutor = new ThreadPoolExecutor(1, 1, - 0L, TimeUnit.MILLISECONDS, + 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(url.getPositiveParameter(CONNECT_QUEUE_CAPACITY, Integer.MAX_VALUE)), - new NamedThreadFactory(threadName, true), - new AbortPolicyWithReport(threadName, url) + new NamedThreadFactory(threadName, true), + new AbortPolicyWithReport(threadName, url) ); // FIXME There's no place to release connectionExecutor! queueWarningLimit = url.getParameter(CONNECT_QUEUE_WARNING_SIZE, DEFAULT_CONNECT_QUEUE_WARNING_SIZE); } @@ -103,7 +104,7 @@ public class ConnectionOrderedChannelHandler extends WrappedChannelHandler { private void checkQueueLength() { if (connectionExecutor.getQueue().size() > queueWarningLimit) { - logger.warn(new IllegalThreadStateException("connectionordered channel handler queue size: " + connectionExecutor.getQueue().size() + " exceed the warning limit number :" + queueWarningLimit)); + logger.warn(TRANSPORT_CONNECTION_LIMIT_EXCEED, "", "", "connectionordered channel handler queue size: " + connectionExecutor.getQueue().size() + " exceed the warning limit number :" + queueWarningLimit); } } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperClient.java index 6dec2bd78b..5e0fa3b53c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperClient.java @@ -18,7 +18,7 @@ package org.apache.dubbo.remoting.zookeeper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigItem; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashSet; @@ -29,9 +29,11 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.Executor; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION; + public abstract class AbstractZookeeperClient implements ZookeeperClient { - protected static final Logger logger = LoggerFactory.getLogger(AbstractZookeeperClient.class); + protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractZookeeperClient.class); // may hang up to wait name resolution up to 10s protected int DEFAULT_CONNECTION_TIMEOUT_MS = 30 * 1000; @@ -159,7 +161,7 @@ public abstract class AbstractZookeeperClient clazz){ + public JettyLoggerAdapter(Class clazz) { this(clazz.getName()); } public JettyLoggerAdapter(String name) { this.name = name; - this.logger = LoggerFactory.getLogger(name); + this.logger = LoggerFactory.getErrorTypeAwareLogger(name); } @Override @@ -56,42 +59,42 @@ public class JettyLoggerAdapter extends AbstractLogger { @Override public void warn(String msg, Object... objects) { - if (logger.isWarnEnabled()){ - logger.warn(this.format(msg, objects)); + if (logger.isWarnEnabled()) { + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", this.format(msg, objects)); } } @Override public void warn(Throwable throwable) { - if (logger.isWarnEnabled()){ - logger.warn(throwable); + if (logger.isWarnEnabled()) { + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", throwable.getMessage(), throwable); } } @Override public void warn(String msg, Throwable throwable) { - if (logger.isWarnEnabled()){ - logger.warn(msg, throwable); + if (logger.isWarnEnabled()) { + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", msg, throwable); } } @Override public void info(String msg, Object... objects) { - if (logger.isInfoEnabled()){ + if (logger.isInfoEnabled()) { logger.info(this.format(msg, objects)); } } @Override public void info(Throwable throwable) { - if (logger.isInfoEnabled()){ + if (logger.isInfoEnabled()) { logger.info(throwable); } } @Override public void info(String msg, Throwable throwable) { - if (logger.isInfoEnabled()){ + if (logger.isInfoEnabled()) { logger.info(msg, throwable); } } @@ -108,29 +111,29 @@ public class JettyLoggerAdapter extends AbstractLogger { @Override public void debug(String msg, Object... objects) { - if (debugEnabled && logger.isDebugEnabled()){ + if (debugEnabled && logger.isDebugEnabled()) { logger.debug(this.format(msg, objects)); } } @Override public void debug(Throwable throwable) { - if (debugEnabled && logger.isDebugEnabled()){ + if (debugEnabled && logger.isDebugEnabled()) { logger.debug(throwable); } } @Override public void debug(String msg, Throwable throwable) { - if (debugEnabled && logger.isDebugEnabled()){ + if (debugEnabled && logger.isDebugEnabled()) { logger.debug(msg, throwable); } } @Override public void ignore(Throwable throwable) { - if (logger.isWarnEnabled()){ - logger.warn("IGNORED EXCEPTION ", throwable); + if (logger.isWarnEnabled()) { + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "IGNORED EXCEPTION ", throwable); } } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java index 2d0b8a121b..dfbba2948e 100755 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.http.tomcat; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.servlet.DispatcherServlet; @@ -33,11 +33,12 @@ import java.io.File; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_STOP_HTTP_SERVER; import static org.apache.dubbo.remoting.Constants.ACCEPTS_KEY; public class TomcatHttpServer extends AbstractHttpServer { - private static final Logger logger = LoggerFactory.getLogger(TomcatHttpServer.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TomcatHttpServer.class); private final Tomcat tomcat; @@ -91,7 +92,7 @@ public class TomcatHttpServer extends AbstractHttpServer { // close port by destroy() tomcat.destroy(); } catch (Exception e) { - logger.warn(e.getMessage(), e); + logger.warn(COMMON_FAILED_STOP_HTTP_SERVER, "", "", e.getMessage(), e); } } } diff --git a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyLoggerAdapterTest.java b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyLoggerAdapterTest.java index e26034213c..948bea258a 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyLoggerAdapterTest.java +++ b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyLoggerAdapterTest.java @@ -18,6 +18,7 @@ package org.apache.dubbo.remoting.http.jetty; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.support.FailsafeErrorTypeAwareLogger; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Constants; @@ -70,7 +71,7 @@ public class JettyLoggerAdapterTest { Field loggerField = clazz.getDeclaredField("logger"); loggerField.setAccessible(true); - loggerField.set(jettyLoggerAdapter, successLogger); + loggerField.set(jettyLoggerAdapter, new FailsafeErrorTypeAwareLogger(successLogger)); jettyLoggerAdapter.setDebugEnabled(true); when(successLogger.isDebugEnabled()).thenReturn(true); diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyChannel.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyChannel.java index c13bc2905c..ee51ee6050 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyChannel.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyChannel.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.transport.netty; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; @@ -33,13 +33,14 @@ import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; /** * NettyChannel. */ final class NettyChannel extends AbstractChannel { - private static final Logger logger = LoggerFactory.getLogger(NettyChannel.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NettyChannel.class); private static final ConcurrentMap CHANNEL_MAP = new ConcurrentHashMap(); @@ -115,7 +116,7 @@ final class NettyChannel extends AbstractChannel { if (!success) { throw new RemotingException(this, "Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to " + getRemoteAddress() - + "in timeout(" + timeout + "ms) limit"); + + "in timeout(" + timeout + "ms) limit"); } } @@ -124,17 +125,17 @@ final class NettyChannel extends AbstractChannel { try { super.close(); } catch (Exception e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { removeChannelIfDisconnected(channel); } catch (Exception e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { attributes.clear(); } catch (Exception e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { if (logger.isInfoEnabled()) { @@ -142,7 +143,7 @@ final class NettyChannel extends AbstractChannel { } channel.close(); } catch (Exception e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java index f5e0dc6cc2..3f907959be 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java @@ -41,6 +41,7 @@ import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_CLIENT_CONNECT_TIMEOUT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CONNECT_PROVIDER; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_DISCONNECT_PROVIDER; /** * NettyClient. @@ -52,8 +53,8 @@ public class NettyClient extends AbstractClient { // ChannelFactory's closure has a DirectMemory leak, using static to avoid // https://issues.jboss.org/browse/NETTY-424 private static final ChannelFactory CHANNEL_FACTORY = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientBoss", true)), - Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientWorker", true)), - Constants.DEFAULT_IO_THREADS); + Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientWorker", true)), + Constants.DEFAULT_IO_THREADS); private ClientBootstrap bootstrap; private volatile Channel channel; // volatile, please copy reference to use @@ -127,7 +128,7 @@ public class NettyClient extends AbstractClient { Throwable cause = future.getCause(); RemotingException remotingException = new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server " - + getRemoteAddress() + ", error message is:" + cause.getMessage(), cause); + + getRemoteAddress() + ", error message is:" + cause.getMessage(), cause); // 6-1 - Failed to connect to provider server by other reason. logger.error(TRANSPORT_FAILED_CONNECT_PROVIDER, "network disconnected", "", "Failed to connect to provider server by other reason.", cause); @@ -136,9 +137,9 @@ public class NettyClient extends AbstractClient { } else { RemotingException remotingException = new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server " - + getRemoteAddress() + " client-side timeout " - + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client " - + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()); + + getRemoteAddress() + " client-side timeout " + + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client " + + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()); // 6-2 - Client-side timeout. logger.error(TRANSPORT_CLIENT_CONNECT_TIMEOUT, "provider crash", "", "Client-side timeout.", remotingException); @@ -157,7 +158,7 @@ public class NettyClient extends AbstractClient { try { NettyChannel.removeChannelIfDisconnected(channel); } catch (Throwable t) { - logger.warn(t.getMessage()); + logger.warn(TRANSPORT_FAILED_DISCONNECT_PROVIDER, "", "", t.getMessage()); } } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyHelper.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyHelper.java index 64f41b2dae..bfe8cafd8a 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyHelper.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyHelper.java @@ -16,13 +16,15 @@ */ package org.apache.dubbo.remoting.transport.netty; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.jboss.netty.logging.AbstractInternalLogger; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNEXPECTED_EXCEPTION; + final class NettyHelper { public static void setNettyLoggerFactory() { @@ -36,15 +38,15 @@ final class NettyHelper { @Override public InternalLogger newInstance(String name) { - return new DubboLogger(LoggerFactory.getLogger(name)); + return new DubboLogger(LoggerFactory.getErrorTypeAwareLogger(name)); } } static class DubboLogger extends AbstractInternalLogger { - private Logger logger; + private ErrorTypeAwareLogger logger; - DubboLogger(Logger logger) { + DubboLogger(ErrorTypeAwareLogger logger) { this.logger = logger; } @@ -90,22 +92,22 @@ final class NettyHelper { @Override public void warn(String msg) { - logger.warn(msg); + logger.warn(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", msg); } @Override public void warn(String msg, Throwable cause) { - logger.warn(msg, cause); + logger.warn(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", msg, cause); } @Override public void error(String msg) { - logger.error(msg); + logger.error(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", msg); } @Override public void error(String msg, Throwable cause) { - logger.error(msg, cause); + logger.error(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", msg, cause); } @Override diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java index 4afdb00f80..04285dfb62 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.transport.netty; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ExecutorUtil; @@ -47,6 +47,7 @@ import java.util.concurrent.Executors; import static org.apache.dubbo.common.constants.CommonConstants.BACKLOG_KEY; import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_BOSS_POOL_NAME; import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_WORKER_POOL_NAME; @@ -55,7 +56,7 @@ import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_WORKER_POOL_NAME; */ public class NettyServer extends AbstractServer implements RemotingServer { - private static final Logger logger = LoggerFactory.getLogger(NettyServer.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NettyServer.class); private Map channels; // @@ -109,7 +110,7 @@ public class NettyServer extends AbstractServer implements RemotingServer { channel.close(); } } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { Collection channels = getChannels(); @@ -118,12 +119,12 @@ public class NettyServer extends AbstractServer implements RemotingServer { try { channel.close(); } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } } } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { if (bootstrap != null) { @@ -131,14 +132,14 @@ public class NettyServer extends AbstractServer implements RemotingServer { bootstrap.releaseExternalResources(); } } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { if (channels != null) { channels.clear(); } } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } diff --git a/dubbo-remoting/dubbo-remoting-netty4/pom.xml b/dubbo-remoting/dubbo-remoting-netty4/pom.xml index af48662c28..fb4c31784f 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/pom.xml +++ b/dubbo-remoting/dubbo-remoting-netty4/pom.xml @@ -40,9 +40,11 @@ dubbo-remoting-api ${project.parent.version} + io.netty - netty-all + netty-handler-proxy + compile org.apache.dubbo diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java index 24e3a8057f..4534b6c9f1 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; @@ -35,13 +35,14 @@ import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; /** * NettyChannel maintains the cache of channel. */ final class NettyChannel extends AbstractChannel { - private static final Logger logger = LoggerFactory.getLogger(NettyChannel.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NettyChannel.class); /** * the cache for netty channel and dubbo channel */ @@ -180,7 +181,7 @@ final class NettyChannel extends AbstractChannel { } if (!success) { throw new RemotingException(this, "Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to " + getRemoteAddress() - + "in timeout(" + timeout + "ms) limit"); + + "in timeout(" + timeout + "ms) limit"); } } @@ -189,17 +190,17 @@ final class NettyChannel extends AbstractChannel { try { super.close(); } catch (Exception e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { removeChannelIfDisconnected(channel); } catch (Exception e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { attributes.clear(); } catch (Exception e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { if (logger.isInfoEnabled()) { @@ -207,7 +208,7 @@ final class NettyChannel extends AbstractChannel { } channel.close(); } catch (Exception e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java index f664e8e7e8..85d4bfe750 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java @@ -50,6 +50,7 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.apache.dubbo.common.constants.CommonConstants.SSL_ENABLED_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_CLIENT_CONNECT_TIMEOUT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CONNECT_PROVIDER; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_DISCONNECT_PROVIDER; import static org.apache.dubbo.remoting.Constants.DEFAULT_CONNECT_TIMEOUT; import static org.apache.dubbo.remoting.api.NettyEventLoopFactory.eventLoopGroup; import static org.apache.dubbo.remoting.api.NettyEventLoopFactory.socketChannelClass; @@ -111,11 +112,11 @@ public class NettyClient extends AbstractClient { protected void initBootstrap(NettyClientHandler nettyClientHandler) { bootstrap.group(EVENT_LOOP_GROUP.get()) - .option(ChannelOption.SO_KEEPALIVE, true) - .option(ChannelOption.TCP_NODELAY, true) - .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) - //.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout()) - .channel(socketChannelClass()); + .option(ChannelOption.SO_KEEPALIVE, true) + .option(ChannelOption.TCP_NODELAY, true) + .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) + //.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout()) + .channel(socketChannelClass()); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.max(DEFAULT_CONNECT_TIMEOUT, getConnectTimeout())); bootstrap.handler(new ChannelInitializer() { @@ -130,13 +131,13 @@ public class NettyClient extends AbstractClient { NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this); ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug - .addLast("decoder", adapter.getDecoder()) - .addLast("encoder", adapter.getEncoder()) - .addLast("client-idle-handler", new IdleStateHandler(heartbeatInterval, 0, 0, MILLISECONDS)) - .addLast("handler", nettyClientHandler); + .addLast("decoder", adapter.getDecoder()) + .addLast("encoder", adapter.getEncoder()) + .addLast("client-idle-handler", new IdleStateHandler(heartbeatInterval, 0, 0, MILLISECONDS)) + .addLast("handler", nettyClientHandler); String socksProxyHost = ConfigurationUtils.getProperty(getUrl().getOrDefaultApplicationModel(), SOCKS_PROXY_HOST); - if(socksProxyHost != null && !isFilteredAddress(getUrl().getHost())) { + if (socksProxyHost != null && !isFilteredAddress(getUrl().getHost())) { int socksProxyPort = Integer.parseInt(ConfigurationUtils.getProperty(getUrl().getOrDefaultApplicationModel(), SOCKS_PROXY_PORT, DEFAULT_SOCKS_PROXY_PORT)); Socks5ProxyHandler socks5ProxyHandler = new Socks5ProxyHandler(new InetSocketAddress(socksProxyHost, socksProxyPort)); ch.pipeline().addFirst(socks5ProxyHandler); @@ -220,7 +221,7 @@ public class NettyClient extends AbstractClient { // 6-1 Failed to connect to provider server by other reason. RemotingException remotingException = new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server " - + serverAddress + ", error message is:" + cause.getMessage(), cause); + + serverAddress + ", error message is:" + cause.getMessage(), cause); logger.error(TRANSPORT_FAILED_CONNECT_PROVIDER, "network disconnected", "", "Failed to connect to provider server by other reason.", cause); @@ -232,9 +233,9 @@ public class NettyClient extends AbstractClient { // 6-2 Client-side timeout RemotingException remotingException = new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server " - + serverAddress + " client-side timeout " - + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client " - + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()); + + serverAddress + " client-side timeout " + + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client " + + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()); logger.error(TRANSPORT_CLIENT_CONNECT_TIMEOUT, "provider crash", "", "Client-side timeout.", remotingException); @@ -254,7 +255,7 @@ public class NettyClient extends AbstractClient { try { NettyChannel.removeChannelIfDisconnected(channel); } catch (Throwable t) { - logger.warn(t.getMessage()); + logger.warn(TRANSPORT_FAILED_DISCONNECT_PROVIDER, "", "", t.getMessage()); } } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServer.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServer.java index 6a3b926219..57ceb3f44a 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServer.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServer.java @@ -18,7 +18,7 @@ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.NetUtils; @@ -54,6 +54,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SSL_ENABLED_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_BOSS_POOL_NAME; import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_WORKER_POOL_NAME; @@ -62,7 +63,7 @@ import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_WORKER_POOL_NAME; */ public class NettyPortUnificationServer extends AbstractPortUnificationServer { - private static final Logger logger = LoggerFactory.getLogger(NettyPortUnificationServer.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NettyPortUnificationServer.class); private final int serverShutdownTimeoutMills; /** @@ -100,8 +101,8 @@ public class NettyPortUnificationServer extends AbstractPortUnificationServer { } } - public void bind(){ - if(channel == null) { + public void bind() { + if (channel == null) { doOpen(); } } @@ -153,7 +154,7 @@ public class NettyPortUnificationServer extends AbstractPortUnificationServer { } @Override - public void doClose(){ + public void doClose() { try { if (channel != null) { @@ -163,7 +164,7 @@ public class NettyPortUnificationServer extends AbstractPortUnificationServer { } } catch (Throwable e) { - logger.warn("Interrupted while shutting down", e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", "Interrupted while shutting down", e); } try { @@ -173,12 +174,12 @@ public class NettyPortUnificationServer extends AbstractPortUnificationServer { try { channel.close(); } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } } } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } for (WireProtocol protocol : getProtocols()) { @@ -197,7 +198,7 @@ public class NettyPortUnificationServer extends AbstractPortUnificationServer { workerGroupShutdownFuture.awaitUninterruptibly(timeout, MILLISECONDS); } } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServerHandler.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServerHandler.java index e6fcb1ad65..3d22ce7a03 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServerHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServerHandler.java @@ -18,7 +18,7 @@ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.io.Bytes; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; @@ -39,9 +39,11 @@ import java.util.List; import java.util.Map; import java.util.Set; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNEXPECTED_EXCEPTION; + public class NettyPortUnificationServerHandler extends ByteToMessageDecoder { - private static final Logger LOGGER = LoggerFactory.getLogger( + private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger( NettyPortUnificationServerHandler.class); private final SslContext sslCtx; @@ -69,7 +71,7 @@ public class NettyPortUnificationServerHandler extends ByteToMessageDecoder { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - LOGGER.error("Unexpected exception from downstream before protocol detected.", cause); + LOGGER.error(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", "Unexpected exception from downstream before protocol detected.", cause); } @Override @@ -123,7 +125,7 @@ public class NettyPortUnificationServerHandler extends ByteToMessageDecoder { Set supported = url.getApplicationModel() .getExtensionLoader(WireProtocol.class) .getSupportedExtensions(); - LOGGER.error(String.format("Can not recognize protocol from downstream=%s . " + LOGGER.error(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", String.format("Can not recognize protocol from downstream=%s . " + "preface=%s protocols=%s", ctx.channel().remoteAddress(), Bytes.bytes2hex(preface), supported)); diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java index 5c4ce032cc..d3c5a8ab37 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java @@ -18,7 +18,7 @@ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ExecutorUtil; @@ -52,6 +52,7 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.KEEP_ALIVE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SSL_ENABLED_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_BOSS_POOL_NAME; import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_WORKER_POOL_NAME; @@ -61,7 +62,7 @@ import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_WORKER_POOL_NAME; */ public class NettyServer extends AbstractServer { - private static final Logger logger = LoggerFactory.getLogger(NettyServer.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NettyServer.class); /** * the cache for alive worker channel. * @@ -119,7 +120,7 @@ public class NettyServer extends AbstractServer { protected EventLoopGroup createWorkerGroup() { return NettyEventLoopFactory.eventLoopGroup( - getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS), + getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS), EVENT_LOOP_WORKER_POOL_NAME); } @@ -131,27 +132,27 @@ public class NettyServer extends AbstractServer { boolean keepalive = getUrl().getParameter(KEEP_ALIVE_KEY, Boolean.FALSE); bootstrap.group(bossGroup, workerGroup) - .channel(NettyEventLoopFactory.serverSocketChannelClass()) - .option(ChannelOption.SO_REUSEADDR, Boolean.TRUE) - .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE) - .childOption(ChannelOption.SO_KEEPALIVE, keepalive) - .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) - .childHandler(new ChannelInitializer() { - @Override - protected void initChannel(SocketChannel ch) throws Exception { - // FIXME: should we use getTimeout()? - int idleTimeout = UrlUtils.getIdleTimeout(getUrl()); - NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this); - if (getUrl().getParameter(SSL_ENABLED_KEY, false)) { - ch.pipeline().addLast("negotiation", new SslServerTlsHandler(getUrl())); - } - ch.pipeline() - .addLast("decoder", adapter.getDecoder()) - .addLast("encoder", adapter.getEncoder()) - .addLast("server-idle-handler", new IdleStateHandler(0, 0, idleTimeout, MILLISECONDS)) - .addLast("handler", nettyServerHandler); + .channel(NettyEventLoopFactory.serverSocketChannelClass()) + .option(ChannelOption.SO_REUSEADDR, Boolean.TRUE) + .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE) + .childOption(ChannelOption.SO_KEEPALIVE, keepalive) + .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel ch) throws Exception { + // FIXME: should we use getTimeout()? + int idleTimeout = UrlUtils.getIdleTimeout(getUrl()); + NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this); + if (getUrl().getParameter(SSL_ENABLED_KEY, false)) { + ch.pipeline().addLast("negotiation", new SslServerTlsHandler(getUrl())); } - }); + ch.pipeline() + .addLast("decoder", adapter.getDecoder()) + .addLast("encoder", adapter.getEncoder()) + .addLast("server-idle-handler", new IdleStateHandler(0, 0, idleTimeout, MILLISECONDS)) + .addLast("handler", nettyServerHandler); + } + }); } @Override @@ -162,7 +163,7 @@ public class NettyServer extends AbstractServer { channel.close(); } } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { Collection channels = getChannels(); @@ -171,12 +172,12 @@ public class NettyServer extends AbstractServer { try { channel.close(); } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } } } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { if (bootstrap != null) { @@ -188,14 +189,14 @@ public class NettyServer extends AbstractServer { workerGroupShutdownFuture.syncUninterruptibly(); } } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { if (channels != null) { channels.clear(); } } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/MessageFormatter.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/MessageFormatter.java index 808600e97f..5c98405ddf 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/MessageFormatter.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/MessageFormatter.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.remoting.transport.netty4.logging; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ArrayUtils; @@ -24,6 +24,8 @@ import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNSUPPORTED_MESSAGE; + // contributors: lizongbo: proposed special treatment of array parameter values // Joern Huxhorn: pointed out double[] omission, suggested deep array copy @@ -90,7 +92,7 @@ import java.util.Map; * {@link #arrayFormat(String, Object[])} methods for more details. */ final class MessageFormatter { - private static final Logger logger = LoggerFactory.getLogger(MessageFormatter.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MessageFormatter.class); static final char DELIM_START = '{'; static final char DELIM_STOP = '}'; static final String DELIM_STR = "{}"; @@ -189,12 +191,12 @@ final class MessageFormatter { // no more variables if (i == 0) { // this is a simple string return new FormattingTuple(messagePattern, argArray, - throwableCandidate); + throwableCandidate); } else { // add the tail string which contains no variables and return // the result. sbuf.append(messagePattern.substring(i)); return new FormattingTuple(sbuf.toString(), argArray, - throwableCandidate); + throwableCandidate); } } else { if (isEscapedDelimeter(messagePattern, j)) { @@ -282,9 +284,9 @@ final class MessageFormatter { sbuf.append(oAsString); } catch (Throwable t) { System.err - .println("SLF4J: Failed toString() invocation on an object of type [" - + o.getClass().getName() + ']'); - logger.error(t.getMessage(), t); + .println("SLF4J: Failed toString() invocation on an object of type [" + + o.getClass().getName() + ']'); + logger.error(TRANSPORT_UNSUPPORTED_MESSAGE, "", "", t.getMessage(), t); sbuf.append("[FAILED toString()]"); } } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ConnectionTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ConnectionTest.java index 55aa550639..cb1037ef78 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ConnectionTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ConnectionTest.java @@ -28,9 +28,9 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -public class ConnectionTest { +class ConnectionTest { @Test - public void connectSyncTest() throws Throwable { + void connectSyncTest() throws Throwable { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("empty://127.0.0.1:" + port + "?foo=bar"); NettyPortUnificationServer server = null; @@ -57,39 +57,44 @@ public class ConnectionTest { // ignored } } - - } @Test - public void testMultiConnect() throws Throwable { + void testMultiConnect() throws Throwable { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("empty://127.0.0.1:" + port + "?foo=bar"); NettyPortUnificationServer server = null; + ExecutorService service = Executors.newFixedThreadPool(10); + try { server = new NettyPortUnificationServer(url, new DefaultPuHandler()); - server.close(); Connection connection = new Connection(url); - ExecutorService service = Executors.newFixedThreadPool(10); + final CountDownLatch latch = new CountDownLatch(10); for (int i = 0; i < 10; i++) { Runnable runnable = () -> { try { Assertions.assertTrue(connection.isAvailable()); - latch.countDown(); } catch (Exception e) { // ignore + } finally { + latch.countDown(); } }; + service.execute(runnable); } + + latch.await(); } finally { try { server.close(); } catch (Throwable e) { // ignored } + + service.shutdown(); } } } diff --git a/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClient.java b/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClient.java index a3c719fc58..8abb161c27 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClient.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClient.java @@ -56,6 +56,7 @@ import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.SESSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CONNECT_REGISTRY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION; public class Curator5ZookeeperClient extends AbstractZookeeperClient { @@ -72,10 +73,10 @@ public class Curator5ZookeeperClient extends AbstractZookeeperClient 0) { builder = builder.authorization("digest", userInformation.getBytes()); @@ -116,7 +117,7 @@ public class Curator5ZookeeperClient extends AbstractZookeeperClient { @@ -76,10 +77,10 @@ public class CuratorZookeeperClient extends AbstractZookeeperClient * But notice that trying to give an uncompleted CompletableFuture a new specified value may face a race condition, * because the background thread watching the real result will also change the status of this CompletableFuture. * The result is you may lose the value you expected to set. @@ -114,7 +115,7 @@ public class AsyncRpcResult implements Result { } } catch (Exception e) { // This should not happen in normal request process; - logger.error("Got exception when trying to fetch the underlying result from AsyncRpcResult."); + logger.error(PROXY_ERROR_ASYNC_RESPONSE, "", "", "Got exception when trying to fetch the underlying result from AsyncRpcResult."); throw new RpcException(e); } } @@ -136,7 +137,7 @@ public class AsyncRpcResult implements Result { } } catch (Exception e) { // This should not happen in normal request process; - logger.error("Got exception when trying to fetch the underlying result from AsyncRpcResult."); + logger.error(PROXY_ERROR_ASYNC_RESPONSE, "", "", "Got exception when trying to fetch the underlying result from AsyncRpcResult."); throw new RpcException(e); } } @@ -161,7 +162,7 @@ public class AsyncRpcResult implements Result { } } catch (Exception e) { // This should not happen in normal request process; - logger.error("Got exception when trying to fetch the underlying result from AsyncRpcResult."); + logger.error(PROXY_ERROR_ASYNC_RESPONSE, "", "", "Got exception when trying to fetch the underlying result from AsyncRpcResult."); throw new RpcException(e); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ExecutableListener.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ExecutableListener.java index c263bf8ede..edfc05a49d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ExecutableListener.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ExecutableListener.java @@ -17,15 +17,17 @@ package org.apache.dubbo.rpc; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.util.concurrent.Executor; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_NOTIFY_EVENT; + public class ExecutableListener implements Runnable { - private static final Logger log = LoggerFactory.getLogger(ExecutableListener.class); + private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(ExecutableListener.class); private final Executor executor; private final CancellationListener listener; @@ -46,7 +48,7 @@ public class ExecutableListener implements Runnable { try { executor.execute(this); } catch (Throwable t) { - log.warn("Exception notifying context listener", t); + log.warn(COMMON_FAILED_NOTIFY_EVENT, "", "", "Exception notifying context listener", t); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java index 283b993417..ec74ff6d77 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; import org.apache.dubbo.common.utils.ConfigUtils; @@ -44,6 +44,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION; import static org.apache.dubbo.rpc.Constants.ACCESS_LOG_KEY; /** @@ -63,7 +64,7 @@ import static org.apache.dubbo.rpc.Constants.ACCESS_LOG_KEY; @Activate(group = PROVIDER, value = ACCESS_LOG_KEY) public class AccessLogFilter implements Filter { - private static final Logger logger = LoggerFactory.getLogger(AccessLogFilter.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AccessLogFilter.class); private static final String LOG_KEY = "dubbo.accesslog"; @@ -112,7 +113,7 @@ public class AccessLogFilter implements Filter { optionalAccessLogData = Optional.of(buildAccessLogData(invoker, inv)); } } catch (Throwable t) { - logger.warn("Exception in AccessLogFilter of service(" + invoker + " -> " + inv + ")", t); + logger.warn(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", "Exception in AccessLogFilter of service(" + invoker + " -> " + inv + ")", t); } try { return invoker.invoke(inv); @@ -131,7 +132,7 @@ public class AccessLogFilter implements Filter { if (logQueue.size() < LOG_MAX_BUFFER) { logQueue.add(accessLogData); } else { - logger.warn("AccessLog buffer is full. Do a force writing to file to clear buffer."); + logger.warn(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "","AccessLog buffer is full. Do a force writing to file to clear buffer."); //just write current logSet to file. writeLogSetToFile(accessLog, logQueue); //after force writing, add accessLogData to current logSet @@ -153,7 +154,7 @@ public class AccessLogFilter implements Filter { processWithAccessKeyLogger(logSet, file); } } catch (Exception e) { - logger.error(e.getMessage(), e); + logger.error(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", e.getMessage(), e); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java index d736e8ae11..cf47119a66 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CompatibleTypeUtils; import org.apache.dubbo.common.utils.PojoUtils; @@ -30,6 +30,8 @@ import org.apache.dubbo.rpc.RpcException; import java.lang.reflect.Method; import java.lang.reflect.Type; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION; + /** * CompatibleFilter make the remote method's return value compatible to invoker's version of object. * To make return object compatible it does @@ -42,11 +44,10 @@ import java.lang.reflect.Type; * * * @see Filter - * */ public class CompatibleFilter implements Filter, Filter.Listener { - private static Logger logger = LoggerFactory.getLogger(CompatibleFilter.class); + private static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CompatibleFilter.class); @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { @@ -78,7 +79,7 @@ public class CompatibleFilter implements Filter, Filter.Listener { appResponse.setValue(newValue); } } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", t.getMessage(), t); } } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java index e5b2cfc4f1..98654af030 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java @@ -18,7 +18,7 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.rpc.Filter; @@ -29,6 +29,7 @@ import org.apache.dubbo.rpc.RpcException; import java.util.Set; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNSUPPORTED_INVOKER; import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY; /** @@ -40,7 +41,7 @@ import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY; @Activate(group = CommonConstants.CONSUMER, value = DEPRECATED_KEY) public class DeprecatedFilter implements Filter { - private static final Logger LOGGER = LoggerFactory.getLogger(DeprecatedFilter.class); + private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(DeprecatedFilter.class); private static final Set LOGGED = new ConcurrentHashSet(); @@ -50,7 +51,7 @@ public class DeprecatedFilter implements Filter { if (!LOGGED.contains(key)) { LOGGED.add(key); if (invoker.getUrl().getMethodParameter(invocation.getMethodName(), DEPRECATED_KEY, false)) { - LOGGER.error("The service method " + invoker.getInterface().getName() + "." + getMethodSignature(invocation) + " is DEPRECATED! Declare from " + invoker.getUrl()); + LOGGER.error(COMMON_UNSUPPORTED_INVOKER, "", "", "The service method " + invoker.getInterface().getName() + "." + getMethodSignature(invocation) + " is DEPRECATED! Declare from " + invoker.getUrl()); } } return invoker.invoke(invocation); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExceptionFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExceptionFilter.java index 28e534d06c..91c830cb53 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExceptionFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExceptionFilter.java @@ -18,7 +18,7 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; @@ -32,6 +32,8 @@ import org.apache.dubbo.rpc.service.GenericService; import java.lang.reflect.Method; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION; + /** * ExceptionInvokerFilter @@ -45,7 +47,7 @@ import java.lang.reflect.Method; */ @Activate(group = CommonConstants.PROVIDER) public class ExceptionFilter implements Filter, Filter.Listener { - private Logger logger = LoggerFactory.getLogger(ExceptionFilter.class); + private ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ExceptionFilter.class); @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { @@ -76,7 +78,7 @@ public class ExceptionFilter implements Filter, Filter.Listener { } // for the exception not found in method's signature, print ERROR message in server's log. - logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getServiceContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + exception.getClass().getName() + ": " + exception.getMessage(), exception); + logger.error(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", "Got unchecked and undeclared exception which called by " + RpcContext.getServiceContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + exception.getClass().getName() + ": " + exception.getMessage(), exception); // directly throw if exception class and interface class are in the same jar file. String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface()); @@ -97,18 +99,18 @@ public class ExceptionFilter implements Filter, Filter.Listener { // otherwise, wrap with RuntimeException and throw back to the client appResponse.setException(new RuntimeException(StringUtils.toString(exception))); } catch (Throwable e) { - logger.warn("Fail to ExceptionFilter when called by " + RpcContext.getServiceContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e); + logger.warn(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", "Fail to ExceptionFilter when called by " + RpcContext.getServiceContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e); } } } @Override public void onError(Throwable e, Invoker invoker, Invocation invocation) { - logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getServiceContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e); + logger.error(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", "Got unchecked and undeclared exception which called by " + RpcContext.getServiceContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e); } // For test purpose - public void setLogger(Logger logger) { + public void setLogger(ErrorTypeAwareLogger logger) { this.logger = logger; } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java index 75dcd5c1bc..4931fc8887 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java @@ -25,7 +25,7 @@ import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.io.UnsafeByteArrayInputStream; import org.apache.dubbo.common.io.UnsafeByteArrayOutputStream; import org.apache.dubbo.common.json.GsonUtils; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.utils.PojoUtils; @@ -54,6 +54,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE_ASYNC; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_BEAN; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_PROTOBUF; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; /** @@ -61,7 +62,7 @@ import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; */ @Activate(group = CommonConstants.PROVIDER, order = -20000) public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware { - private final Logger logger = LoggerFactory.getLogger(GenericFilter.class); + private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(GenericFilter.class); private ApplicationModel applicationModel; @@ -119,7 +120,7 @@ public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware { "If you are sure this is a mistake, " + "please set `" + CommonConstants.ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE + "` enable in configuration! " + "Before doing so, please make sure you have configure JEP290 to prevent serialization attack."; - logger.error(notice); + logger.error(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", notice); throw new RpcException(new IllegalStateException(notice)); } @@ -205,9 +206,9 @@ public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware { }).toArray(); } - private String getGenericValueFromRpcContext(){ + private String getGenericValueFromRpcContext() { String generic = RpcContext.getServerAttachment().getAttachment(GENERIC_KEY); - if (StringUtils.isBlank(generic)){ + if (StringUtils.isBlank(generic)) { generic = RpcContext.getClientAttachment().getAttachment(GENERIC_KEY); } return generic; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java index b76caeae6e..85e0de3e77 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java @@ -21,7 +21,7 @@ import org.apache.dubbo.common.beanutil.JavaBeanDescriptor; import org.apache.dubbo.common.beanutil.JavaBeanSerializeUtil; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.PojoUtils; import org.apache.dubbo.common.utils.ReflectUtils; @@ -44,6 +44,7 @@ import java.lang.reflect.Type; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE_ASYNC; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_PARAMETER_DESC; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_REFLECT; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; /** @@ -52,7 +53,7 @@ import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; @Activate(group = CommonConstants.CONSUMER, value = GENERIC_KEY, order = 20000) public class GenericImplFilter implements Filter, Filter.Listener { - private static final Logger logger = LoggerFactory.getLogger(GenericImplFilter.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(GenericImplFilter.class); private static final Class[] GENERIC_PARAMETER_TYPES = new Class[]{String.class, String[].class, Object[].class}; @@ -120,7 +121,7 @@ public class GenericImplFilter implements Filter, Filter.Listener { } invocation.setAttachment( - GENERIC_KEY, invoker.getUrl().getParameter(GENERIC_KEY)); + GENERIC_KEY, invoker.getUrl().getParameter(GENERIC_KEY)); } return invoker.invoke(invocation); } @@ -141,7 +142,7 @@ public class GenericImplFilter implements Filter, Filter.Listener { try { Class invokerInterface = invoker.getInterface(); if (!$INVOKE.equals(methodName) && !$INVOKE_ASYNC.equals(methodName) - && invokerInterface.isAssignableFrom(GenericService.class)) { + && invokerInterface.isAssignableFrom(GenericService.class)) { try { // find the real interface from url String realInterface = invoker.getUrl().getParameter(Constants.INTERFACE); @@ -195,7 +196,7 @@ public class GenericImplFilter implements Filter, Filter.Listener { } field.set(targetException, exception.getExceptionMessage()); } catch (Throwable e) { - logger.warn(e.getMessage(), e); + logger.warn(COMMON_FAILED_REFLECT, "", "", e.getMessage(), e); } appResponse.setException(targetException); } else if (lastException != null) { @@ -215,15 +216,15 @@ public class GenericImplFilter implements Filter, Filter.Listener { private boolean isCallingGenericImpl(String generic, Invocation invocation) { return ProtocolUtils.isGeneric(generic) - && (!$INVOKE.equals(invocation.getMethodName()) && !$INVOKE_ASYNC.equals(invocation.getMethodName())) - && invocation instanceof RpcInvocation; + && (!$INVOKE.equals(invocation.getMethodName()) && !$INVOKE_ASYNC.equals(invocation.getMethodName())) + && invocation instanceof RpcInvocation; } private boolean isMakingGenericCall(String generic, Invocation invocation) { return (invocation.getMethodName().equals($INVOKE) || invocation.getMethodName().equals($INVOKE_ASYNC)) - && invocation.getArguments() != null - && invocation.getArguments().length == 3 - && ProtocolUtils.isGeneric(generic); + && invocation.getArguments() != null + && invocation.getArguments().length == 3 + && ProtocolUtils.isGeneric(generic); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ProfilerServerFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ProfilerServerFilter.java index 5596bf30f7..1fb19f2dde 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ProfilerServerFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ProfilerServerFilter.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.profiler.Profiler; import org.apache.dubbo.common.profiler.ProfilerEntry; @@ -33,11 +33,12 @@ import org.apache.dubbo.rpc.RpcException; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_TIMEOUT_RESPONSE; @Activate(group = PROVIDER, order = Integer.MIN_VALUE) public class ProfilerServerFilter implements Filter, BaseFilter.Listener { private final static String CLIENT_IP_KEY = "client_ip"; - private final static Logger logger = LoggerFactory.getLogger(ProfilerServerFilter.class); + private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ProfilerServerFilter.class); @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { @@ -94,12 +95,13 @@ public class ProfilerServerFilter implements Filter, BaseFilter.Listener { attachment.append(entry.getKey()).append("=").append(entry.getValue()).append(";\n"); }); - logger.warn(String.format("[Dubbo-Provider] execute service %s#%s cost %d.%06d ms, this invocation almost (maybe already) timeout. Timeout: %dms\n" + - "client: %s\n" + - "invocation context:\n%s" + - "thread info: \n%s", - invocation.getTargetServiceUniqueName(), invocation.getMethodName(), usage / 1000_000, usage % 1000_000, timeout, - invocation.get(CLIENT_IP_KEY), attachment, Profiler.buildDetail(profiler))); + logger.warn(PROXY_TIMEOUT_RESPONSE, "", "", + String.format("[Dubbo-Provider] execute service %s#%s cost %d.%06d ms, this invocation almost (maybe already) timeout. Timeout: %dms\n" + + "client: %s\n" + + "invocation context:\n%s" + + "thread info: \n%s", + invocation.getTargetServiceUniqueName(), invocation.getMethodName(), usage / 1000_000, usage % 1000_000, timeout, + invocation.get(CLIENT_IP_KEY), attachment, Profiler.buildDetail(profiler))); } } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java index 45a831c593..dc4aa29ac1 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java @@ -18,7 +18,7 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Filter; @@ -30,6 +30,7 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.TimeoutCountDown; import static org.apache.dubbo.common.constants.CommonConstants.TIME_COUNTDOWN_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_TIMEOUT_REQUEST; /** * Log any invocation timeout, but don't stop server from running @@ -37,7 +38,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.TIME_COUNTDOWN_K @Activate(group = CommonConstants.PROVIDER) public class TimeoutFilter implements Filter, Filter.Listener { - private static final Logger logger = LoggerFactory.getLogger(TimeoutFilter.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TimeoutFilter.class); @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { @@ -52,7 +53,7 @@ public class TimeoutFilter implements Filter, Filter.Listener { if (countDown.isExpired()) { ((AppResponse) appResponse).clear(); // clear response in case of timeout. if (logger.isWarnEnabled()) { - logger.warn("invoke timed out. method: " + invocation.getMethodName() + + logger.warn(PROXY_TIMEOUT_REQUEST, "", "", "invoke timed out. method: " + invocation.getMethodName() + " url is " + invoker.getUrl() + ", invoke elapsed " + countDown.elapsedMillis() + " ms."); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/DeprecatedInvokerListener.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/DeprecatedInvokerListener.java index a647769e83..4ec9a15f5c 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/DeprecatedInvokerListener.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/DeprecatedInvokerListener.java @@ -17,11 +17,12 @@ package org.apache.dubbo.rpc.listener; import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_UNSUPPORTED_INVOKER; import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY; /** @@ -30,12 +31,12 @@ import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY; @Activate(DEPRECATED_KEY) public class DeprecatedInvokerListener extends InvokerListenerAdapter { - private static final Logger LOGGER = LoggerFactory.getLogger(DeprecatedInvokerListener.class); + private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(DeprecatedInvokerListener.class); @Override public void referred(Invoker invoker) throws RpcException { if (invoker.getUrl().getParameter(DEPRECATED_KEY, false)) { - LOGGER.error("The service " + invoker.getInterface().getName() + " is DEPRECATED! Declare from " + invoker.getUrl()); + LOGGER.error(PROXY_UNSUPPORTED_INVOKER,"","","The service " + invoker.getInterface().getName() + " is DEPRECATED! Declare from " + invoker.getUrl()); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerExporterWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerExporterWrapper.java index 021af672a4..972f5cbc56 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerExporterWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerExporterWrapper.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.rpc.listener; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.Exporter; @@ -26,12 +26,14 @@ import org.apache.dubbo.rpc.Invoker; import java.util.List; import java.util.function.Consumer; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_NOTIFY_EVENT; + /** * ListenerExporter */ public class ListenerExporterWrapper implements Exporter { - private static final Logger logger = LoggerFactory.getLogger(ListenerExporterWrapper.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ListenerExporterWrapper.class); private final Exporter exporter; @@ -68,7 +70,7 @@ public class ListenerExporterWrapper implements Exporter { try { consumer.accept(listener); } catch (RuntimeException t) { - logger.error(t.getMessage(), t); + logger.error(COMMON_FAILED_NOTIFY_EVENT, "", "", t.getMessage(), t); exception = t; } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerInvokerWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerInvokerWrapper.java index 2addb81d29..b4ee190812 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerInvokerWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerInvokerWrapper.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.listener; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.Invocation; @@ -34,7 +34,7 @@ import java.util.function.Consumer; */ public class ListenerInvokerWrapper implements Invoker { - private static final Logger logger = LoggerFactory.getLogger(ListenerInvokerWrapper.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ListenerInvokerWrapper.class); private final Invoker invoker; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractExporter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractExporter.java index 41e4eccb95..2378b2458b 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractExporter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractExporter.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.rpc.protocol; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; @@ -26,7 +26,7 @@ import org.apache.dubbo.rpc.Invoker; */ public abstract class AbstractExporter implements Exporter { - protected final Logger logger = LoggerFactory.getLogger(getClass()); + protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final Invoker invoker; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java index f22edbf927..c2d7b31699 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java @@ -20,7 +20,7 @@ import org.apache.dubbo.common.Node; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.constants.CommonConstants; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.ThreadlessExecutor; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; @@ -50,6 +50,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; import static org.apache.dubbo.rpc.Constants.SERIALIZATION_ID_KEY; /** @@ -57,7 +58,7 @@ import static org.apache.dubbo.rpc.Constants.SERIALIZATION_ID_KEY; */ public abstract class AbstractInvoker implements Invoker { - protected static final Logger logger = LoggerFactory.getLogger(AbstractInvoker.class); + protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractInvoker.class); /** * Service interface type @@ -165,7 +166,7 @@ public abstract class AbstractInvoker implements Invoker { public Result invoke(Invocation inv) throws RpcException { // if invoker is destroyed due to address refresh from registry, let's allow the current invoke to proceed if (isDestroyed()) { - logger.warn("Invoker for service " + this + " on consumer " + NetUtils.getLocalHost() + " is destroyed, " + ", dubbo version is " + Version.getVersion() + ", this invoker should not be used any longer"); + logger.warn(PROTOCOL_FAILED_REQUEST, "", "", "Invoker for service " + this + " on consumer " + NetUtils.getLocalHost() + " is destroyed, " + ", dubbo version is " + Version.getVersion() + ", this invoker should not be used any longer"); } RpcInvocation invocation = (RpcInvocation) inv; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java index 5278c35c6e..50c37d9a81 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java @@ -18,7 +18,7 @@ package org.apache.dubbo.rpc.protocol; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.support.SerializableClassRegistry; import org.apache.dubbo.common.serialize.support.SerializationOptimizer; @@ -45,13 +45,14 @@ import java.util.concurrent.ConcurrentHashMap; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.OPTIMIZER_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DESTROY_INVOKER; /** * abstract ProtocolSupport. */ public abstract class AbstractProtocol implements Protocol, ScopeModelAware { - protected final Logger logger = LoggerFactory.getLogger(getClass()); + protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); protected final Map> exporterMap = new ConcurrentHashMap<>(); @@ -107,13 +108,13 @@ public abstract class AbstractProtocol implements Protocol, ScopeModelAware { } invoker.destroy(); } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", t.getMessage(), t); } } } invokers.clear(); - exporterMap.forEach((key, exporter)-> { + exporterMap.forEach((key, exporter) -> { if (exporter != null) { try { if (logger.isInfoEnabled()) { @@ -121,7 +122,7 @@ public abstract class AbstractProtocol implements Protocol, ScopeModelAware { } exporter.unexport(); } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", t.getMessage(), t); } } }); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java index 3af93813a4..e1727c38ca 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java @@ -44,6 +44,7 @@ import java.util.concurrent.CopyOnWriteArrayList; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNSUPPORTED; /** * AbstractProxyProtocol @@ -95,7 +96,7 @@ public abstract class AbstractProxyProtocol extends AbstractProtocol { try { runnable.run(); } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(PROTOCOL_UNSUPPORTED, "", "", t.getMessage(), t); } } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java index 974c73aaac..269392b04b 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.rpc.proxy; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.ReflectUtils; @@ -34,6 +34,7 @@ import java.util.Arrays; import java.util.LinkedHashSet; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_UNSUPPORTED_INVOKER; import static org.apache.dubbo.rpc.Constants.INTERFACES; /** @@ -44,7 +45,7 @@ public abstract class AbstractProxyFactory implements ProxyFactory { EchoService.class, Destroyable.class }; - private static final Logger logger = LoggerFactory.getLogger(AbstractProxyFactory.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractProxyFactory.class); @Override public T getProxy(Invoker invoker) throws RpcException { @@ -98,7 +99,7 @@ public abstract class AbstractProxyFactory implements ProxyFactory { } interfaces.remove(invoker.getInterface()); - logger.error("Error occur when creating proxy. Invoker is in generic mode. Trying to create proxy without real interface class.", t); + logger.error(PROXY_UNSUPPORTED_INVOKER, "", "", "Error occur when creating proxy. Invoker is in generic mode. Trying to create proxy without real interface class.", t); return getProxy(invoker, interfaces.toArray(new Class[0])); } else { throw t; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.java index 7235d0fdb2..f9b6f0db82 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.proxy; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.profiler.Profiler; import org.apache.dubbo.common.profiler.ProfilerEntry; @@ -36,12 +36,13 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_ASYNC_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_ERROR_ASYNC_RESPONSE; /** * This Invoker works on provider side, delegates RPC to interface implementation. */ public abstract class AbstractProxyInvoker implements Invoker { - Logger logger = LoggerFactory.getLogger(AbstractProxyInvoker.class); + ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractProxyInvoker.class); private final T proxy; @@ -127,7 +128,7 @@ public abstract class AbstractProxyInvoker implements Invoker { return new AsyncRpcResult(appResponseFuture, invocation); } catch (InvocationTargetException e) { if (RpcContext.getServiceContext().isAsyncStarted() && !RpcContext.getServiceContext().stopAsync()) { - logger.error("Provider async started, but got an exception from the original method, cannot write the exception back to consumer because an async result may have returned the new thread.", e); + logger.error(PROXY_ERROR_ASYNC_RESPONSE, "", "", "Provider async started, but got an exception from the original method, cannot write the exception back to consumer because an async result may have returned the new thread.", e); } return AsyncRpcResult.newDefaultAsyncResult(null, e.getTargetException(), invocation); } catch (Throwable e) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvocationUtil.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvocationUtil.java index 9d75590624..dd245a4767 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvocationUtil.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvocationUtil.java @@ -18,7 +18,7 @@ package org.apache.dubbo.rpc.proxy; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.profiler.Profiler; import org.apache.dubbo.common.profiler.ProfilerEntry; @@ -29,9 +29,10 @@ import org.apache.dubbo.rpc.RpcServiceContext; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_TIMEOUT_REQUEST; public class InvocationUtil { - private static final Logger logger = LoggerFactory.getLogger(InvokerInvocationHandler.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(InvokerInvocationHandler.class); public static Object invoke(Invoker invoker, RpcInvocation rpcInvocation) throws Throwable { URL url = invoker.getUrl(); @@ -71,7 +72,7 @@ public class InvocationUtil { attachment.append(entry.getKey()).append("=").append(entry.getValue()).append(";\n"); }); - logger.warn(String.format( + logger.warn(PROXY_TIMEOUT_REQUEST, "", "", String.format( "[Dubbo-Consumer] execute service %s#%s cost %d.%06d ms, this invocation almost (maybe already) timeout. Timeout: %dms\n" + "invocation context:\n%s" + "thread info: \n%s", rpcInvocation.getProtocolServiceKey(), rpcInvocation.getMethodName(), diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java index 12d48f5427..8755a75cca 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java @@ -29,6 +29,8 @@ import org.apache.dubbo.rpc.proxy.jdk.JdkProxyFactory; import java.util.Arrays; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED_JAVASSIST; + /** * JavassistRpcProxyFactory */ @@ -45,13 +47,13 @@ public class JavassistProxyFactory extends AbstractProxyFactory { // try fall back to JDK proxy factory try { T proxy = jdkProxyFactory.getProxy(invoker, interfaces); - logger.error("Failed to generate proxy by Javassist failed. Fallback to use JDK proxy success. " + + logger.error(PROXY_FAILED_JAVASSIST, "", "", "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy success. " + "Interfaces: " + Arrays.toString(interfaces), fromJavassist); return proxy; } catch (Throwable fromJdk) { - logger.error("Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. " + + logger.error(PROXY_FAILED_JAVASSIST, "", "", "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + Arrays.toString(interfaces) + " Javassist Error.", fromJavassist); - logger.error("Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. " + + logger.error(PROXY_FAILED_JAVASSIST, "", "", "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + Arrays.toString(interfaces) + " JDK Error.", fromJdk); throw fromJavassist; } @@ -75,14 +77,14 @@ public class JavassistProxyFactory extends AbstractProxyFactory { // try fall back to JDK proxy factory try { Invoker invoker = jdkProxyFactory.getInvoker(proxy, type, url); - logger.error("Failed to generate invoker by Javassist failed. Fallback to use JDK proxy success. " + + logger.error(PROXY_FAILED_JAVASSIST, "", "", "Failed to generate invoker by Javassist failed. Fallback to use JDK proxy success. " + "Interfaces: " + type, fromJavassist); // log out error return invoker; } catch (Throwable fromJdk) { - logger.error("Failed to generate invoker by Javassist failed. Fallback to use JDK proxy is also failed. " + + logger.error(PROXY_FAILED_JAVASSIST, "", "", "Failed to generate invoker by Javassist failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + type + " Javassist Error.", fromJavassist); - logger.error("Failed to generate invoker by Javassist failed. Fallback to use JDK proxy is also failed. " + + logger.error(PROXY_FAILED_JAVASSIST, "", "", "Failed to generate invoker by Javassist failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + type + " JDK Error.", fromJdk); throw fromJavassist; } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java index a49b9755e7..9721df43ec 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java @@ -20,7 +20,7 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.bytecode.Wrapper; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.NetUtils; @@ -36,6 +36,7 @@ import org.apache.dubbo.rpc.service.GenericService; import java.lang.reflect.Constructor; import static org.apache.dubbo.common.constants.CommonConstants.STUB_EVENT_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED_EXPORT_SERVICE; import static org.apache.dubbo.rpc.Constants.DEFAULT_STUB_EVENT; import static org.apache.dubbo.rpc.Constants.IS_SERVER_KEY; import static org.apache.dubbo.rpc.Constants.LOCAL_KEY; @@ -47,7 +48,7 @@ import static org.apache.dubbo.rpc.Constants.STUB_KEY; */ public class StubProxyFactoryWrapper implements ProxyFactory { - private static final Logger LOGGER = LoggerFactory.getLogger(StubProxyFactoryWrapper.class); + private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(StubProxyFactoryWrapper.class); private final ProxyFactory proxyFactory; @@ -92,14 +93,14 @@ public class StubProxyFactoryWrapper implements ProxyFactory { try { export(proxy, invoker.getInterface(), urlBuilder.build()); } catch (Exception e) { - LOGGER.error("export a stub service error.", e); + LOGGER.error(PROXY_FAILED_EXPORT_SERVICE, "", "", "export a stub service error.", e); } } } catch (NoSuchMethodException e) { throw new IllegalStateException("No such constructor \"public " + stubClass.getSimpleName() + "(" + serviceType.getName() + ")\" in stub implementation class " + stubClass.getName(), e); } } catch (Throwable t) { - LOGGER.error("Failed to create stub implementation class " + stub + " in consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() + ", cause: " + t.getMessage(), t); + LOGGER.error(PROXY_FAILED_EXPORT_SERVICE, "", "", "Failed to create stub implementation class " + stub + " in consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() + ", cause: " + t.getMessage(), t); // ignore } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java index 747380722d..8f864efb46 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.support; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; @@ -38,6 +38,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_PARAMETE import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_ATTACHMENT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_ATTACHMENT_KEY_LOWER; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_REFLECT; import static org.apache.dubbo.rpc.Constants.$ECHO; import static org.apache.dubbo.rpc.Constants.$ECHO_PARAMETER_DESC; import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; @@ -50,15 +51,15 @@ import static org.apache.dubbo.rpc.Constants.RETURN_KEY; */ public class RpcUtils { - private static final Logger logger = LoggerFactory.getLogger(RpcUtils.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RpcUtils.class); private static final AtomicLong INVOKE_ID = new AtomicLong(0); public static Class getReturnType(Invocation invocation) { try { if (invocation != null && invocation.getInvoker() != null - && invocation.getInvoker().getUrl() != null - && invocation.getInvoker().getInterface() != GenericService.class - && !invocation.getMethodName().startsWith("$")) { + && invocation.getInvoker().getUrl() != null + && invocation.getInvoker().getInterface() != GenericService.class + && !invocation.getMethodName().startsWith("$")) { String service = invocation.getInvoker().getUrl().getServiceInterface(); if (StringUtils.isNotEmpty(service)) { Method method = getMethodByService(invocation, service); @@ -66,7 +67,7 @@ public class RpcUtils { } } } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(COMMON_FAILED_REFLECT, "", "", t.getMessage(), t); } return null; } @@ -74,9 +75,9 @@ public class RpcUtils { public static Type[] getReturnTypes(Invocation invocation) { try { if (invocation != null && invocation.getInvoker() != null - && invocation.getInvoker().getUrl() != null - && invocation.getInvoker().getInterface() != GenericService.class - && !invocation.getMethodName().startsWith("$")) { + && invocation.getInvoker().getUrl() != null + && invocation.getInvoker().getInterface() != GenericService.class + && !invocation.getMethodName().startsWith("$")) { String service = invocation.getInvoker().getUrl().getServiceInterface(); if (StringUtils.isNotEmpty(service)) { Method method = getMethodByService(invocation, service); @@ -84,7 +85,7 @@ public class RpcUtils { } } } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(COMMON_FAILED_REFLECT, "", "", t.getMessage(), t); } return null; } @@ -120,9 +121,9 @@ public class RpcUtils { public static String getMethodName(Invocation invocation) { if ($INVOKE.equals(invocation.getMethodName()) - && invocation.getArguments() != null - && invocation.getArguments().length > 0 - && invocation.getArguments()[0] instanceof String) { + && invocation.getArguments() != null + && invocation.getArguments().length > 0 + && invocation.getArguments()[0] instanceof String) { return (String) invocation.getArguments()[0]; } return invocation.getMethodName(); @@ -130,9 +131,9 @@ public class RpcUtils { public static Object[] getArguments(Invocation invocation) { if ($INVOKE.equals(invocation.getMethodName()) - && invocation.getArguments() != null - && invocation.getArguments().length > 2 - && invocation.getArguments()[2] instanceof Object[]) { + && invocation.getArguments() != null + && invocation.getArguments().length > 2 + && invocation.getArguments()[2] instanceof Object[]) { return (Object[]) invocation.getArguments()[2]; } return invocation.getArguments(); @@ -140,9 +141,9 @@ public class RpcUtils { public static Class[] getParameterTypes(Invocation invocation) { if ($INVOKE.equals(invocation.getMethodName()) - && invocation.getArguments() != null - && invocation.getArguments().length > 1 - && invocation.getArguments()[1] instanceof String[]) { + && invocation.getArguments() != null + && invocation.getArguments().length > 1 + && invocation.getArguments()[1] instanceof String[]) { String[] types = (String[]) invocation.getArguments()[1]; if (types == null) { return new Class[0]; @@ -228,7 +229,7 @@ public class RpcUtils { private static Method getMethodByService(Invocation invocation, String service) throws NoSuchMethodException { Class invokerInterface = invocation.getInvoker().getInterface(); Class cls = invokerInterface != null ? ReflectUtils.forName(invokerInterface.getClassLoader(), service) - : ReflectUtils.forName(service); + : ReflectUtils.forName(service); Method method = cls.getMethod(invocation.getMethodName(), invocation.getParameterTypes()); if (method.getReturnType() == void.class) { return null; @@ -239,7 +240,7 @@ public class RpcUtils { public static long getTimeout(Invocation invocation, long defaultTimeout) { long timeout = defaultTimeout; Object genericTimeout = invocation.getObjectAttachmentWithoutConvert(TIMEOUT_ATTACHMENT_KEY); - if(genericTimeout == null) { + if (genericTimeout == null) { genericTimeout = invocation.getObjectAttachmentWithoutConvert(TIMEOUT_ATTACHMENT_KEY_LOWER); } if (genericTimeout != null) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExceptionFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExceptionFilterTest.java index 9544369ba3..0f496cdf22 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExceptionFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExceptionFilterTest.java @@ -17,6 +17,7 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.support.FailsafeErrorTypeAwareLogger; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invoker; @@ -30,8 +31,8 @@ import org.apache.dubbo.rpc.support.LocalException; import com.alibaba.com.caucho.hessian.HessianException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import org.mockito.Mockito; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -46,7 +47,8 @@ public class ExceptionFilterTest { @SuppressWarnings("unchecked") @Test public void testRpcException() { - Logger logger = mock(Logger.class); + Logger failLogger = mock(Logger.class); + FailsafeErrorTypeAwareLogger failsafeLogger = new FailsafeErrorTypeAwareLogger(failLogger); RpcContext.getServiceContext().setRemoteAddress("127.0.0.1", 1234); RpcException exception = new RpcException("TestRpcException"); @@ -60,13 +62,13 @@ public class ExceptionFilterTest { exceptionFilter.invoke(invoker, invocation); } catch (RpcException e) { assertEquals("TestRpcException", e.getMessage()); - exceptionFilter.setLogger(logger); + exceptionFilter.setLogger(failsafeLogger); exceptionFilter.onError(e, invoker, invocation); } - Mockito.verify(logger).error(eq("Got unchecked and undeclared exception which called by 127.0.0.1. service: " - + DemoService.class.getName() + ", method: sayHello, exception: " - + RpcException.class.getName() + ": TestRpcException"), eq(exception)); + failsafeLogger.error(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", eq("Got unchecked and undeclared exception which called by 127.0.0.1. service: " + + DemoService.class.getName() + ", method: sayHello, exception: " + + RpcException.class.getName() + ": TestRpcException"), eq(exception)); RpcContext.removeContext(); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilterTest.java index 4a8ba537eb..2f0f3b5faf 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilterTest.java @@ -22,6 +22,7 @@ import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; +import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.RpcStatus; import org.apache.dubbo.rpc.support.BlockMyInvoker; @@ -36,12 +37,12 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; -public class ExecuteLimitFilterTest { +class ExecuteLimitFilterTest { private ExecuteLimitFilter executeLimitFilter = new ExecuteLimitFilter(); @Test - public void testNoExecuteLimitInvoke() throws Exception { + void testNoExecuteLimitInvoke() { Invoker invoker = Mockito.mock(Invoker.class); when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result")); when(invoker.getUrl()).thenReturn(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1")); @@ -54,7 +55,7 @@ public class ExecuteLimitFilterTest { } @Test - public void testExecuteLimitInvoke() throws Exception { + void testExecuteLimitInvoke() { Invoker invoker = Mockito.mock(Invoker.class); when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result")); when(invoker.getUrl()).thenReturn(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&executes=10")); @@ -67,7 +68,7 @@ public class ExecuteLimitFilterTest { } @Test - public void testExecuteLimitInvokeWitException() throws Exception { + void testExecuteLimitInvokeWithException() { Invoker invoker = Mockito.mock(Invoker.class); doThrow(new RpcException()) .when(invoker).invoke(any(Invocation.class)); @@ -89,43 +90,44 @@ public class ExecuteLimitFilterTest { } @Test - public void testMoreThanExecuteLimitInvoke() throws Exception { + void testMoreThanExecuteLimitInvoke() { int maxExecute = 10; int totalExecute = 20; final AtomicInteger failed = new AtomicInteger(0); - final Invocation invocation = Mockito.mock(Invocation.class); + final Invocation invocation = Mockito.mock(RpcInvocation.class); when(invocation.getMethodName()).thenReturn("testMoreThanExecuteLimitInvoke"); URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&executes=" + maxExecute); - final Invoker invoker = new BlockMyInvoker(url, 1000); + final Invoker invoker = new BlockMyInvoker<>(url, 1000); + + final CountDownLatch latchThatWaitsAllThreadStarted = new CountDownLatch(1); + final CountDownLatch latchThatWaitsAllThreadFinished = new CountDownLatch(totalExecute); - final CountDownLatch latch = new CountDownLatch(1); for (int i = 0; i < totalExecute; i++) { - Thread thread = new Thread(new Runnable() { - - public void run() { - try { - latch.await(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - try { - executeLimitFilter.invoke(invoker, invocation); - } catch (RpcException expected) { - failed.incrementAndGet(); - } + Thread thread = new Thread(() -> { + try { + latchThatWaitsAllThreadStarted.await(); + executeLimitFilter.invoke(invoker, invocation); + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (RpcException expected) { + failed.incrementAndGet(); + } finally { + latchThatWaitsAllThreadFinished.countDown(); } }); + thread.start(); } - latch.countDown(); + + latchThatWaitsAllThreadStarted.countDown(); try { - Thread.sleep(1000); + latchThatWaitsAllThreadFinished.await(); } catch (InterruptedException e) { - e.printStackTrace(); + throw new RuntimeException(e); } Assertions.assertEquals(totalExecute - maxExecute, failed.get()); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java index c950d135bc..b944a8311a 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java @@ -18,7 +18,7 @@ package org.apache.dubbo.rpc.protocol.dubbo; import org.apache.dubbo.common.BaseServiceMetadata; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.ClassUtils; @@ -52,6 +52,9 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DESTROY_INVOKER; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_LOAD_MODEL; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_INCORRECT_PARAMETER_VALUES; import static org.apache.dubbo.rpc.Constants.IS_SERVER_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_PROXY_KEY; @@ -62,7 +65,7 @@ import static org.apache.dubbo.rpc.protocol.dubbo.Constants.IS_CALLBACK_SERVICE; * callback service helper */ public class CallbackServiceCodec { - private static final Logger logger = LoggerFactory.getLogger(CallbackServiceCodec.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CallbackServiceCodec.class); private static final byte CALLBACK_NONE = 0x0; private static final byte CALLBACK_CREATE = 0x1; @@ -149,7 +152,7 @@ public class CallbackServiceCodec { if (inv.getServiceModel() == null) { //TODO should get scope model from url? moduleModel = ApplicationModel.defaultModel().getDefaultModule(); - logger.error("Unable to get Service Model from Invocation. Please check if your invocation failed! " + + logger.error(PROTOCOL_FAILED_LOAD_MODEL, "", "", "Unable to get Service Model from Invocation. Please check if your invocation failed! " + "This error only happen in UT cases! Invocation:" + inv); } else { moduleModel = inv.getServiceModel().getModuleModel(); @@ -229,7 +232,7 @@ public class CallbackServiceCodec { } invoker.destroy(); } catch (Exception e) { - logger.error(e.getMessage(), e); + logger.error(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", e.getMessage(), e); } // cancel refer, directly remove from the map channel.removeAttribute(proxyCacheKey); @@ -283,7 +286,7 @@ public class CallbackServiceCodec { } channel.setAttribute(countkey, count); } catch (Exception e) { - logger.error(e.getMessage(), e); + logger.error(PROTOCOL_INCORRECT_PARAMETER_VALUES, "", "", e.getMessage(), e); } } @@ -297,7 +300,7 @@ public class CallbackServiceCodec { } channel.setAttribute(countkey, count); } catch (Exception e) { - logger.error(e.getMessage(), e); + logger.error(PROTOCOL_INCORRECT_PARAMETER_VALUES, "", "", e.getMessage(), e); } } @@ -337,7 +340,7 @@ public class CallbackServiceCodec { try { return referOrDestroyCallbackService(channel, url, pts[paraIndex], inv, Integer.parseInt(inv.getAttachment(INV_ATT_CALLBACK_KEY + paraIndex)), true); } catch (Exception e) { - logger.error(e.getMessage(), e); + logger.error(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", e.getMessage(), e); throw new IOException(StringUtils.toString(e)); } case CallbackServiceCodec.CALLBACK_DESTROY: diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java index 700687e881..482505ff9d 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.protocol.dubbo; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.Cleanable; import org.apache.dubbo.common.serialize.ObjectInput; @@ -52,12 +52,13 @@ import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KE import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DECODE; import static org.apache.dubbo.rpc.Constants.SERIALIZATION_ID_KEY; import static org.apache.dubbo.rpc.Constants.SERIALIZATION_SECURITY_CHECK_KEY; public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Decodeable { - private static final Logger log = LoggerFactory.getLogger(DecodeableRpcInvocation.class); + private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(DecodeableRpcInvocation.class); private Channel channel; @@ -92,7 +93,7 @@ public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Dec decode(channel, inputStream); } catch (Throwable e) { if (log.isWarnEnabled()) { - log.warn("Decode rpc invocation failed: " + e.getMessage(), e); + log.warn(PROTOCOL_FAILED_DECODE, "", "", "Decode rpc invocation failed: " + e.getMessage(), e); } request.setBroken(true); request.setData(e); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java index e95cc2f56b..1b0e748fe3 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java @@ -18,7 +18,7 @@ package org.apache.dubbo.rpc.protocol.dubbo; import org.apache.dubbo.common.config.Configuration; import org.apache.dubbo.common.config.ConfigurationUtils; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.Cleanable; import org.apache.dubbo.common.serialize.ObjectInput; @@ -40,12 +40,13 @@ import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Type; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DECODE; import static org.apache.dubbo.rpc.Constants.SERIALIZATION_ID_KEY; import static org.apache.dubbo.rpc.Constants.SERIALIZATION_SECURITY_CHECK_KEY; public class DecodeableRpcResult extends AppResponse implements Codec, Decodeable { - private static final Logger log = LoggerFactory.getLogger(DecodeableRpcResult.class); + private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(DecodeableRpcResult.class); private Channel channel; @@ -138,7 +139,7 @@ public class DecodeableRpcResult extends AppResponse implements Codec, Decodeabl decode(channel, inputStream); } catch (Throwable e) { if (log.isWarnEnabled()) { - log.warn("Decode rpc result failed: " + e.getMessage(), e); + log.warn(PROTOCOL_FAILED_DECODE, "", "", "Decode rpc result failed: " + e.getMessage(), e); } response.setStatus(Response.CLIENT_ERROR); response.setErrorMessage(StringUtils.toString(e)); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java index 43d4db8ec3..62f59539d5 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java @@ -19,7 +19,7 @@ package org.apache.dubbo.rpc.protocol.dubbo; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.io.Bytes; import org.apache.dubbo.common.io.UnsafeByteArrayInputStream; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -46,6 +46,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEM import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DECODE; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.DECODE_IN_IO_THREAD_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.DEFAULT_DECODE_IN_IO_THREAD; @@ -64,7 +65,7 @@ public class DubboCodec extends ExchangeCodec { public static final byte RESPONSE_NULL_VALUE_WITH_ATTACHMENTS = 5; public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; public static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; - private static final Logger log = LoggerFactory.getLogger(DubboCodec.class); + private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(DubboCodec.class); private CallbackServiceCodec callbackServiceCodec; private FrameworkModel frameworkModel; @@ -103,12 +104,12 @@ public class DubboCodec extends ExchangeCodec { DecodeableRpcResult result; if (channel.getUrl().getParameter(DECODE_IN_IO_THREAD_KEY, DEFAULT_DECODE_IN_IO_THREAD)) { result = new DecodeableRpcResult(channel, res, is, - (Invocation) getRequestData(id), proto); + (Invocation) getRequestData(id), proto); result.decode(); } else { result = new DecodeableRpcResult(channel, res, - new UnsafeByteArrayInputStream(readMessageData(is)), - (Invocation) getRequestData(id), proto); + new UnsafeByteArrayInputStream(readMessageData(is)), + (Invocation) getRequestData(id), proto); } data = result; } @@ -119,7 +120,7 @@ public class DubboCodec extends ExchangeCodec { } } catch (Throwable t) { if (log.isWarnEnabled()) { - log.warn("Decode response failed: " + t.getMessage(), t); + log.warn(PROTOCOL_FAILED_DECODE, "", "", "Decode response failed: " + t.getMessage(), t); } res.setStatus(Response.CLIENT_ERROR); res.setErrorMessage(StringUtils.toString(t)); @@ -151,7 +152,7 @@ public class DubboCodec extends ExchangeCodec { inv.decode(); } else { inv = new DecodeableRpcInvocation(frameworkModel, channel, req, - new UnsafeByteArrayInputStream(readMessageData(is)), proto); + new UnsafeByteArrayInputStream(readMessageData(is)), proto); } data = inv; } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java index 9c426419bf..3fe1cddfe0 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java @@ -52,6 +52,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_ATTACHME import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIME_COUNTDOWN_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** @@ -181,7 +182,7 @@ public class DubboInvoker extends AbstractInvoker { client.close(serverShutdownTimeout); } } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", t.getMessage(), t); } } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java index c4e238c38d..7952143f62 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -66,6 +66,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.LAZY_CONNECT_KEY import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.STUB_EVENT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_SERVER; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REFER_INVOKER; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNSUPPORTED; import static org.apache.dubbo.remoting.Constants.CHANNEL_READONLYEVENT_SENT_KEY; import static org.apache.dubbo.remoting.Constants.CLIENT_KEY; import static org.apache.dubbo.remoting.Constants.CODEC_KEY; @@ -141,7 +145,7 @@ public class DubboProtocol extends AbstractProtocol { } } if (!hasMethod) { - logger.warn(new IllegalStateException("The methodName " + inv.getMethodName() + logger.warn(PROTOCOL_FAILED_REFER_INVOKER, "", "", new IllegalStateException("The methodName " + inv.getMethodName() + " not found in callback service interface ,invoke will be ignored." + " please update the api interface. url is:" + invoker.getUrl()) + " ,invocation is :" + inv); @@ -185,7 +189,7 @@ public class DubboProtocol extends AbstractProtocol { } received(channel, invocation); } catch (Throwable t) { - logger.warn("Failed to invoke event method " + invocation.getMethodName() + "(), cause: " + t.getMessage(), t); + logger.warn(PROTOCOL_FAILED_REFER_INVOKER, "", "", "Failed to invoke event method " + invocation.getMethodName() + "(), cause: " + t.getMessage(), t); } } } @@ -316,8 +320,8 @@ public class DubboProtocol extends AbstractProtocol { String stubServiceMethods = url.getParameter(STUB_EVENT_METHODS_KEY); if (stubServiceMethods == null || stubServiceMethods.length() == 0) { if (logger.isWarnEnabled()) { - logger.warn(new IllegalStateException("consumer [" + url.getParameter(INTERFACE_KEY) + - "], has set stub proxy support event ,but no stub methods founded.")); + logger.warn(PROTOCOL_UNSUPPORTED, "", "", "consumer [" + url.getParameter(INTERFACE_KEY) + + "], has set stub proxy support event ,but no stub methods founded."); } } @@ -636,7 +640,7 @@ public class DubboProtocol extends AbstractProtocol { server.close(getServerShutdownTimeout(protocolServer)); } catch (Throwable t) { - logger.warn("Close dubbo server [" + server.getLocalAddress() + "] failed: " + t.getMessage(), t); + logger.warn(PROTOCOL_ERROR_CLOSE_SERVER, "", "", "Close dubbo server [" + server.getLocalAddress() + "] failed: " + t.getMessage(), t); } } serverMap.clear(); @@ -685,7 +689,7 @@ public class DubboProtocol extends AbstractProtocol { */ } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", t.getMessage(), t); } } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java index 7e2d5332c8..7454df2b8f 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java @@ -18,7 +18,7 @@ package org.apache.dubbo.rpc.protocol.dubbo; import org.apache.dubbo.common.Parameters; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.ChannelHandler; @@ -36,6 +36,7 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import static org.apache.dubbo.common.constants.CommonConstants.LAZY_CONNECT_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; import static org.apache.dubbo.remoting.Constants.SEND_RECONNECT_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.DEFAULT_LAZY_REQUEST_WITH_WARNING; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.LAZY_REQUEST_WITH_WARNING_KEY; @@ -46,7 +47,7 @@ import static org.apache.dubbo.rpc.protocol.dubbo.Constants.LAZY_REQUEST_WITH_WA @SuppressWarnings("deprecation") final class LazyConnectExchangeClient implements ExchangeClient { - private final static Logger logger = LoggerFactory.getLogger(LazyConnectExchangeClient.class); + private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(LazyConnectExchangeClient.class); private final boolean requestWithWarning; private final URL url; private final ExchangeHandler requestHandler; @@ -130,7 +131,7 @@ final class LazyConnectExchangeClient implements ExchangeClient { private void warning() { if (requestWithWarning) { if (warningCount.get() % warningPeriod == 0) { - logger.warn(url.getAddress() + " " + url.getServiceKey() + " safe guard client , should not be called ,must have a bug."); + logger.warn(PROTOCOL_FAILED_REQUEST, "", "", url.getAddress() + " " + url.getServiceKey() + " safe guard client , should not be called ,must have a bug."); } warningCount.incrementAndGet(); } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java index b0a8f08e2f..18eeceb2b0 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java @@ -19,7 +19,7 @@ package org.apache.dubbo.rpc.protocol.dubbo; import org.apache.dubbo.common.Parameters; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; @@ -32,6 +32,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; /** * dubbo protocol support class. @@ -39,7 +40,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_S @SuppressWarnings("deprecation") final class ReferenceCountExchangeClient implements ExchangeClient { - private final static Logger logger = LoggerFactory.getLogger(ReferenceCountExchangeClient.class); + private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReferenceCountExchangeClient.class); private final URL url; private final AtomicInteger referenceCount = new AtomicInteger(0); private final AtomicInteger disconnectCount = new AtomicInteger(0); @@ -199,7 +200,7 @@ final class ReferenceCountExchangeClient implements ExchangeClient { private void replaceWithLazyClient() { // start warning at second replaceWithLazyClient() if (disconnectCount.getAndIncrement() % warningPeriod == 1) { - logger.warn(url.getAddress() + " " + url.getServiceKey() + " safe guard client , should not be called ,must have a bug."); + logger.warn(PROTOCOL_FAILED_REQUEST, "", "", url.getAddress() + " " + url.getServiceKey() + " safe guard client , should not be called ,must have a bug."); } // the order of judgment in the if statement cannot be changed. diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java index 9d9e205316..b35e00d8d9 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java @@ -18,7 +18,7 @@ package org.apache.dubbo.rpc.protocol.dubbo.filter; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -33,6 +33,7 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.ASYNC_METHOD_INFO; /** @@ -41,7 +42,7 @@ import static org.apache.dubbo.rpc.protocol.dubbo.Constants.ASYNC_METHOD_INFO; @Activate(group = CommonConstants.CONSUMER) public class FutureFilter implements ClusterFilter, ClusterFilter.Listener { - protected static final Logger logger = LoggerFactory.getLogger(FutureFilter.class); + protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FutureFilter.class); @Override public Result invoke(final Invoker invoker, final Invocation invocation) throws RpcException { @@ -179,10 +180,10 @@ public class FutureFilter implements ClusterFilter, ClusterFilter.Listener { } onthrowMethod.invoke(onthrowInst, params); } catch (Throwable e) { - logger.error(invocation.getMethodName() + ".call back method invoke error . callback method :" + onthrowMethod + ", url:" + invoker.getUrl(), e); + logger.error(PROTOCOL_FAILED_REQUEST, "", "", invocation.getMethodName() + ".call back method invoke error . callback method :" + onthrowMethod + ", url:" + invoker.getUrl(), e); } } else { - logger.error(invocation.getMethodName() + ".call back method invoke error . callback method :" + onthrowMethod + ", url:" + invoker.getUrl(), exception); + logger.error(PROTOCOL_FAILED_REQUEST, "", "", invocation.getMethodName() + ".call back method invoke error . callback method :" + onthrowMethod + ", url:" + invoker.getUrl(), exception); } } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java index 3247436179..3bf847dd6d 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java @@ -18,7 +18,7 @@ package org.apache.dubbo.rpc.protocol.dubbo.filter; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashSet; @@ -39,13 +39,15 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_PARSE; + /** * TraceFilter */ @Activate(group = CommonConstants.PROVIDER) public class TraceFilter implements Filter { - private static final Logger logger = LoggerFactory.getLogger(TraceFilter.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TraceFilter.class); private static final String TRACE_MAX = "trace.max"; @@ -113,7 +115,7 @@ public class TraceFilter implements Filter { } } catch (Throwable e) { channels.remove(channel); - logger.warn(e.getMessage(), e); + logger.warn(PROTOCOL_FAILED_PARSE, "", "", e.getMessage(), e); } } else { channels.remove(channel); diff --git a/dubbo-rpc/dubbo-rpc-grpc/src/main/java/org/apache/dubbo/rpc/protocol/grpc/GrpcOptionsUtils.java b/dubbo-rpc/dubbo-rpc-grpc/src/main/java/org/apache/dubbo/rpc/protocol/grpc/GrpcOptionsUtils.java index 314d1d7c29..a0685b2da7 100644 --- a/dubbo-rpc/dubbo-rpc-grpc/src/main/java/org/apache/dubbo/rpc/protocol/grpc/GrpcOptionsUtils.java +++ b/dubbo-rpc/dubbo-rpc-grpc/src/main/java/org/apache/dubbo/rpc/protocol/grpc/GrpcOptionsUtils.java @@ -18,7 +18,7 @@ package org.apache.dubbo.rpc.protocol.grpc; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.ThreadPool; import org.apache.dubbo.common.utils.CollectionUtils; @@ -50,6 +50,7 @@ import java.util.Set; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.SSL_ENABLED_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_CLOSE_STREAM; import static org.apache.dubbo.remoting.Constants.DISPATCHER_KEY; import static org.apache.dubbo.rpc.Constants.EXECUTES_KEY; import static org.apache.dubbo.rpc.protocol.grpc.GrpcConstants.CLIENT_INTERCEPTORS; @@ -65,7 +66,7 @@ import static org.apache.dubbo.rpc.protocol.grpc.GrpcConstants.TRANSPORT_FILTERS */ public class GrpcOptionsUtils { - private static final Logger logger = LoggerFactory.getLogger(GrpcOptionsUtils.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(GrpcOptionsUtils.class); static ServerBuilder buildServerBuilder(URL url, NettyServerBuilder builder) { @@ -95,14 +96,14 @@ public class GrpcOptionsUtils { // server interceptors List serverInterceptors = url.getOrDefaultFrameworkModel().getExtensionLoader(ServerInterceptor.class) - .getActivateExtension(url, SERVER_INTERCEPTORS, PROVIDER_SIDE); + .getActivateExtension(url, SERVER_INTERCEPTORS, PROVIDER_SIDE); for (ServerInterceptor serverInterceptor : serverInterceptors) { builder.intercept(serverInterceptor); } // server filters List transportFilters = url.getOrDefaultFrameworkModel().getExtensionLoader(ServerTransportFilter.class) - .getActivateExtension(url, TRANSPORT_FILTERS, PROVIDER_SIDE); + .getActivateExtension(url, TRANSPORT_FILTERS, PROVIDER_SIDE); for (ServerTransportFilter transportFilter : transportFilters) { builder.addTransportFilter(transportFilter.grpcTransportFilter()); } @@ -116,8 +117,8 @@ public class GrpcOptionsUtils { // Give users the chance to customize ServerBuilder return getConfigurator() - .map(configurator -> configurator.configureServerBuilder(builder, url)) - .orElse(builder); + .map(configurator -> configurator.configureServerBuilder(builder, url)) + .orElse(builder); } static ManagedChannel buildManagedChannel(URL url) { @@ -135,15 +136,15 @@ public class GrpcOptionsUtils { // client interceptors List interceptors = new ArrayList<>( url.getOrDefaultFrameworkModel().getExtensionLoader(ClientInterceptor.class) - .getActivateExtension(url, CLIENT_INTERCEPTORS, CONSUMER_SIDE) + .getActivateExtension(url, CLIENT_INTERCEPTORS, CONSUMER_SIDE) ); builder.intercept(interceptors); return getConfigurator() - .map(configurator -> configurator.configureChannelBuilder(builder, url)) - .orElse(builder) - .build(); + .map(configurator -> configurator.configureChannelBuilder(builder, url)) + .orElse(builder) + .build(); } static CallOptions buildCallOptions(URL url) { @@ -152,8 +153,8 @@ public class GrpcOptionsUtils { // .withDeadline(Deadline.after(url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT), TimeUnit.MILLISECONDS)); CallOptions callOptions = CallOptions.DEFAULT; return getConfigurator() - .map(configurator -> configurator.configureCallOptions(callOptions, url)) - .orElse(callOptions); + .map(configurator -> configurator.configureCallOptions(callOptions, url)) + .orElse(callOptions); } private static SslContext buildServerSslContext(URL url) { @@ -236,7 +237,7 @@ public class GrpcOptionsUtils { private static Optional getConfigurator() { // Give users the chance to customize ServerBuilder Set configurators = ExtensionLoader.getExtensionLoader(GrpcConfigurator.class) - .getSupportedExtensionInstances(); + .getSupportedExtensionInstances(); if (CollectionUtils.isNotEmpty(configurators)) { return Optional.of(configurators.iterator().next()); } @@ -250,7 +251,7 @@ public class GrpcOptionsUtils { try { stream.close(); } catch (IOException e) { - logger.warn("Failed to close a stream.", e); + logger.warn(PROTOCOL_FAILED_CLOSE_STREAM, "", "", "Failed to close a stream.", e); } } } diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/DefaultParamDeepCopyUtil.java b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/DefaultParamDeepCopyUtil.java index 7ff20aadc8..c02bdd34f9 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/DefaultParamDeepCopyUtil.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/DefaultParamDeepCopyUtil.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.protocol.injvm; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -28,8 +28,10 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_DESERIALIZE; + public class DefaultParamDeepCopyUtil implements ParamDeepCopyUtil { - private static final Logger logger = LoggerFactory.getLogger(DefaultParamDeepCopyUtil.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultParamDeepCopyUtil.class); public final static String NAME = "default"; @@ -48,11 +50,11 @@ public class DefaultParamDeepCopyUtil implements ParamDeepCopyUtil { ObjectInput objectInput = serialization.deserialize(url, inputStream); return objectInput.readObject(targetClass); } catch (ClassNotFoundException | IOException e) { - logger.error("Unable to deep copy parameter to target class.", e); + logger.error(PROTOCOL_ERROR_DESERIALIZE, "", "", "Unable to deep copy parameter to target class.", e); } } catch (Throwable e) { - logger.error("Unable to deep copy parameter to target class.", e); + logger.error(PROTOCOL_ERROR_DESERIALIZE, "", "", "Unable to deep copy parameter to target class.", e); } diff --git a/dubbo-rpc/dubbo-rpc-rest/pom.xml b/dubbo-rpc/dubbo-rpc-rest/pom.xml index c8fc01ae50..25127469be 100644 --- a/dubbo-rpc/dubbo-rpc-rest/pom.xml +++ b/dubbo-rpc/dubbo-rpc-rest/pom.xml @@ -83,11 +83,6 @@ resteasy-jaxb-provider - - io.netty - netty-all - - io.swagger diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ReferenceCountedClient.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ReferenceCountedClient.java index e3c15debe4..393a6d6c34 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ReferenceCountedClient.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ReferenceCountedClient.java @@ -16,14 +16,16 @@ */ package org.apache.dubbo.rpc.protocol.rest; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.reference.ReferenceCountedResource; import org.jboss.resteasy.client.jaxrs.ResteasyClient; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT; + public class ReferenceCountedClient extends ReferenceCountedResource { - private static final Logger logger = LoggerFactory.getLogger(ReferenceCountedClient.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReferenceCountedClient.class); private final ResteasyClient resteasyClient; @@ -44,7 +46,7 @@ public class ReferenceCountedClient extends ReferenceCountedResource { try { resteasyClient.close(); } catch (Exception e) { - logger.error("Close resteasy client error", e); + logger.error(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", "Close resteasy client error", e); } } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java index 267fcb18f0..f38b0139c0 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java @@ -51,6 +51,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATT import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_SERVER; import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY; import static org.apache.dubbo.remoting.Constants.CONNECT_TIMEOUT_KEY; import static org.apache.dubbo.remoting.Constants.DEFAULT_CONNECT_TIMEOUT; @@ -103,14 +105,14 @@ public class RestProtocol extends AbstractProxyProtocol { ServletContext servletContext = ServletManager.getInstance().getServletContext(ServletManager.EXTERNAL_SERVER_PORT); if (servletContext == null) { throw new RpcException("No servlet context found. Since you are using server='servlet', " + - "make sure that you've configured " + BootstrapListener.class.getName() + " in web.xml"); + "make sure that you've configured " + BootstrapListener.class.getName() + " in web.xml"); } String webappPath = servletContext.getContextPath(); if (StringUtils.isNotEmpty(webappPath)) { webappPath = webappPath.substring(1); if (!contextPath.startsWith(webappPath)) { throw new RpcException("Since you are using server='servlet', " + - "make sure that the 'contextpath' property starts with the path of external webapp"); + "make sure that the 'contextpath' property starts with the path of external webapp"); } contextPath = contextPath.substring(webappPath.length()); if (contextPath.startsWith("/")) { @@ -230,7 +232,7 @@ public class RestProtocol extends AbstractProxyProtocol { } entry.getValue().close(); } catch (Throwable t) { - logger.warn("Error closing rest server", t); + logger.warn(PROTOCOL_ERROR_CLOSE_SERVER, "", "", "Error closing rest server", t); } } serverMap.clear(); @@ -243,7 +245,7 @@ public class RestProtocol extends AbstractProxyProtocol { // destroy directly regardless of the current reference count. client.destroy(); } catch (Throwable t) { - logger.warn("Error closing rest client", t); + logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", "Error closing rest client", t); } } clients.clear(); @@ -280,7 +282,7 @@ public class RestProtocol extends AbstractProxyProtocol { connectionMonitor.destroyManager(url); } } catch (Exception e) { - logger.warn("Failed to close unused resources in rest protocol. interfaceName [" + url.getServiceInterface() + "]", e); + logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", "Failed to close unused resources in rest protocol. interfaceName [" + url.getServiceInterface() + "]", e); } } diff --git a/dubbo-rpc/dubbo-rpc-triple/pom.xml b/dubbo-rpc/dubbo-rpc-triple/pom.xml index 17f141a845..eeca0e6937 100644 --- a/dubbo-rpc/dubbo-rpc-triple/pom.xml +++ b/dubbo-rpc/dubbo-rpc-triple/pom.xml @@ -45,6 +45,10 @@ ${project.parent.version} test + + io.netty + netty-codec-http2 + com.google.protobuf protobuf-java diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/StatusRpcException.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/StatusRpcException.java similarity index 100% rename from dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/StatusRpcException.java rename to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/StatusRpcException.java diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/TriRpcStatus.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/TriRpcStatus.java similarity index 95% rename from dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/TriRpcStatus.java rename to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/TriRpcStatus.java index 61540b78ea..11a250bcaf 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/TriRpcStatus.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/TriRpcStatus.java @@ -83,7 +83,7 @@ public class TriRpcStatus { return new TriRpcStatus(code, throwable, description); } if (throwable instanceof TimeoutException) { - return new TriRpcStatus(TriRpcStatus.Code.DEADLINE_EXCEEDED, throwable, description); + return new TriRpcStatus(Code.DEADLINE_EXCEEDED, throwable, description); } return new TriRpcStatus(Code.UNKNOWN, throwable, description); } @@ -165,27 +165,27 @@ public class TriRpcStatus { return encoder.toString().substring(2); } - public static TriRpcStatus.Code httpStatusToGrpcCode(int httpStatusCode) { + public static Code httpStatusToGrpcCode(int httpStatusCode) { if (httpStatusCode >= 100 && httpStatusCode < 200) { - return TriRpcStatus.Code.INTERNAL; + return Code.INTERNAL; } if (httpStatusCode == HttpResponseStatus.BAD_REQUEST.code() || httpStatusCode == HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LARGE.code() ) { - return TriRpcStatus.Code.INTERNAL; + return Code.INTERNAL; } else if (httpStatusCode == HttpResponseStatus.UNAUTHORIZED.code()) { - return TriRpcStatus.Code.UNAUTHENTICATED; + return Code.UNAUTHENTICATED; } else if (httpStatusCode == HttpResponseStatus.FORBIDDEN.code()) { - return TriRpcStatus.Code.PERMISSION_DENIED; + return Code.PERMISSION_DENIED; } else if (httpStatusCode == HttpResponseStatus.NOT_FOUND.code()) { - return TriRpcStatus.Code.UNIMPLEMENTED; + return Code.UNIMPLEMENTED; } else if (httpStatusCode == HttpResponseStatus.BAD_GATEWAY.code() || httpStatusCode == HttpResponseStatus.TOO_MANY_REQUESTS.code() || httpStatusCode == HttpResponseStatus.SERVICE_UNAVAILABLE.code() || httpStatusCode == HttpResponseStatus.GATEWAY_TIMEOUT.code()) { return Code.UNAVAILABLE; } else { - return TriRpcStatus.Code.UNKNOWN; + return Code.UNKNOWN; } } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleInvoker.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleInvoker.java index 6b352bfcf6..07b5a61ff4 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleInvoker.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleInvoker.java @@ -19,7 +19,7 @@ package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.remoting.api.Connection; @@ -66,6 +66,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_ATTACHMENT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIME_COUNTDOWN_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DESTROY_INVOKER; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** @@ -73,7 +75,7 @@ import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; */ public class TripleInvoker extends AbstractInvoker { - private static final Logger LOGGER = LoggerFactory.getLogger(TripleInvoker.class); + private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(TripleInvoker.class); private final Connection connection; @@ -84,11 +86,11 @@ public class TripleInvoker extends AbstractInvoker { private final TripleWriteQueue writeQueue = new TripleWriteQueue(); public TripleInvoker(Class serviceType, - URL url, - String acceptEncodings, - ConnectionManager connectionManager, - Set> invokers, - ExecutorService streamExecutor) { + URL url, + String acceptEncodings, + ConnectionManager connectionManager, + Set> invokers, + ExecutorService streamExecutor) { super(serviceType, url, new String[]{INTERFACE_KEY, GROUP_KEY, TOKEN_KEY}); this.invokers = invokers; this.connection = connectionManager.connect(url); @@ -106,7 +108,7 @@ public class TripleInvoker extends AbstractInvoker { if (!connection.isAvailable()) { CompletableFuture future = new CompletableFuture<>(); RpcException exception = TriRpcStatus.UNAVAILABLE.withDescription( - String.format("upstream %s is unavailable", getUrl().getAddress())) + String.format("upstream %s is unavailable", getUrl().getAddress())) .asException(); future.completeExceptionally(exception); return new AsyncRpcResult(future, invocation); @@ -145,7 +147,7 @@ public class TripleInvoker extends AbstractInvoker { try { call.cancelByLocal(e); } catch (Throwable t1) { - LOGGER.error("Cancel triple request failed", t1); + LOGGER.error(PROTOCOL_FAILED_REQUEST, "", "", "Cancel triple request failed", t1); } CompletableFuture future = new CompletableFuture<>(); future.completeExceptionally(e); @@ -154,7 +156,7 @@ public class TripleInvoker extends AbstractInvoker { } AsyncRpcResult invokeServerStream(MethodDescriptor methodDescriptor, Invocation invocation, - ClientCall call) { + ClientCall call) { RequestMetadata request = createRequest(methodDescriptor, invocation, null); StreamObserver responseObserver = (StreamObserver) invocation.getArguments()[1]; final StreamObserver requestObserver = streamCall(call, request, responseObserver); @@ -164,7 +166,7 @@ public class TripleInvoker extends AbstractInvoker { } AsyncRpcResult invokeBiOrClientStream(MethodDescriptor methodDescriptor, Invocation invocation, - ClientCall call) { + ClientCall call) { final AsyncRpcResult result; RequestMetadata request = createRequest(methodDescriptor, invocation, null); StreamObserver responseObserver = (StreamObserver) invocation.getArguments()[0]; @@ -175,8 +177,8 @@ public class TripleInvoker extends AbstractInvoker { } StreamObserver streamCall(ClientCall call, - RequestMetadata metadata, - StreamObserver responseObserver) { + RequestMetadata metadata, + StreamObserver responseObserver) { ObserverToClientCallListenerAdapter listener = new ObserverToClientCallListenerAdapter( responseObserver); StreamObserver streamObserver = call.start(metadata, listener); @@ -192,7 +194,7 @@ public class TripleInvoker extends AbstractInvoker { } AsyncRpcResult invokeUnary(MethodDescriptor methodDescriptor, Invocation invocation, - ClientCall call) { + ClientCall call) { ExecutorService callbackExecutor = getCallbackExecutor(getUrl(), invocation); int timeout = calculateTimeout(invocation, invocation.getMethodName()); @@ -229,7 +231,7 @@ public class TripleInvoker extends AbstractInvoker { } RequestMetadata createRequest(MethodDescriptor methodDescriptor, Invocation invocation, - Integer timeout) { + Integer timeout) { final String methodName = RpcUtils.getMethodName(invocation); Objects.requireNonNull(methodDescriptor, "MethodDescriptor not found for" + methodName + " params:" + Arrays.toString( @@ -291,7 +293,7 @@ public class TripleInvoker extends AbstractInvoker { try { connection.release(); } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", t.getMessage(), t); } } finally { diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocol.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocol.java index 66f347682c..a03f5fc72b 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocol.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocol.java @@ -75,7 +75,7 @@ public class TripleProtocol extends AbstractProtocol { this.pathResolver = frameworkModel.getExtensionLoader(PathResolver.class) .getDefaultExtension(); CONVERT_NO_LOWER_HEADER = ConfigurationUtils.getEnvConfiguration(ApplicationModel.defaultModel()) - .getBoolean(H2_SUPPORT_NO_LOWER_HEADER_KEY, false); + .getBoolean(H2_SUPPORT_NO_LOWER_HEADER_KEY, true); Set supported = frameworkModel.getExtensionLoader(DeCompressor.class) .getSupportedExtensions(); this.acceptEncodings = String.join(",", supported); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCall.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCall.java index 76b1fb39f7..ca4d849ab4 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCall.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCall.java @@ -18,7 +18,7 @@ package org.apache.dubbo.rpc.protocol.tri.call; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.CancellationContext; @@ -50,10 +50,15 @@ import java.util.Objects; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_CREATE_STREAM_TRIPLE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_PARSE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_SERIALIZE_TRIPLE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; + public abstract class AbstractServerCall implements ServerCall, ServerStream.Listener { public static final String REMOTE_ADDRESS_KEY = "tri.remote.address"; - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractServerCall.class); + private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(AbstractServerCall.class); public final Invoker invoker; public final FrameworkModel frameworkModel; @@ -141,7 +146,7 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis } catch (Throwable e) { close(TriRpcStatus.INTERNAL.withDescription("Serialize response failed") .withCause(e), null); - LOGGER.error(String.format("Serialize triple response failed, service=%s method=%s", + LOGGER.error(PROTOCOL_FAILED_SERIALIZE_TRIPLE,"","",String.format("Serialize triple response failed, service=%s method=%s", serviceName, methodName), e); return; } @@ -183,7 +188,7 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis final TriRpcStatus status = TriRpcStatus.UNKNOWN.withDescription("Server error") .withCause(t); close(status, null); - LOGGER.error("Process request failed. service=" + serviceName + + LOGGER.error(PROTOCOL_FAILED_REQUEST,"","","Process request failed. service=" + serviceName + " method=" + methodName, t); } finally { ClassLoadUtil.switchContextLoader(tccl); @@ -229,7 +234,7 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis this.timeout = parseTimeoutToMills(timeout); } } catch (Throwable t) { - LOGGER.warn(String.format("Failed to parse request timeout set from:%s, service=%s " + LOGGER.warn(PROTOCOL_FAILED_PARSE, "", "", String.format("Failed to parse request timeout set from:%s, service=%s " + "method=%s", timeout, serviceDescriptor.getInterfaceName(), methodName)); } if (null != requestMetadata.get(TripleHeaderEnum.CONSUMER_APP_NAME_KEY.getHeader())) { @@ -348,7 +353,7 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis } closed = true; stream.complete(status, null); - LOGGER.error("Triple request error: service=" + serviceName + " method" + methodName, + LOGGER.error(PROTOCOL_FAILED_REQUEST, "", "", "Triple request error: service=" + serviceName + " method" + methodName, status.asException()); } @@ -383,7 +388,7 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis } return listener; } catch (Throwable t) { - LOGGER.error("Create triple stream failed", t); + LOGGER.error(PROTOCOL_FAILED_CREATE_STREAM_TRIPLE, "", "", "Create triple stream failed", t); responseErr(TriRpcStatus.INTERNAL.withDescription("Create stream failed") .withCause(t)); } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCallListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCallListener.java index 3dc8d46ca9..2c06f35e0b 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCallListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCallListener.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.protocol.tri.call; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.CancellationContext; import org.apache.dubbo.rpc.Invoker; @@ -30,9 +30,11 @@ import org.apache.dubbo.rpc.protocol.tri.observer.ServerCallToObserverAdapter; import java.net.InetSocketAddress; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_TIMEOUT_SERVER; + public abstract class AbstractServerCallListener implements AbstractServerCall.Listener { - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractServerCallListener.class); + private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(AbstractServerCallListener.class); public final CancellationContext cancellationContext; final RpcInvocation invocation; final Invoker invoker; @@ -71,7 +73,7 @@ public abstract class AbstractServerCallListener implements AbstractServerCall.L } final long cost = System.currentTimeMillis() - stInMillis; if (responseObserver.isTimeout(cost)) { - LOGGER.error(String.format( + LOGGER.error(PROTOCOL_TIMEOUT_SERVER, "", "", String.format( "Invoke timeout at server side, ignored to send response. service=%s method=%s cost=%s", invocation.getTargetServiceUniqueName(), invocation.getMethodName(), diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/TripleClientCall.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/TripleClientCall.java index 90db0098c2..6fb731f97d 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/TripleClientCall.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/TripleClientCall.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.protocol.tri.call; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.remoting.api.Connection; @@ -46,9 +46,13 @@ import java.util.List; import java.util.Map; import java.util.concurrent.Executor; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_RESPONSE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_SERIALIZE_TRIPLE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_STREAM_LISTENER; + public class TripleClientCall implements ClientCall, ClientStream.Listener { - private static final Logger LOGGER = LoggerFactory.getLogger(TripleClientCall.class); + private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(TripleClientCall.class); private final Connection connection; private final Executor executor; private final FrameworkModel frameworkModel; @@ -74,7 +78,7 @@ public class TripleClientCall implements ClientCall, ClientStream.Listener { @Override public void onMessage(byte[] message) { if (done) { - LOGGER.warn( + LOGGER.warn(PROTOCOL_STREAM_LISTENER, "", "", "Received message from closed stream,connection=" + connection + " service=" + requestMetadata.service + " method=" + requestMetadata.method.getMethodName()); @@ -86,8 +90,8 @@ public class TripleClientCall implements ClientCall, ClientStream.Listener { } catch (Throwable t) { cancelByLocal(TriRpcStatus.INTERNAL.withDescription("Deserialize response failed") .withCause(t).asException()); - LOGGER.error(String.format("Failed to deserialize triple response, service=%s, method=%s,connection=%s", - connection ,requestMetadata.service, requestMetadata.method.getMethodName()),t); + LOGGER.error(PROTOCOL_FAILED_RESPONSE, "", "", String.format("Failed to deserialize triple response, service=%s, method=%s,connection=%s", + connection, requestMetadata.service, requestMetadata.method.getMethodName()), t); } } @@ -105,7 +109,7 @@ public class TripleClientCall implements ClientCall, ClientStream.Listener { @Override public void onComplete(TriRpcStatus status, Map attachments, - Map excludeHeaders) { + Map excludeHeaders) { if (done) { return; } @@ -177,7 +181,7 @@ public class TripleClientCall implements ClientCall, ClientStream.Listener { // support others type but now only support this } } catch (Throwable t) { - LOGGER.error("tran from grpc-status-details error", t); + LOGGER.error(PROTOCOL_FAILED_RESPONSE, "", "", "tran from grpc-status-details error", t); } return map; } @@ -236,7 +240,7 @@ public class TripleClientCall implements ClientCall, ClientStream.Listener { } }); } catch (Throwable t) { - LOGGER.error(String.format("Serialize triple request failed, service=%s method=%s", + LOGGER.error(PROTOCOL_FAILED_SERIALIZE_TRIPLE, "", "", String.format("Serialize triple request failed, service=%s method=%s", requestMetadata.service, requestMetadata.method), t); cancelByLocal(t); @@ -269,7 +273,7 @@ public class TripleClientCall implements ClientCall, ClientStream.Listener { @Override public StreamObserver start(RequestMetadata metadata, - ClientCall.Listener responseListener) { + ClientCall.Listener responseListener) { this.requestMetadata = metadata; this.listener = responseListener; this.stream = new TripleClientStream(frameworkModel, executor, connection.getChannel(), diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/TriHealthImpl.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/TriHealthImpl.java index 4f22c832e3..c21e78e1af 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/TriHealthImpl.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/TriHealthImpl.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.protocol.tri.service; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.rpc.RpcContext; @@ -32,9 +32,11 @@ import java.util.IdentityHashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_CLOSED_SERVER; + public class TriHealthImpl extends DubboHealthTriple.HealthImplBase { - private static final Logger logger = LoggerFactory.getLogger(TriHealthImpl.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TriHealthImpl.class); // Due to the latency of rpc calls, synchronization of the map does not help with consistency. // However, need use ConcurrentHashMap to allow concurrent reading by check(). @@ -76,7 +78,7 @@ public class TriHealthImpl extends DubboHealthTriple.HealthImplBase { @Override public void watch(HealthCheckRequest request, - StreamObserver responseObserver) { + StreamObserver responseObserver) { final String service = request.getService(); synchronized (watchLock) { HealthCheckResponse.ServingStatus status = statusMap.get(service); @@ -136,7 +138,7 @@ public class TriHealthImpl extends DubboHealthTriple.HealthImplBase { void enterTerminalState() { synchronized (watchLock) { if (terminal) { - logger.warn("Already terminating", new RuntimeException()); + logger.warn(PROTOCOL_CLOSED_SERVER, "", "", "Already terminating", new RuntimeException()); return; } terminal = true; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtils.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtils.java index e0c6f61400..1270f421c4 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtils.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtils.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.protocol.tri.stream; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.rpc.TriRpcStatus; @@ -35,9 +35,11 @@ import java.util.Locale; import java.util.Map; import java.util.stream.Collectors; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNSUPPORTED; + public class StreamUtils { - protected static final Logger LOGGER = LoggerFactory.getLogger(StreamUtils.class); + protected static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(StreamUtils.class); private static final Base64.Decoder BASE64_DECODER = Base64.getDecoder(); private static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder().withoutPadding(); @@ -132,14 +134,13 @@ public class StreamUtils { String str = encodeBase64ASCII((byte[]) v); headers.set(key + TripleConstant.HEADER_BIN_SUFFIX, str); } else { - LOGGER.warn("Unsupported attachment k: " + key + " class: " + v.getClass().getName()); + LOGGER.warn(PROTOCOL_UNSUPPORTED, "", "", "Unsupported attachment k: " + key + " class: " + v.getClass().getName()); } } catch (Throwable t) { - LOGGER.warn("Meet exception when convert single attachment key:" + key + " value=" + v, + LOGGER.warn(PROTOCOL_UNSUPPORTED, "", "", "Meet exception when convert single attachment key:" + key + " value=" + v, t); } } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListener.java index d3bcc86a1b..2cf6caa001 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListener.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.protocol.tri.transport; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.protocol.tri.TripleConstant; import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum; @@ -29,9 +29,11 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_PARSE; + public abstract class AbstractH2TransportListener implements H2TransportListener { - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractH2TransportListener.class); + private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(AbstractH2TransportListener.class); /** * Parse metadata to a KV pairs map. @@ -54,7 +56,7 @@ public abstract class AbstractH2TransportListener implements H2TransportListener byte[] value = StreamUtils.decodeASCIIByte(header.getValue()); attachments.put(realKey, value); } catch (Exception e) { - LOGGER.error("Failed to parse response attachment key=" + key, e); + LOGGER.error(PROTOCOL_FAILED_PARSE, "", "", "Failed to parse response attachment key=" + key, e); } } else { attachments.put(key, header.getValue().toString()); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandler.java index 3fd99be7c6..19b35fd912 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandler.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandler.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.protocol.tri.transport; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.TriRpcStatus; @@ -30,10 +30,12 @@ import io.netty.handler.codec.http2.Http2HeadersFrame; import io.netty.handler.codec.http2.Http2ResetFrame; import io.netty.handler.codec.http2.Http2StreamFrame; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_SERIALIZE_TRIPLE; + public final class TripleHttp2ClientResponseHandler extends SimpleChannelInboundHandler { - private static final Logger LOGGER = LoggerFactory.getLogger( + private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger( TripleHttp2ClientResponseHandler.class); private final H2TransportListener transportListener; @@ -70,7 +72,7 @@ public final class TripleHttp2ClientResponseHandler extends } private void onResetRead(ChannelHandlerContext ctx, Http2ResetFrame resetFrame) { - LOGGER.warn("Triple Client received remote reset errorCode=" + resetFrame.errorCode()); + LOGGER.warn(PROTOCOL_FAILED_SERIALIZE_TRIPLE, "", "", "Triple Client received remote reset errorCode=" + resetFrame.errorCode()); transportListener.cancelByRemote(resetFrame.errorCode()); ctx.close(); } @@ -85,7 +87,7 @@ public final class TripleHttp2ClientResponseHandler extends public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { final TriRpcStatus status = TriRpcStatus.INTERNAL .withCause(cause); - LOGGER.warn("Meet Exception on ClientResponseHandler, status code is: " + status.code, + LOGGER.warn(PROTOCOL_FAILED_SERIALIZE_TRIPLE, "", "", "Meet Exception on ClientResponseHandler, status code is: " + status.code, cause); transportListener.cancelByRemote(Http2Error.INTERNAL_ERROR.code()); ctx.close(); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2FrameServerHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2FrameServerHandler.java index 08595f090b..4b17e82b29 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2FrameServerHandler.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2FrameServerHandler.java @@ -18,7 +18,7 @@ package org.apache.dubbo.rpc.protocol.tri.transport; import io.netty.handler.codec.http2.Http2StreamChannel; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.HeaderFilter; import org.apache.dubbo.rpc.PathResolver; @@ -39,10 +39,12 @@ import io.netty.util.ReferenceCounted; import java.util.List; import java.util.concurrent.Executor; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_RESPONSE; + public class TripleHttp2FrameServerHandler extends ChannelDuplexHandler { - private static final Logger LOGGER = LoggerFactory.getLogger( + private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger( TripleHttp2FrameServerHandler.class); private final PathResolver pathResolver; private final ExecutorSupport executorSupport; @@ -86,7 +88,7 @@ public class TripleHttp2FrameServerHandler extends ChannelDuplexHandler { } public void onResetRead(ChannelHandlerContext ctx, Http2ResetFrame frame) { - LOGGER.warn("Triple Server received remote reset errorCode=" + frame.errorCode()); + LOGGER.warn(PROTOCOL_FAILED_RESPONSE, "", "", "Triple Server received remote reset errorCode=" + frame.errorCode()); if (tripleServerStream != null) { tripleServerStream.transportObserver.cancelByRemote(frame.errorCode()); } @@ -95,7 +97,7 @@ public class TripleHttp2FrameServerHandler extends ChannelDuplexHandler { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (LOGGER.isWarnEnabled()) { - LOGGER.warn("Exception in processing triple message", cause); + LOGGER.warn(PROTOCOL_FAILED_RESPONSE, "", "", "Exception in processing triple message", cause); } TriRpcStatus status = TriRpcStatus.getStatus(cause, "Provider's error:\n" + cause.getMessage()); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleServerConnectionHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleServerConnectionHandler.java index 97c23545ca..7aefff58fc 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleServerConnectionHandler.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleServerConnectionHandler.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.protocol.tri.transport; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import io.netty.channel.ChannelHandlerContext; @@ -32,10 +32,11 @@ import java.net.SocketException; import java.util.HashSet; import java.util.Set; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_RESPONSE; import static org.apache.dubbo.rpc.protocol.tri.transport.GracefulShutdown.GRACEFUL_SHUTDOWN_PING; public class TripleServerConnectionHandler extends Http2ChannelDuplexHandler { - private static final Logger logger = LoggerFactory.getLogger(TripleServerConnectionHandler.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TripleServerConnectionHandler.class); // Some exceptions are not very useful and add too much noise to the log private static final Set QUIET_EXCEPTIONS = new HashSet<>(); private static final Set> QUIET_EXCEPTIONS_CLASS = new HashSet<>(); @@ -54,7 +55,7 @@ public class TripleServerConnectionHandler extends Http2ChannelDuplexHandler { if (((Http2PingFrame) msg).content() == GRACEFUL_SHUTDOWN_PING) { if (gracefulShutdown == null) { // this should never happen - logger.warn("Received GRACEFUL_SHUTDOWN_PING Ack but gracefulShutdown is null"); + logger.warn(PROTOCOL_FAILED_RESPONSE, "", "", "Received GRACEFUL_SHUTDOWN_PING Ack but gracefulShutdown is null"); } else { gracefulShutdown.secondGoAwayAndClose(ctx); } @@ -86,7 +87,7 @@ public class TripleServerConnectionHandler extends Http2ChannelDuplexHandler { logger.debug(String.format("Channel:%s Error", ctx.channel()), cause); } } else { - logger.warn(String.format("Channel:%s Error", ctx.channel()), cause); + logger.warn(PROTOCOL_FAILED_RESPONSE, "", "", String.format("Channel:%s Error", ctx.channel()), cause); } ctx.close(); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubInvocationUtil.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/stub/StubInvocationUtil.java similarity index 100% rename from dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubInvocationUtil.java rename to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/stub/StubInvocationUtil.java diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/StatusRpcExceptionTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/StatusRpcExceptionTest.java similarity index 100% rename from dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/StatusRpcExceptionTest.java rename to dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/StatusRpcExceptionTest.java diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/TriRpcStatusTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/TriRpcStatusTest.java similarity index 100% rename from dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/TriRpcStatusTest.java rename to dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/TriRpcStatusTest.java diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubInvocationUtilTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/stub/StubInvocationUtilTest.java similarity index 90% rename from dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubInvocationUtilTest.java rename to dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/stub/StubInvocationUtilTest.java index e5196f3237..56a192c319 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubInvocationUtilTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/stub/StubInvocationUtilTest.java @@ -25,7 +25,7 @@ import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.MethodDescriptor; import org.apache.dubbo.rpc.model.ServiceDescriptor; -import org.apache.dubbo.rpc.support.DemoService; +import org.apache.dubbo.rpc.protocol.tri.support.IGreeter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -43,7 +43,7 @@ class StubInvocationUtilTest { @Test void unaryCall() throws Throwable { - Invoker invoker = Mockito.mock(Invoker.class); + Invoker invoker = Mockito.mock(Invoker.class); URL url = Mockito.mock(URL.class); ConsumerModel consumerModel = Mockito.mock(ConsumerModel.class); ServiceDescriptor serviceDescriptor = Mockito.mock(ServiceDescriptor.class); @@ -51,13 +51,13 @@ class StubInvocationUtilTest { when(url.getServiceModel()) .thenReturn(consumerModel); when(url.getServiceInterface()) - .thenReturn(DemoService.class.getName()); + .thenReturn(IGreeter.class.getName()); when(url.getProtocolServiceKey()) - .thenReturn(DemoService.class.getName()); + .thenReturn(IGreeter.class.getName()); when(invoker.getUrl()) .thenReturn(url); when(invoker.getInterface()) - .thenReturn(DemoService.class); + .thenReturn(IGreeter.class); Result result = Mockito.mock(Result.class); when(invoker.invoke(any(Invocation.class))) .thenReturn(result); @@ -75,7 +75,7 @@ class StubInvocationUtilTest { @Test void unaryCall2() throws Throwable { - Invoker invoker = Mockito.mock(Invoker.class); + Invoker invoker = Mockito.mock(Invoker.class); URL url = Mockito.mock(URL.class); ConsumerModel consumerModel = Mockito.mock(ConsumerModel.class); ServiceDescriptor serviceDescriptor = Mockito.mock(ServiceDescriptor.class); @@ -83,13 +83,13 @@ class StubInvocationUtilTest { when(url.getServiceModel()) .thenReturn(consumerModel); when(url.getServiceInterface()) - .thenReturn(DemoService.class.getName()); + .thenReturn(IGreeter.class.getName()); when(url.getProtocolServiceKey()) - .thenReturn(DemoService.class.getName()); + .thenReturn(IGreeter.class.getName()); when(invoker.getUrl()) .thenReturn(url); when(invoker.getInterface()) - .thenReturn(DemoService.class); + .thenReturn(IGreeter.class); Result result = Mockito.mock(Result.class); when(invoker.invoke(any(Invocation.class))) .thenThrow(new RuntimeException("a")) @@ -118,7 +118,7 @@ class StubInvocationUtilTest { @Test void testUnaryCall() throws Throwable { - Invoker invoker = Mockito.mock(Invoker.class); + Invoker invoker = Mockito.mock(Invoker.class); URL url = Mockito.mock(URL.class); ConsumerModel consumerModel = Mockito.mock(ConsumerModel.class); ServiceDescriptor serviceDescriptor = Mockito.mock(ServiceDescriptor.class); @@ -126,13 +126,13 @@ class StubInvocationUtilTest { when(url.getServiceModel()) .thenReturn(consumerModel); when(url.getServiceInterface()) - .thenReturn(DemoService.class.getName()); + .thenReturn(IGreeter.class.getName()); when(url.getProtocolServiceKey()) - .thenReturn(DemoService.class.getName()); + .thenReturn(IGreeter.class.getName()); when(invoker.getUrl()) .thenReturn(url); when(invoker.getInterface()) - .thenReturn(DemoService.class); + .thenReturn(IGreeter.class); Result result = Mockito.mock(Result.class); String response = "response"; when(invoker.invoke(any(Invocation.class))) @@ -168,7 +168,7 @@ class StubInvocationUtilTest { @Test void biOrClientStreamCall() throws InterruptedException { - Invoker invoker = Mockito.mock(Invoker.class); + Invoker invoker = Mockito.mock(Invoker.class); URL url = Mockito.mock(URL.class); ConsumerModel consumerModel = Mockito.mock(ConsumerModel.class); ServiceDescriptor serviceDescriptor = Mockito.mock(ServiceDescriptor.class); @@ -176,13 +176,13 @@ class StubInvocationUtilTest { when(url.getServiceModel()) .thenReturn(consumerModel); when(url.getServiceInterface()) - .thenReturn(DemoService.class.getName()); + .thenReturn(IGreeter.class.getName()); when(url.getProtocolServiceKey()) - .thenReturn(DemoService.class.getName()); + .thenReturn(IGreeter.class.getName()); when(invoker.getUrl()) .thenReturn(url); when(invoker.getInterface()) - .thenReturn(DemoService.class); + .thenReturn(IGreeter.class); Result result = Mockito.mock(Result.class); String response = "response"; @@ -243,7 +243,7 @@ class StubInvocationUtilTest { @Test void serverStreamCall() throws InterruptedException { - Invoker invoker = Mockito.mock(Invoker.class); + Invoker invoker = Mockito.mock(Invoker.class); URL url = Mockito.mock(URL.class); ConsumerModel consumerModel = Mockito.mock(ConsumerModel.class); ServiceDescriptor serviceDescriptor = Mockito.mock(ServiceDescriptor.class); @@ -251,13 +251,13 @@ class StubInvocationUtilTest { when(url.getServiceModel()) .thenReturn(consumerModel); when(url.getServiceInterface()) - .thenReturn(DemoService.class.getName()); + .thenReturn(IGreeter.class.getName()); when(url.getProtocolServiceKey()) - .thenReturn(DemoService.class.getName()); + .thenReturn(IGreeter.class.getName()); when(invoker.getUrl()) .thenReturn(url); when(invoker.getInterface()) - .thenReturn(DemoService.class); + .thenReturn(IGreeter.class); Result result = Mockito.mock(Result.class); String response = "response"; when(invoker.invoke(any(Invocation.class))) diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaSerialization.java b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaSerialization.java index e166f33776..4626ece767 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaSerialization.java +++ b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaSerialization.java @@ -17,7 +17,7 @@ package org.apache.dubbo.common.serialize.java; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -28,6 +28,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.util.concurrent.atomic.AtomicBoolean; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNSAFE_SERIALIZATION; import static org.apache.dubbo.common.serialize.Constants.JAVA_SERIALIZATION_ID; /** @@ -38,7 +39,7 @@ import static org.apache.dubbo.common.serialize.Constants.JAVA_SERIALIZATION_ID; * */ public class JavaSerialization implements Serialization { - private static final Logger logger = LoggerFactory.getLogger(JavaSerialization.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(JavaSerialization.class); private static final AtomicBoolean warn = new AtomicBoolean(false); @Override @@ -54,7 +55,7 @@ public class JavaSerialization implements Serialization { @Override public ObjectOutput serialize(URL url, OutputStream out) throws IOException { if (warn.compareAndSet(false, true)) { - logger.error("Java serialization is unsafe. Dubbo Team do not recommend anyone to use it." + + logger.error(PROTOCOL_UNSAFE_SERIALIZATION, "", "", "Java serialization is unsafe. Dubbo Team do not recommend anyone to use it." + "If you still want to use it, please follow [JEP 290](https://openjdk.java.net/jeps/290)" + "to set serialization filter to prevent deserialization leak."); } @@ -64,7 +65,7 @@ public class JavaSerialization implements Serialization { @Override public ObjectInput deserialize(URL url, InputStream is) throws IOException { if (warn.compareAndSet(false, true)) { - logger.error("Java serialization is unsafe. Dubbo Team do not recommend anyone to use it." + + logger.error(PROTOCOL_UNSAFE_SERIALIZATION, "", "", "Java serialization is unsafe. Dubbo Team do not recommend anyone to use it." + "If you still want to use it, please follow [JEP 290](https://openjdk.java.net/jeps/290)" + "to set serialization filter to prevent deserialization leak."); } diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaSerialization.java b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaSerialization.java index 854fb0e26f..2e6e493b91 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaSerialization.java +++ b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaSerialization.java @@ -18,7 +18,7 @@ package org.apache.dubbo.common.serialize.nativejava; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -30,6 +30,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.util.concurrent.atomic.AtomicBoolean; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNSAFE_SERIALIZATION; import static org.apache.dubbo.common.serialize.Constants.NATIVE_JAVA_SERIALIZATION_ID; /** @@ -40,7 +41,7 @@ import static org.apache.dubbo.common.serialize.Constants.NATIVE_JAVA_SERIALIZAT * */ public class NativeJavaSerialization implements Serialization { - private static final Logger logger = LoggerFactory.getLogger(JavaSerialization.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(JavaSerialization.class); private static final AtomicBoolean warn = new AtomicBoolean(false); @Override @@ -56,7 +57,7 @@ public class NativeJavaSerialization implements Serialization { @Override public ObjectOutput serialize(URL url, OutputStream output) throws IOException { if (warn.compareAndSet(false, true)) { - logger.error("Java serialization is unsafe. Dubbo Team do not recommend anyone to use it." + + logger.error(PROTOCOL_UNSAFE_SERIALIZATION, "", "", "Java serialization is unsafe. Dubbo Team do not recommend anyone to use it." + "If you still want to use it, please follow [JEP 290](https://openjdk.java.net/jeps/290)" + "to set serialization filter to prevent deserialization leak."); } @@ -66,7 +67,7 @@ public class NativeJavaSerialization implements Serialization { @Override public ObjectInput deserialize(URL url, InputStream input) throws IOException { if (warn.compareAndSet(false, true)) { - logger.error("Java serialization is unsafe. Dubbo Team do not recommend anyone to use it." + + logger.error(PROTOCOL_UNSAFE_SERIALIZATION, "", "", "Java serialization is unsafe. Dubbo Team do not recommend anyone to use it." + "If you still want to use it, please follow [JEP 290](https://openjdk.java.net/jeps/290)" + "to set serialization filter to prevent deserialization leak."); } diff --git a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/condition/CompatibleOnEnabledEndpointCondition.java b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/condition/CompatibleOnEnabledEndpointCondition.java index 15caada2d0..0c76ea7605 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/condition/CompatibleOnEnabledEndpointCondition.java +++ b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/condition/CompatibleOnEnabledEndpointCondition.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.spring.boot.actuate.endpoint.condition; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.springframework.beans.BeanUtils; @@ -26,6 +26,8 @@ import org.springframework.context.annotation.Conditional; import org.springframework.core.type.AnnotatedTypeMetadata; import org.springframework.util.ClassUtils; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_CLASS_NOT_FOUND; + /** * {@link Conditional} that checks whether or not an endpoint is enabled, which is compatible with * org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnEnabledEndpointCondition @@ -36,7 +38,7 @@ import org.springframework.util.ClassUtils; */ class CompatibleOnEnabledEndpointCondition implements Condition { - private static final Logger LOGGER = LoggerFactory.getLogger(CompatibleOnEnabledEndpointCondition.class); + private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(CompatibleOnEnabledEndpointCondition.class); // Spring Boot [2.0.0 , 2.2.x] static String CONDITION_CLASS_NAME_OLD = @@ -62,7 +64,7 @@ class CompatibleOnEnabledEndpointCondition implements Condition { return true; } // No condition class found - LOGGER.warn(String.format("No condition class found, Dubbo Health Endpoint [%s] will not expose", metadata)); + LOGGER.warn(COMMON_CLASS_NOT_FOUND, "No condition class found", "", String.format("No condition class found, Dubbo Health Endpoint [%s] will not expose", metadata)); return false; } } diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/ConfigZookeeperInitializer.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/ConfigZookeeperInitializer.java index cc50bb958a..f703f1e780 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/ConfigZookeeperInitializer.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/ConfigZookeeperInitializer.java @@ -23,7 +23,6 @@ import org.apache.dubbo.test.check.exception.DubboTestException; import org.apache.dubbo.test.check.registrycenter.context.ZookeeperContext; import java.io.File; -import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; @@ -54,7 +53,8 @@ public class ConfigZookeeperInitializer extends ZookeeperInitializer { int availableAdminServerPort = NetUtils.getAvailablePort(adminServerPort); Properties properties = new Properties(); try { - properties.load(new FileInputStream(zooSample)); + // use Files.newInputStream instead of new FileInputStream + properties.load(Files.newInputStream(zooSample.toPath())); properties.setProperty("clientPort", String.valueOf(clientPort)); properties.setProperty("admin.serverPort", String.valueOf(availableAdminServerPort)); Path dataDir = Paths.get(zookeeperConf.getParent().toString(), "data"); @@ -87,7 +87,8 @@ public class ConfigZookeeperInitializer extends ZookeeperInitializer { File log4j = Paths.get(zookeeperConf.toString(), "log4j.properties").toFile(); try { - properties.load(new FileInputStream(log4j)); + // use Files.newInputStream instead of new FileInputStream + properties.load(Files.newInputStream(log4j.toPath())); Path logDir = Paths.get(zookeeperConf.getParent().toString(), "logs"); if (!Files.exists(logDir)) { try { diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/DownloadZookeeperInitializer.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/DownloadZookeeperInitializer.java index b5973d5a6f..ebdb835206 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/DownloadZookeeperInitializer.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/DownloadZookeeperInitializer.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.test.check.registrycenter.initializer; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.test.check.exception.DubboTestException; import org.apache.dubbo.test.check.registrycenter.context.ZookeeperContext; @@ -37,12 +37,14 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_DOWNLOAD_FILE; + /** * Download zookeeper binary archive. */ public class DownloadZookeeperInitializer extends ZookeeperInitializer { - private static final Logger logger = LoggerFactory.getLogger(DownloadZookeeperInitializer.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DownloadZookeeperInitializer.class); /** * The zookeeper binary file name format. @@ -167,7 +169,7 @@ public class DownloadZookeeperInitializer extends ZookeeperInitializer { @Override public void onThrowable(Throwable t) { - logger.warn("Failed to download the file, download url: " + url); + logger.warn(REGISTRY_FAILED_DOWNLOAD_FILE, "", "", "Failed to download the file, download url: " + url); super.onThrowable(t); } }); diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ZookeeperUnixProcessor.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ZookeeperUnixProcessor.java index c2600319e3..0ef5a6cbc8 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ZookeeperUnixProcessor.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ZookeeperUnixProcessor.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.test.check.registrycenter.processor; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.test.check.exception.DubboTestException; import org.apache.dubbo.test.check.registrycenter.Context; @@ -29,12 +29,15 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.util.regex.Pattern; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_START_ZOOKEEPER; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_STOP_ZOOKEEPER; + /** * The abstract implementation of {@link Processor} is to provide some common methods on Unix OS. */ public abstract class ZookeeperUnixProcessor implements Processor { - private static final Logger logger = LoggerFactory.getLogger(ZookeeperUnixProcessor.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ZookeeperUnixProcessor.class); @Override public void process(Context context) throws DubboTestException { @@ -47,7 +50,7 @@ public abstract class ZookeeperUnixProcessor implements Processor { try { process.destroy(); } catch (Throwable cause) { - logger.warn(String.format("Failed to kill the process, with client port %s !", clientPort), cause); + logger.warn(REGISTRY_FAILED_STOP_ZOOKEEPER, "", "", String.format("Failed to kill the process, with client port %s !", clientPort), cause); } } } @@ -61,7 +64,7 @@ public abstract class ZookeeperUnixProcessor implements Processor { try (final BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream))) { String line; while ((line = reader.readLine()) != null) { - logger.error(line); + logger.error(REGISTRY_FAILED_START_ZOOKEEPER,"","",line); } } catch (IOException e) { /* eat quietly */ diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsServiceDiscovery.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsServiceDiscovery.java index 28945f85f0..9f2b856bb3 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsServiceDiscovery.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsServiceDiscovery.java @@ -17,7 +17,7 @@ package org.apache.dubbo.registry.xds; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.registry.client.DefaultServiceInstance; import org.apache.dubbo.registry.client.ReflectionBasedServiceDiscovery; @@ -34,9 +34,12 @@ import java.util.LinkedList; import java.util.List; import java.util.Set; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_INITIALIZE_XDS; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_PARSING_XDS; + public class XdsServiceDiscovery extends ReflectionBasedServiceDiscovery { - private static final Logger logger = LoggerFactory.getLogger(XdsServiceDiscovery.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(XdsServiceDiscovery.class); private PilotExchanger exchanger; @@ -49,7 +52,7 @@ public class XdsServiceDiscovery extends ReflectionBasedServiceDiscovery { try { exchanger = PilotExchanger.initialize(registryURL); } catch (Throwable t) { - logger.error(t); + logger.error(REGISTRY_ERROR_INITIALIZE_XDS, "", "", t.getMessage(), t); } } @@ -58,7 +61,7 @@ public class XdsServiceDiscovery extends ReflectionBasedServiceDiscovery { try { exchanger.destroy(); } catch (Throwable t) { - logger.error(t); + logger.error(REGISTRY_ERROR_INITIALIZE_XDS, "", "", t.getMessage(), t); } } @@ -88,7 +91,7 @@ public class XdsServiceDiscovery extends ReflectionBasedServiceDiscovery { fillServiceInstance(serviceInstance); instances.add(serviceInstance); } catch (Throwable t) { - logger.error("Error occurred when parsing endpoints. Endpoints List:" + endpoints, t); + logger.error(REGISTRY_ERROR_PARSING_XDS, "", "", "Error occurred when parsing endpoints. Endpoints List:" + endpoints, t); } }); instances.sort(Comparator.comparingInt(ServiceInstance::hashCode)); diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsServiceDiscoveryFactory.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsServiceDiscoveryFactory.java index 41eba21a70..706e230c51 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsServiceDiscoveryFactory.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsServiceDiscoveryFactory.java @@ -17,23 +17,25 @@ package org.apache.dubbo.registry.xds; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.registry.client.AbstractServiceDiscoveryFactory; import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.rpc.model.ApplicationModel; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_INITIALIZE_XDS; + public class XdsServiceDiscoveryFactory extends AbstractServiceDiscoveryFactory { - private static final Logger logger = LoggerFactory.getLogger(XdsServiceDiscoveryFactory.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(XdsServiceDiscoveryFactory.class); @Override protected ServiceDiscovery createDiscovery(URL registryURL) { - XdsServiceDiscovery xdsServiceDiscovery = new XdsServiceDiscovery(ApplicationModel.defaultModel() ,registryURL); + XdsServiceDiscovery xdsServiceDiscovery = new XdsServiceDiscovery(ApplicationModel.defaultModel(), registryURL); try { xdsServiceDiscovery.doInitialize(registryURL); } catch (Exception e) { - logger.error("Error occurred when initialize xDS service discovery impl.", e); + logger.error(REGISTRY_ERROR_INITIALIZE_XDS, "", "", "Error occurred when initialize xDS service discovery impl.", e); } return xdsServiceDiscovery; } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioCitadelCertificateSigner.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioCitadelCertificateSigner.java index 7aa033c486..df8ce0a8f8 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioCitadelCertificateSigner.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioCitadelCertificateSigner.java @@ -17,7 +17,7 @@ package org.apache.dubbo.registry.xds.istio; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.registry.xds.XdsCertificateSigner; import org.apache.dubbo.rpc.RpcException; @@ -63,9 +63,13 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_GENERATE_CERT_ISTIO; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_GENERATE_KEY_ISTIO; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_RECEIVE_ERROR_MSG_ISTIO; + public class IstioCitadelCertificateSigner implements XdsCertificateSigner { - private static final Logger logger = LoggerFactory.getLogger(IstioCitadelCertificateSigner.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(IstioCitadelCertificateSigner.class); private final org.apache.dubbo.registry.xds.istio.IstioEnv istioEnv; @@ -100,7 +104,7 @@ public class IstioCitadelCertificateSigner implements XdsCertificateSigner { try { certPair = createCert(); } catch (IOException e) { - logger.error("Generate Cert from Istio failed.", e); + logger.error(REGISTRY_FAILED_GENERATE_CERT_ISTIO, "", "", "Generate Cert from Istio failed.", e); throw new RpcException("Generate Cert from Istio failed.", e); } } @@ -123,7 +127,7 @@ public class IstioCitadelCertificateSigner implements XdsCertificateSigner { privateKey = keypair.getPrivate(); signer = new JcaContentSignerBuilder("SHA256withECDSA").build(keypair.getPrivate()); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | OperatorCreationException e) { - logger.error("Generate Key with secp256r1 algorithm failed. Please check if your system support. " + logger.error(REGISTRY_FAILED_GENERATE_KEY_ISTIO, "", "", "Generate Key with secp256r1 algorithm failed. Please check if your system support. " + "Will attempt to generate with RSA2048.", e); } } @@ -137,7 +141,7 @@ public class IstioCitadelCertificateSigner implements XdsCertificateSigner { privateKey = keypair.getPrivate(); signer = new JcaContentSignerBuilder("SHA256WithRSA").build(keypair.getPrivate()); } catch (NoSuchAlgorithmException | OperatorCreationException e) { - logger.error("Generate Key with SHA256WithRSA algorithm failed. Please check if your system support.", e); + logger.error(REGISTRY_FAILED_GENERATE_KEY_ISTIO, "", "", "Generate Key with SHA256WithRSA algorithm failed. Please check if your system support.", e); throw new RpcException(e); } } @@ -207,7 +211,7 @@ public class IstioCitadelCertificateSigner implements XdsCertificateSigner { @Override public void onError(Throwable throwable) { failed.set(true); - logger.error("Receive error message from Istio Citadel grpc stub.", throwable); + logger.error(REGISTRY_RECEIVE_ERROR_MSG_ISTIO, "", "", "Receive error message from Istio Citadel grpc stub.", throwable); countDownLatch.countDown(); } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioEnv.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioEnv.java index 87d468573f..d78422db61 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioEnv.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioEnv.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.registry.xds.istio; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.registry.xds.XdsEnv; @@ -27,12 +27,13 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Optional; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_READ_FILE_ISTIO; import static org.apache.dubbo.registry.xds.istio.IstioConstant.NS; import static org.apache.dubbo.registry.xds.istio.IstioConstant.SA; import static org.apache.dubbo.registry.xds.istio.IstioConstant.SPIFFE; public class IstioEnv implements XdsEnv { - private static final Logger logger = LoggerFactory.getLogger(IstioEnv.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(IstioEnv.class); private static final IstioEnv INSTANCE = new IstioEnv(); @@ -67,7 +68,7 @@ public class IstioEnv implements XdsEnv { try { return FileUtils.readFileToString(namespaceFile, StandardCharsets.UTF_8); } catch (IOException e) { - logger.error("read namespace file error", e); + logger.error(REGISTRY_ERROR_READ_FILE_ISTIO, "", "", "read namespace file error", e); } } return IstioConstant.DEFAULT_WORKLOAD_NAMESPACE; diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/XdsChannel.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/XdsChannel.java index 9019d38018..3378cbf4dd 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/XdsChannel.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/XdsChannel.java @@ -21,7 +21,7 @@ import io.grpc.netty.shaded.io.netty.channel.epoll.EpollDomainSocketChannel; import io.grpc.netty.shaded.io.netty.channel.epoll.EpollEventLoopGroup; import io.grpc.netty.shaded.io.netty.channel.unix.DomainSocketAddress; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.url.component.URLAddress; import org.apache.dubbo.registry.xds.XdsCertificateSigner; @@ -37,12 +37,15 @@ import io.grpc.netty.shaded.io.netty.handler.ssl.util.InsecureTrustManagerFactor import io.grpc.stub.StreamObserver; import org.apache.dubbo.registry.xds.util.bootstrap.Bootstrapper; import org.apache.dubbo.registry.xds.util.bootstrap.BootstrapperImpl; + import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_CREATE_CHANNEL_XDS; + public class XdsChannel { - private static final Logger logger = LoggerFactory.getLogger(XdsChannel.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(XdsChannel.class); private static final String USE_AGENT = "use-agent"; @@ -51,7 +54,7 @@ public class XdsChannel { protected XdsChannel(URL url) { ManagedChannel managedChannel = null; try { - if(!url.getParameter(USE_AGENT,false)) { + if (!url.getParameter(USE_AGENT, false)) { XdsCertificateSigner signer = url.getOrDefaultApplicationModel().getExtensionLoader(XdsCertificateSigner.class) .getExtension(url.getParameter("signer", "istio")); XdsCertificateSigner.CertPair certPair = signer.GenerateCert(url); @@ -62,11 +65,10 @@ public class XdsChannel { .build(); managedChannel = NettyChannelBuilder.forAddress(url.getHost(), url.getPort()).sslContext(context) .build(); - } - else { + } else { BootstrapperImpl bootstrapper = new BootstrapperImpl(); Bootstrapper.BootstrapInfo bootstrapInfo = bootstrapper.bootstrap(); - URLAddress address =URLAddress.parse(bootstrapInfo.servers().get(0).target(),null, false); + URLAddress address = URLAddress.parse(bootstrapInfo.servers().get(0).target(), null, false); EpollEventLoopGroup elg = new EpollEventLoopGroup(); managedChannel = NettyChannelBuilder.forAddress(new DomainSocketAddress("/" + address.getPath())) .eventLoopGroup(elg) @@ -75,7 +77,7 @@ public class XdsChannel { .build(); } } catch (Exception e) { - logger.error("Error occurred when creating gRPC channel to control panel.", e); + logger.error(REGISTRY_ERROR_CREATE_CHANNEL_XDS, "", "", "Error occurred when creating gRPC channel to control panel.", e); } channel = managedChannel; } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/AbstractProtocol.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/AbstractProtocol.java index 4c87033109..fdb98c3410 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/AbstractProtocol.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/AbstractProtocol.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.registry.xds.util.protocol; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.registry.xds.util.XdsChannel; @@ -39,9 +39,11 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_REQUEST_XDS; + public abstract class AbstractProtocol> implements XdsProtocol { - private static final Logger logger = LoggerFactory.getLogger(AbstractProtocol.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractProtocol.class); protected final XdsChannel xdsChannel; @@ -114,7 +116,7 @@ public abstract class AbstractProtocol> implements // get result return future.get(); } catch (InterruptedException | ExecutionException e) { - logger.error("Error occur when request control panel."); + logger.error(REGISTRY_ERROR_REQUEST_XDS, "", "", "Error occur when request control panel."); return null; } finally { // close observer @@ -166,7 +168,7 @@ public abstract class AbstractProtocol> implements // get result consumer.accept(future.get()); } catch (InterruptedException | ExecutionException e) { - logger.error("Error occur when request control panel."); + logger.error(REGISTRY_ERROR_REQUEST_XDS, "", "", "Error occur when request control panel."); } finally { // close observer //requestObserver.onCompleted(); @@ -175,7 +177,7 @@ public abstract class AbstractProtocol> implements streamResult.remove(request); } } catch (Throwable t) { - logger.error("Error when requesting observe data. Type: " + getTypeUrl(), t); + logger.error(REGISTRY_ERROR_REQUEST_XDS, "", "", "Error when requesting observe data. Type: " + getTypeUrl(), t); } }, pollingTimeout, pollingTimeout, TimeUnit.SECONDS); @@ -231,7 +233,7 @@ public abstract class AbstractProtocol> implements @Override public void onError(Throwable t) { - logger.error("xDS Client received error message! detail:", t); + logger.error(REGISTRY_ERROR_REQUEST_XDS, "", "", "xDS Client received error message! detail:", t); clear(); returnResult(null); } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/EdsProtocol.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/EdsProtocol.java index 510370a312..b171a5406a 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/EdsProtocol.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/EdsProtocol.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.registry.xds.util.protocol.impl; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.registry.xds.util.XdsChannel; import org.apache.dubbo.registry.xds.util.protocol.AbstractProtocol; @@ -37,9 +37,11 @@ import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_RESPONSE_XDS; + public class EdsProtocol extends AbstractProtocol { - private static final Logger logger = LoggerFactory.getLogger(EdsProtocol.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(EdsProtocol.class); public EdsProtocol(XdsChannel xdsChannel, Node node, int pollingPoolSize, int pollingTimeout) { super(xdsChannel, node, pollingPoolSize, pollingTimeout); @@ -86,7 +88,7 @@ public class EdsProtocol extends AbstractProtocol try { return any.unpack(ClusterLoadAssignment.class); } catch (InvalidProtocolBufferException e) { - logger.error("Error occur when decode xDS response.", e); + logger.error(REGISTRY_ERROR_RESPONSE_XDS, "", "", "Error occur when decode xDS response.", e); return null; } } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/LdsProtocol.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/LdsProtocol.java index b9a59a591b..8566e6e027 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/LdsProtocol.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/LdsProtocol.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.registry.xds.util.protocol.impl; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.registry.xds.util.XdsChannel; import org.apache.dubbo.registry.xds.util.protocol.AbstractProtocol; @@ -38,9 +38,11 @@ import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_RESPONSE_XDS; + public class LdsProtocol extends AbstractProtocol { - private static final Logger logger = LoggerFactory.getLogger(LdsProtocol.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(LdsProtocol.class); public LdsProtocol(XdsChannel xdsChannel, Node node, int pollingPoolSize, int pollingTimeout) { super(xdsChannel, node, pollingPoolSize, pollingTimeout); @@ -87,7 +89,7 @@ public class LdsProtocol extends AbstractProtocol try { return any.unpack(Listener.class); } catch (InvalidProtocolBufferException e) { - logger.error("Error occur when decode xDS response.", e); + logger.error(REGISTRY_ERROR_RESPONSE_XDS, "", "", "Error occur when decode xDS response.", e); return null; } } @@ -99,7 +101,7 @@ public class LdsProtocol extends AbstractProtocol } return any.unpack(HttpConnectionManager.class); } catch (InvalidProtocolBufferException e) { - logger.error("Error occur when decode xDS response.", e); + logger.error(REGISTRY_ERROR_RESPONSE_XDS, "", "", "Error occur when decode xDS response.", e); return null; } } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/RdsProtocol.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/RdsProtocol.java index ff9ba67a1a..653b53e648 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/RdsProtocol.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/RdsProtocol.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.registry.xds.util.protocol.impl; -import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.registry.xds.util.XdsChannel; import org.apache.dubbo.registry.xds.util.protocol.AbstractProtocol; @@ -37,9 +37,11 @@ import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_RESPONSE_XDS; + public class RdsProtocol extends AbstractProtocol { - private static final Logger logger = LoggerFactory.getLogger(RdsProtocol.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RdsProtocol.class); public RdsProtocol(XdsChannel xdsChannel, Node node, int pollingPoolSize, int pollingTimeout) { super(xdsChannel, node, pollingPoolSize, pollingTimeout); @@ -85,7 +87,7 @@ public class RdsProtocol extends AbstractProtocol { try { return any.unpack(RouteConfiguration.class); } catch (InvalidProtocolBufferException e) { - logger.error("Error occur when decode xDS response.", e); + logger.error(REGISTRY_ERROR_RESPONSE_XDS, "", "", "Error occur when decode xDS response.", e); return null; } }