From 791918c471aa7a14ef6d1a915bdc62ac60531691 Mon Sep 17 00:00:00 2001 From: cnjxzhao <85160585+cnjxzhao@users.noreply.github.com> Date: Fri, 25 Nov 2022 17:34:38 +0800 Subject: [PATCH] Error code is managed with constants (#10771) (#11016) --- .../file/FileSystemDynamicConfiguration.java | 57 ++++++++++--------- .../common/constants/LoggerCodeConstants.java | 11 +++- .../utils/ClassLoaderResourceLoader.java | 10 ++-- .../apache/dubbo/config/ProtocolConfig.java | 3 +- .../logger/support/FailsafeLoggerTest.java | 33 +++++------ .../config/utils/ConfigValidationUtils.java | 5 +- .../config/bootstrap/MultiInstanceTest.java | 32 +++++------ .../utils/ConfigValidationUtilsTest.java | 5 +- .../AbstractAnnotationBeanPostProcessor.java | 32 +++++------ .../ReferenceAnnotationBeanPostProcessor.java | 25 ++++---- .../DubboBootstrapApplicationListener.java | 15 +++-- .../DubboConfigApplicationListener.java | 10 ++-- .../reference/ReferenceBeanManager.java | 22 +++---- .../config/spring/EmbeddedZooKeeper.java | 6 +- .../support/apollo/EmbeddedApolloJunit5.java | 10 ++-- .../ZookeeperDynamicConfiguration.java | 3 +- .../store/nacos/NacosMetadataReport.java | 2 +- .../store/redis/RedisMetadataReport.java | 35 +++++++----- .../dubbo/monitor/dubbo/MetricsFilter.java | 7 ++- .../registry/PerformanceRegistryTest.java | 11 ++-- .../dubbo/remoting/ChanelHandlerTest.java | 11 ++-- .../remoting/PerformanceClientCloseTest.java | 13 +++-- .../remoting/PerformanceClientFixedTest.java | 9 +-- .../dubbo/remoting/PerformanceClientTest.java | 9 +-- .../dubbo/remoting/PerformanceServerTest.java | 15 ++--- .../codec/DeprecatedExchangeCodec.java | 17 +++--- .../remoting/codec/DeprecatedTelnetCodec.java | 17 +++--- .../tri/stream/TripleClientStream.java | 20 ++++--- 28 files changed, 246 insertions(+), 199 deletions(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfiguration.java index 2612c7baef..cf055349aa 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfiguration.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfiguration.java @@ -25,14 +25,14 @@ import org.apache.dubbo.common.config.configcenter.TreePathDynamicConfiguration; import org.apache.dubbo.common.function.ThrowableConsumer; import org.apache.dubbo.common.function.ThrowableFunction; import org.apache.dubbo.common.lang.ShutdownHookCallbacks; +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; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; import org.apache.commons.io.FileUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import java.io.File; import java.io.IOException; @@ -70,6 +70,7 @@ import static java.util.Collections.unmodifiableMap; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.apache.commons.io.FileUtils.readFileToString; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_ERROR_PROCESS_LISTENER; /** * File-System based {@link DynamicConfiguration} implementation @@ -83,7 +84,7 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration public static final String CONFIG_CENTER_ENCODING_PARAM_NAME = PARAM_NAME_PREFIX + "encoding"; public static final String DEFAULT_CONFIG_CENTER_DIR_PATH = System.getProperty("user.home") + File.separator - + ".dubbo" + File.separator + "config-center"; + + ".dubbo" + File.separator + "config-center"; public static final int DEFAULT_THREAD_POOL_SIZE = 1; @@ -101,7 +102,7 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration /** * Logger */ - private static final Log logger = LogFactory.getLog(FileSystemDynamicConfiguration.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FileSystemDynamicConfiguration.class); /** @@ -109,14 +110,14 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration * {@link WatchEvent.Kind WatchEvent's Kind} */ private static final Map CONFIG_CHANGE_TYPES_MAP = - unmodifiableMap(new HashMap() { - // Initializes the elements that is mapping ConfigChangeType - { - put(ENTRY_CREATE.name(), ConfigChangeType.ADDED); - put(ENTRY_DELETE.name(), ConfigChangeType.DELETED); - put(ENTRY_MODIFY.name(), ConfigChangeType.MODIFIED); - } - }); + unmodifiableMap(new HashMap() { + // Initializes the elements that is mapping ConfigChangeType + { + put(ENTRY_CREATE.name(), ConfigChangeType.ADDED); + put(ENTRY_DELETE.name(), ConfigChangeType.DELETED); + put(ENTRY_MODIFY.name(), ConfigChangeType.MODIFIED); + } + }); private static final Optional watchService; @@ -221,7 +222,7 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration public FileSystemDynamicConfiguration(URL url) { this(initDirectory(url), getEncoding(url), getThreadPoolPrefixName(url), getThreadPoolSize(url), - getThreadPoolKeepAliveTime(url), url.getScopeModel()); + getThreadPoolKeepAliveTime(url), url.getScopeModel()); } private Set initProcessingDirectories() { @@ -358,7 +359,7 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration listener.process(new ConfigChangedEvent(key, configDirectory.getName(), value, configChangeType)); } catch (Throwable e) { if (logger.isErrorEnabled()) { - logger.error(e.getMessage(), e); + logger.error(CONFIG_ERROR_PROCESS_LISTENER, "", "", e.getMessage(), e); } } }); @@ -404,8 +405,8 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration return new TreeSet<>(); } else { return Stream.of(files) - .map(File::getName) - .collect(Collectors.toList()); + .map(File::getName) + .collect(Collectors.toList()); } } @@ -457,7 +458,7 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration long timeout = SECONDS.toMillis(delay); if (logger.isDebugEnabled()) { logger.debug(format("The config[path : %s] is about to delay in %d ms.", - configFilePath, timeout)); + configFilePath, timeout)); } configDirectory.wait(timeout); } @@ -473,7 +474,7 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration value = function.apply(configFile); } catch (Throwable e) { if (logger.isErrorEnabled()) { - logger.error(e.getMessage(), e); + logger.error(CONFIG_ERROR_PROCESS_LISTENER, "", "", e.getMessage(), e); } } @@ -500,14 +501,14 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration public Set getConfigGroups() { return Stream.of(getRootDirectory().listFiles()) - .filter(File::isDirectory) - .map(File::getName) - .collect(Collectors.toSet()); + .filter(File::isDirectory) + .map(File::getName) + .collect(Collectors.toSet()); } protected String getConfig(File configFile) { return ThrowableFunction.execute(configFile, - file -> canRead(configFile) ? readFileToString(configFile, getEncoding()) : null); + file -> canRead(configFile) ? readFileToString(configFile, getEncoding()) : null); } @Override @@ -554,7 +555,7 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration value = callable.call(); } catch (Exception e) { if (logger.isErrorEnabled()) { - logger.error(e.getMessage(), e); + logger.error(CONFIG_ERROR_PROCESS_LISTENER, "", "", e.getMessage(), e); } } } @@ -599,7 +600,7 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration watchService = Optional.of(fileSystem.newWatchService()); } catch (IOException e) { if (logger.isErrorEnabled()) { - logger.error(e.getMessage(), e); + logger.error(CONFIG_ERROR_PROCESS_LISTENER, "", "", e.getMessage(), e); } watchService = Optional.empty(); } @@ -619,7 +620,7 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration if (!rootDirectory.exists() && !rootDirectory.mkdirs()) { throw new IllegalStateException(format("Dubbo config center rootDirectory[%s] can't be created!", - rootDirectory.getAbsolutePath())); + rootDirectory.getAbsolutePath())); } return rootDirectory; } @@ -630,8 +631,8 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration private static ThreadPoolExecutor newWatchEventsLoopThreadPool() { return new ThreadPoolExecutor(THREAD_POOL_SIZE, THREAD_POOL_SIZE, - 0L, MILLISECONDS, - new SynchronousQueue(), - new NamedThreadFactory("dubbo-config-center-watch-events-loop", true)); + 0L, MILLISECONDS, + new SynchronousQueue(), + new NamedThreadFactory("dubbo-config-center-watch-events-loop", true)); } } 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 4d8a6120b2..c4ab2f3c2e 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 @@ -324,6 +324,14 @@ public interface LoggerCodeConstants { String CONFIG_FILTER_VALIDATION_EXCEPTION = "5-36"; + String CONFIG_ERROR_PROCESS_LISTENER = "5-37"; + + String CONFIG_UNDEFINED_ARGUMENT = "5-38"; + + String CONFIG_DUBBO_BEAN_INITIALIZER = "5-39"; + + String CONFIG_DUBBO_BEAN_NOT_FOUND = "5-40"; + // transport module String TRANSPORT_FAILED_CONNECT_PROVIDER = "6-1"; @@ -355,7 +363,7 @@ public interface LoggerCodeConstants { String TRANSPORT_SKIP_UNUSED_STREAM = "6-15"; - String TRANSPORT_FAILED_RECONNECT = "6-3"; + String TRANSPORT_FAILED_RECONNECT = "6-16"; // qos plugin String QOS_PROFILER_DISABLED = "7-1"; @@ -371,7 +379,6 @@ public interface LoggerCodeConstants { String QOS_UNEXPECTED_EXCEPTION = "7-6"; // Internal unknown error. - String INTERNAL_ERROR = "99-0"; String INTERNAL_INTERRUPTED = "99-1"; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoader.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoader.java index 2b4e88e228..fa180db2a2 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoader.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoader.java @@ -16,7 +16,7 @@ */ 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 org.apache.dubbo.common.resource.GlobalResourcesRepository; @@ -35,13 +35,15 @@ import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_IO_EXCEPTION; + public class ClassLoaderResourceLoader { - private static Logger logger = LoggerFactory.getLogger(ClassLoaderResourceLoader.class); + private static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ClassLoaderResourceLoader.class); private static SoftReference>>> classLoaderResourcesCache = null; static { // register resources destroy listener - GlobalResourcesRepository.registerGlobalDisposable(()-> destroy()); + GlobalResourcesRepository.registerGlobalDisposable(() -> destroy()); } public static Map> loadResources(String fileName, List classLoaders) throws InterruptedException { @@ -88,7 +90,7 @@ public class ClassLoaderResourceLoader { } } } catch (IOException e) { - logger.error("Exception occurred when reading SPI definitions. SPI path: " + fileName + " ClassLoader name: " + currentClassLoader, e); + logger.error(COMMON_IO_EXCEPTION, "", "", "Exception occurred when reading SPI definitions. SPI path: " + fileName + " ClassLoader name: " + currentClassLoader, e); } urlCache.put(fileName, set); } 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 0903ac94b8..bb5b6e0141 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 @@ -28,6 +28,7 @@ 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; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_POOL_EXHAUSTED_LISTENERS_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; /** * ProtocolConfig @@ -603,7 +604,7 @@ public class ProtocolConfig extends AbstractConfig { }); } } catch (Exception e) { - logger.error("merge protocol config fail, error: ", e); + logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", "merge protocol config fail, error: ", e); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/logger/support/FailsafeLoggerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/logger/support/FailsafeLoggerTest.java index 52abadc0c7..0af20fb239 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/logger/support/FailsafeLoggerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/logger/support/FailsafeLoggerTest.java @@ -21,6 +21,7 @@ import org.apache.dubbo.common.logger.Logger; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; @@ -31,7 +32,7 @@ class FailsafeLoggerTest { @Test void testFailSafeForLoggingMethod() { Logger failLogger = mock(Logger.class); - FailsafeLogger failsafeLogger = new FailsafeLogger(failLogger); + FailsafeErrorTypeAwareLogger failsafeLogger = new FailsafeErrorTypeAwareLogger(failLogger); doThrow(new RuntimeException()).when(failLogger).error(anyString()); doThrow(new RuntimeException()).when(failLogger).warn(anyString()); @@ -39,8 +40,8 @@ class FailsafeLoggerTest { doThrow(new RuntimeException()).when(failLogger).debug(anyString()); doThrow(new RuntimeException()).when(failLogger).trace(anyString()); - failsafeLogger.error("error"); - failsafeLogger.warn("warn"); + failsafeLogger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", "error"); + failsafeLogger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "warn"); failsafeLogger.info("info"); failsafeLogger.debug("debug"); failsafeLogger.trace("info"); @@ -51,14 +52,14 @@ class FailsafeLoggerTest { doThrow(new RuntimeException()).when(failLogger).debug(any(Throwable.class)); doThrow(new RuntimeException()).when(failLogger).trace(any(Throwable.class)); - failsafeLogger.error(new Exception("error")); - failsafeLogger.warn(new Exception("warn")); + failsafeLogger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", "error", new Exception("error")); + failsafeLogger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "warn", new Exception("warn")); failsafeLogger.info(new Exception("info")); failsafeLogger.debug(new Exception("debug")); failsafeLogger.trace(new Exception("trace")); - failsafeLogger.error("error", new Exception("error")); - failsafeLogger.warn("warn", new Exception("warn")); + failsafeLogger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", "error", new Exception("error")); + failsafeLogger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "warn", new Exception("warn")); failsafeLogger.info("info", new Exception("info")); failsafeLogger.debug("debug", new Exception("debug")); failsafeLogger.trace("trace", new Exception("trace")); @@ -67,9 +68,9 @@ class FailsafeLoggerTest { @Test void testSuccessLogger() { Logger successLogger = mock(Logger.class); - FailsafeLogger failsafeLogger = new FailsafeLogger(successLogger); - failsafeLogger.error("error"); - failsafeLogger.warn("warn"); + FailsafeErrorTypeAwareLogger failsafeLogger = new FailsafeErrorTypeAwareLogger(successLogger); + failsafeLogger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", "error"); + failsafeLogger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "warn"); failsafeLogger.info("info"); failsafeLogger.debug("debug"); failsafeLogger.trace("info"); @@ -80,14 +81,14 @@ class FailsafeLoggerTest { verify(successLogger).debug(anyString()); verify(successLogger).trace(anyString()); - failsafeLogger.error(new Exception("error")); - failsafeLogger.warn(new Exception("warn")); + failsafeLogger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", "error", new Exception("error")); + failsafeLogger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "warn", new Exception("warn")); failsafeLogger.info(new Exception("info")); failsafeLogger.debug(new Exception("debug")); failsafeLogger.trace(new Exception("trace")); - failsafeLogger.error("error", new Exception("error")); - failsafeLogger.warn("warn", new Exception("warn")); + failsafeLogger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", "error", new Exception("error")); + failsafeLogger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "warn", new Exception("warn")); failsafeLogger.info("info", new Exception("info")); failsafeLogger.debug("debug", new Exception("debug")); failsafeLogger.trace("trace", new Exception("trace")); @@ -97,10 +98,10 @@ class FailsafeLoggerTest { void testGetLogger() { Assertions.assertThrows(RuntimeException.class, () -> { Logger failLogger = mock(Logger.class); - FailsafeLogger failsafeLogger = new FailsafeLogger(failLogger); + FailsafeErrorTypeAwareLogger failsafeLogger = new FailsafeErrorTypeAwareLogger(failLogger); doThrow(new RuntimeException()).when(failLogger).error(anyString()); failsafeLogger.getLogger().error("should get error"); }); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ConfigValidationUtils.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ConfigValidationUtils.java index a716800abb..4d8801a72a 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ConfigValidationUtils.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ConfigValidationUtils.java @@ -100,6 +100,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_SE import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.USERNAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_CLASS_NOT_FOUND; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_PARAMETER_FORMAT_ERROR; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTER_MODE_ALL; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTER_MODE_INSTANCE; @@ -498,7 +499,7 @@ public class ConfigValidationUtils { try { ClassUtils.forName("org.apache.dubbo.qos.protocol.QosProtocolWrapper"); } catch (ClassNotFoundException e) { - logger.warn("No QosProtocolWrapper class was found. Please check the dependency of dubbo-qos whether was imported correctly.", e); + logger.warn(COMMON_CLASS_NOT_FOUND, "", "", "No QosProtocolWrapper class was found. Please check the dependency of dubbo-qos whether was imported correctly.", e); } } } @@ -641,7 +642,7 @@ public class ConfigValidationUtils { * @param value The Extension name */ public static void checkMultiExtension(ScopeModel scopeModel, Class type, String property, String value) { - checkMultiExtension(scopeModel,Collections.singletonList(type), property, value); + checkMultiExtension(scopeModel, Collections.singletonList(type), property, value); } public static void checkMultiExtension(ScopeModel scopeModel, List> types, String property, String value) { diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/MultiInstanceTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/MultiInstanceTest.java index d14c5bc837..994fbe5c99 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/MultiInstanceTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/MultiInstanceTest.java @@ -20,7 +20,7 @@ import org.apache.dubbo.common.deploy.ApplicationDeployer; import org.apache.dubbo.common.deploy.DeployListener; import org.apache.dubbo.common.deploy.DeployState; import org.apache.dubbo.common.deploy.ModuleDeployer; -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; @@ -63,7 +63,7 @@ import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_BOSS_POOL_NAME; class MultiInstanceTest { - private static final Logger logger = LoggerFactory.getLogger(MultiInstanceTest.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MultiInstanceTest.class); private static RegistryConfig registryConfig; @@ -101,7 +101,7 @@ class MultiInstanceTest { Map unclosedThreadMap = testChecker.checkUnclosedThreads(testClassName, 3000); if (unclosedThreadMap.size() > 0) { String str = getStackTraceString(unclosedThreadMap); - Assertions.fail("Found unclosed threads: " + unclosedThreadMap.size()+"\n" + str); + Assertions.fail("Found unclosed threads: " + unclosedThreadMap.size() + "\n" + str); } } @@ -396,24 +396,24 @@ class MultiInstanceTest { private void checkUnclosedThreadsOfApp(Map stackTraces1, String msg, String[] ignoredThreadPrefixes) { int waitTimeMs = 5000; - System.out.println("Wait "+waitTimeMs+"ms to check threads of app ..."); + System.out.println("Wait " + waitTimeMs + "ms to check threads of app ..."); try { Thread.sleep(waitTimeMs); } catch (InterruptedException e) { } HashMap unclosedThreadMap1 = new HashMap<>(stackTraces1); unclosedThreadMap1.keySet().removeIf(thread -> !thread.isAlive()); - if (ignoredThreadPrefixes!= null && ignoredThreadPrefixes.length > 0) { + if (ignoredThreadPrefixes != null && ignoredThreadPrefixes.length > 0) { unclosedThreadMap1.keySet().removeIf(thread -> isIgnoredThread(thread.getName(), ignoredThreadPrefixes)); } if (unclosedThreadMap1.size() > 0) { String str = getStackTraceString(unclosedThreadMap1); - Assertions.fail(msg + unclosedThreadMap1.size()+"\n" + str); + Assertions.fail(msg + unclosedThreadMap1.size() + "\n" + str); } } private boolean isIgnoredThread(String name, String[] ignoredThreadPrefixes) { - if (ignoredThreadPrefixes!= null && ignoredThreadPrefixes.length > 0) { + if (ignoredThreadPrefixes != null && ignoredThreadPrefixes.length > 0) { for (String prefix : ignoredThreadPrefixes) { if (name.startsWith(prefix)) { return true; @@ -613,7 +613,7 @@ class MultiInstanceTest { providerBootstrap.start(); Assertions.assertEquals(DeployState.STARTED, applicationDeployer.getState()); Assertions.assertEquals(DeployState.STARTED, defaultModule.getDeployer().getState()); - + // 3. add module2 and re-start application ServiceConfig serviceConfig2 = new ServiceConfig(); serviceConfig2.setInterface(DemoService.class); @@ -625,7 +625,7 @@ class MultiInstanceTest { providerBootstrap.start(); Assertions.assertEquals(DeployState.STARTED, applicationDeployer.getState()); Assertions.assertEquals(DeployState.STARTED, moduleModel2.getDeployer().getState()); - + // 4. add module3 and start module3 ServiceConfig serviceConfig3 = new ServiceConfig(); serviceConfig3.setInterface(DemoService.class); @@ -803,7 +803,7 @@ class MultiInstanceTest { .protocol(new ProtocolConfig("dubbo", -1)) .service(serviceConfig) .asyncStart(); - logger.warn("provider app has start async"); + logger.info("provider app has start async"); // it might be started if running on fast machine. // Assertions.assertFalse(serviceConfig.getScopeModel().getDeployer().isStarted(), "Async export seems something wrong"); @@ -813,27 +813,27 @@ class MultiInstanceTest { .registry(registryConfig) .reference(referenceConfig) .asyncStart(); - logger.warn("consumer app has start async"); + logger.info("consumer app has start async"); // it might be started if running on fast machine. // Assertions.assertFalse(referenceConfig.getScopeModel().getDeployer().isStarted(), "Async refer seems something wrong"); // wait for provider app startup providerFuture.get(); - logger.warn("provider app is startup"); + logger.info("provider app is startup"); Assertions.assertEquals(true, serviceConfig.isExported()); ServiceDescriptor serviceDescriptor = serviceConfig.getScopeModel().getServiceRepository().lookupService(Greeting.class.getName()); Assertions.assertNotNull(serviceDescriptor); // wait for consumer app startup consumerFuture.get(); - logger.warn("consumer app is startup"); + logger.info("consumer app is startup"); Object target = referenceConfig.getServiceMetadata().getTarget(); Assertions.assertNotNull(target); // wait for invokers notified from registry - MigrationInvoker migrationInvoker = (MigrationInvoker) referenceConfig.getInvoker(); + MigrationInvoker migrationInvoker = (MigrationInvoker) referenceConfig.getInvoker(); for (int i = 0; i < 10; i++) { if (((List) migrationInvoker.getDirectory().getAllInvokers()) - .stream().anyMatch(invoker -> invoker.getInterface() == Greeting.class)) { + .stream().anyMatch(invoker -> invoker.getInterface() == Greeting.class)) { break; } Thread.sleep(100); @@ -925,4 +925,4 @@ class MultiInstanceTest { deployEventMap.put(DeployState.FAILED, System.currentTimeMillis()); } } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ConfigValidationUtilsTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ConfigValidationUtilsTest.java index b98c46ec9d..af98533496 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ConfigValidationUtilsTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ConfigValidationUtilsTest.java @@ -33,6 +33,7 @@ import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_CLASS_NOT_FOUND; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; @@ -101,7 +102,7 @@ class ConfigValidationUtilsTest { try (MockedStatic mockedStatic = Mockito.mockStatic(ConfigValidationUtils.class);) { mockedStatic.when(() -> ConfigValidationUtils.validateApplicationConfig(any())).thenCallRealMethod(); ApplicationConfig config = new ApplicationConfig(); - Assertions.assertThrows(IllegalStateException.class,() -> { + Assertions.assertThrows(IllegalStateException.class, () -> { ConfigValidationUtils.validateApplicationConfig(config); }); @@ -140,7 +141,7 @@ class ConfigValidationUtilsTest { config.setQosEnable(true); mock.validateApplicationConfig(config); - verify(loggerMock).warn(eq("No QosProtocolWrapper class was found. Please check the dependency of dubbo-qos whether was imported correctly."), any()); + verify(loggerMock).warn(eq(COMMON_CLASS_NOT_FOUND), eq(""), eq(""), eq("No QosProtocolWrapper class was found. Please check the dependency of dubbo-qos whether was imported correctly."), any()); } private void injectField(Field field, Object newValue) throws Exception { diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationBeanPostProcessor.java index 381c6df0af..9960e6731e 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationBeanPostProcessor.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.config.spring.beans.factory.annotation; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; +import org.apache.dubbo.common.logger.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; import org.springframework.beans.PropertyValues; @@ -54,6 +54,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static com.alibaba.spring.util.AnnotationUtils.getAnnotationAttributes; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_INITIALIZER; import static org.springframework.core.BridgeMethodResolver.findBridgedMethod; import static org.springframework.core.BridgeMethodResolver.isVisibilityBridgeMethodPair; @@ -62,17 +63,17 @@ import static org.springframework.core.BridgeMethodResolver.isVisibilityBridgeMe */ @SuppressWarnings("unchecked") public abstract class AbstractAnnotationBeanPostProcessor extends - InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor, - BeanFactoryAware, BeanClassLoaderAware, EnvironmentAware, DisposableBean { + InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor, + BeanFactoryAware, BeanClassLoaderAware, EnvironmentAware, DisposableBean { private final static int CACHE_SIZE = Integer.getInteger("", 32); - private final Log logger = LogFactory.getLog(getClass()); + private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final Class[] annotationTypes; private final ConcurrentMap injectionMetadataCache = - new ConcurrentHashMap(CACHE_SIZE); + new ConcurrentHashMap(CACHE_SIZE); private ConfigurableListableBeanFactory beanFactory; @@ -116,7 +117,7 @@ public abstract class AbstractAnnotationBeanPostProcessor extends @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { Assert.isInstanceOf(ConfigurableListableBeanFactory.class, beanFactory, - "AnnotationInjectedBeanPostProcessor requires a ConfigurableListableBeanFactory"); + "AnnotationInjectedBeanPostProcessor requires a ConfigurableListableBeanFactory"); this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; } @@ -140,7 +141,7 @@ public abstract class AbstractAnnotationBeanPostProcessor extends if (Modifier.isStatic(field.getModifiers())) { if (logger.isWarnEnabled()) { - logger.warn("@" + annotationType.getName() + " is not supported on static fields: " + field); + logger.warn(CONFIG_DUBBO_BEAN_INITIALIZER, "", "", "@" + annotationType.getName() + " is not supported on static fields: " + field); } return; } @@ -183,10 +184,10 @@ public abstract class AbstractAnnotationBeanPostProcessor extends if (attributes != null && method.equals(ClassUtils.getMostSpecificMethod(method, beanClass))) { if (Modifier.isStatic(method.getModifiers())) { - throw new IllegalStateException("When using @"+annotationType.getName() +" to inject interface proxy, it is not supported on static methods: "+method); + throw new IllegalStateException("When using @" + annotationType.getName() + " to inject interface proxy, it is not supported on static methods: " + method); } if (method.getParameterTypes().length != 1) { - throw new IllegalStateException("When using @"+annotationType.getName() +" to inject interface proxy, the method must have only one parameter: "+method); + throw new IllegalStateException("When using @" + annotationType.getName() + " to inject interface proxy, the method must have only one parameter: " + method); } PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, beanClass); elements.add(new AnnotatedMethodElement(method, pd, attributes)); @@ -221,7 +222,7 @@ public abstract class AbstractAnnotationBeanPostProcessor extends this.injectionMetadataCache.put(cacheKey, metadata); } catch (NoClassDefFoundError err) { throw new IllegalStateException("Failed to introspect object class [" + clazz.getName() + - "] for annotation metadata: could not find class that it depends on", err); + "] for annotation metadata: could not find class that it depends on", err); } } } @@ -285,6 +286,7 @@ public abstract class AbstractAnnotationBeanPostProcessor extends /** * Prepare injection data after found injection elements + * * @param metadata * @throws Exception */ @@ -343,7 +345,7 @@ public abstract class AbstractAnnotationBeanPostProcessor extends return false; } //IGNORE Spring CGLIB enhanced class - if (targetClass.isAssignableFrom(clazz) && clazz.getName().contains("$$EnhancerBySpringCGLIB$$")) { + if (targetClass.isAssignableFrom(clazz) && clazz.getName().contains("$$EnhancerBySpringCGLIB$$")) { return false; } return true; @@ -386,11 +388,9 @@ public abstract class AbstractAnnotationBeanPostProcessor extends if (injectedType == null) { if (this.isField) { injectedType = ((Field) this.member).getType(); - } - else if (this.pd != null) { + } else if (this.pd != null) { return this.pd.getPropertyType(); - } - else { + } else { Method method = (Method) this.member; if (method.getParameterTypes().length > 0) { injectedType = method.getParameterTypes()[0]; diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java index 3c6eadda67..be855881bc 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java @@ -17,7 +17,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.Assert; import org.apache.dubbo.common.utils.ClassUtils; @@ -65,6 +65,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static com.alibaba.spring.util.AnnotationUtils.getAttribute; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_INITIALIZER; import static org.apache.dubbo.common.utils.AnnotationUtils.filterDefaultValues; import static org.springframework.util.StringUtils.hasText; @@ -87,7 +88,7 @@ import static org.springframework.util.StringUtils.hasText; * @since 2.5.7 */ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBeanPostProcessor - implements ApplicationContextAware, BeanFactoryPostProcessor { + implements ApplicationContextAware, BeanFactoryPostProcessor { /** * The bean name of {@link ReferenceAnnotationBeanPostProcessor} @@ -99,13 +100,13 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean */ private static final int CACHE_SIZE = Integer.getInteger(BEAN_NAME + ".cache.size", 32); - private final Logger logger = LoggerFactory.getLogger(getClass()); + private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final ConcurrentMap injectedFieldReferenceBeanCache = - new ConcurrentHashMap<>(CACHE_SIZE); + new ConcurrentHashMap<>(CACHE_SIZE); private final ConcurrentMap injectedMethodReferenceBeanCache = - new ConcurrentHashMap<>(CACHE_SIZE); + new ConcurrentHashMap<>(CACHE_SIZE); private ApplicationContext applicationContext; @@ -127,7 +128,7 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean String[] beanNames = beanFactory.getBeanDefinitionNames(); for (String beanName : beanNames) { Class beanType; - if (beanFactory.isFactoryBean(beanName)){ + if (beanFactory.isFactoryBean(beanName)) { BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); if (isReferenceBean(beanDefinition)) { continue; @@ -172,7 +173,7 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean applicationContext.publishEvent(new DubboConfigInitEvent(applicationContext)); } catch (Exception e) { // if spring version is less than 4.2, it does not support early application event - logger.warn("publish early application event failed, please upgrade spring version to 4.2.x or later: " + e); + logger.warn(CONFIG_DUBBO_BEAN_INITIALIZER, "", "", "publish early application event failed, please upgrade spring version to 4.2.x or later: " + e); } } @@ -204,6 +205,7 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean * * } * + * * @param beanName * @param beanDefinition */ @@ -309,7 +311,7 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean @Override public PropertyValues postProcessPropertyValues( - PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException { + PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException { try { AnnotatedInjectionMetadata metadata = findInjectionMetadata(beanName, bean.getClass(), pvs); @@ -319,7 +321,7 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean throw ex; } catch (Throwable ex) { throw new BeanCreationException(beanName, "Injection of @" + getAnnotationType().getSimpleName() - + " dependencies is failed", ex); + + " dependencies is failed", ex); } return pvs; } @@ -437,7 +439,7 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean } newBeanDesc = newReferenceBeanName + "[" + referenceKey + "]"; - logger.warn("Already exists another bean definition with the same bean name [" + referenceBeanName + "], " + + logger.warn(CONFIG_DUBBO_BEAN_INITIALIZER, "", "", "Already exists another bean definition with the same bean name [" + referenceBeanName + "], " + "rename dubbo reference bean to [" + newReferenceBeanName + "]. " + "It is recommended to modify the name of one of the beans to avoid injection problems. " + "prev: " + prevBeanDesc + ", new: " + newBeanDesc + ". " + checkLocation); @@ -508,7 +510,8 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean /** * Gets all beans of {@link ReferenceBean} - * @deprecated use {@link ReferenceBeanManager.getReferences()} instead + * + * @deprecated use {@link ReferenceBeanManager.getReferences()} instead */ @Deprecated public Collection> getReferenceBeans() { diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboBootstrapApplicationListener.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboBootstrapApplicationListener.java index 58e295cd87..802e32d9d4 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboBootstrapApplicationListener.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboBootstrapApplicationListener.java @@ -16,14 +16,14 @@ */ package org.apache.dubbo.config.spring.context; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; +import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.bootstrap.BootstrapTakeoverMode; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.context.event.DubboConfigInitEvent; import org.apache.dubbo.config.spring.util.DubboBeanUtils; import org.apache.dubbo.rpc.model.ModuleModel; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; @@ -34,6 +34,8 @@ import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.core.Ordered; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_INITIALIZER; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_NOT_FOUND; import static org.springframework.util.ObjectUtils.nullSafeEquals; /** @@ -52,7 +54,7 @@ public class DubboBootstrapApplicationListener implements ApplicationListener, A */ public static final String BEAN_NAME = "dubboBootstrapApplicationListener"; - private final Log logger = LogFactory.getLog(getClass()); + private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private ApplicationContext applicationContext; private DubboBootstrap bootstrap; @@ -92,7 +94,7 @@ public class DubboBootstrapApplicationListener implements ApplicationListener, A if (applicationContext.containsBean(DubboConfigBeanInitializer.BEAN_NAME)) { applicationContext.getBean(DubboConfigBeanInitializer.BEAN_NAME, DubboConfigBeanInitializer.class); } else { - logger.warn("Bean '" + DubboConfigBeanInitializer.BEAN_NAME + "' was not found"); + logger.warn(CONFIG_DUBBO_BEAN_NOT_FOUND, "", "", "Bean '" + DubboConfigBeanInitializer.BEAN_NAME + "' was not found"); } // All infrastructure config beans are loaded, initialize dubbo here @@ -127,6 +129,7 @@ public class DubboBootstrapApplicationListener implements ApplicationListener, A /** * Is original {@link ApplicationContext} as the event source + * * @param event {@link ApplicationEvent} * @return if original, return true, or false */ @@ -166,8 +169,8 @@ public class DubboBootstrapApplicationListener implements ApplicationListener, A // init config beans here, compatible with spring 3.x/4.1.x initDubboConfigBeans(); } else { - logger.warn("DubboBootstrapApplicationListener initialization is unexpected, " + - "it should be created in AbstractApplicationContext.registerListeners() method", exception); + logger.warn(CONFIG_DUBBO_BEAN_INITIALIZER, "", "", "DubboBootstrapApplicationListener initialization is unexpected, " + + "it should be created in AbstractApplicationContext.registerListeners() method", exception); } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboConfigApplicationListener.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboConfigApplicationListener.java index 23c66f434e..0097382fae 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboConfigApplicationListener.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboConfigApplicationListener.java @@ -16,11 +16,13 @@ */ package org.apache.dubbo.config.spring.context; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_NOT_FOUND; import static org.springframework.util.ObjectUtils.nullSafeEquals; import java.util.concurrent.atomic.AtomicBoolean; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; + +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; +import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.spring.context.event.DubboConfigInitEvent; import org.apache.dubbo.config.spring.util.DubboBeanUtils; import org.apache.dubbo.rpc.model.ModuleModel; @@ -34,7 +36,7 @@ import org.springframework.context.ApplicationListener; */ public class DubboConfigApplicationListener implements ApplicationListener, ApplicationContextAware { - private final static Log logger = LogFactory.getLog(DubboConfigApplicationListener.class); + private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboConfigApplicationListener.class); private ApplicationContext applicationContext; @@ -64,7 +66,7 @@ public class DubboConfigApplicationListener implements ApplicationListener reference bean names private Map> referenceKeyMap = new ConcurrentHashMap<>(); @@ -65,9 +67,9 @@ public class ReferenceBeanManager implements ApplicationContextAware { if (!initialized) { //TODO add issue url to describe early initialization - logger.warn("Early initialize reference bean before DubboConfigBeanInitializer," + - " the BeanPostProcessor has not been loaded at this time, which may cause abnormalities in some components (such as seata): " + - referenceBeanName + " = " + ReferenceBeanSupport.generateReferenceKey(referenceBean, applicationContext)); + logger.warn(CONFIG_DUBBO_BEAN_INITIALIZER, "", "", "Early initialize reference bean before DubboConfigBeanInitializer," + + " the BeanPostProcessor has not been loaded at this time, which may cause abnormalities in some components (such as seata): " + + referenceBeanName + " = " + ReferenceBeanSupport.generateReferenceKey(referenceBean, applicationContext)); } String referenceKey = getReferenceKeyByBeanName(referenceBeanName); if (StringUtils.isEmpty(referenceKey)) { @@ -78,7 +80,7 @@ public class ReferenceBeanManager implements ApplicationContextAware { if (referenceBean != oldReferenceBean) { String oldReferenceKey = ReferenceBeanSupport.generateReferenceKey(oldReferenceBean, applicationContext); throw new IllegalStateException("Found duplicated ReferenceBean with id: " + referenceBeanName + - ", old: " + oldReferenceKey + ", new: " + referenceKey); + ", old: " + oldReferenceKey + ", new: " + referenceKey); } return; } @@ -92,7 +94,7 @@ public class ReferenceBeanManager implements ApplicationContextAware { } } - private String getReferenceKeyByBeanName(String referenceBeanName){ + private String getReferenceKeyByBeanName(String referenceBeanName) { Set>> entries = referenceKeyMap.entrySet(); for (Map.Entry> entry : entries) { if (entry.getValue().contains(referenceBeanName)) { @@ -172,8 +174,8 @@ public class ReferenceBeanManager implements ApplicationContextAware { //create real ReferenceConfig Map referenceAttributes = ReferenceBeanSupport.getReferenceAttributes(referenceBean); referenceConfig = ReferenceCreator.create(referenceAttributes, applicationContext) - .defaultInterfaceClass(referenceBean.getObjectType()) - .build(); + .defaultInterfaceClass(referenceBean.getObjectType()) + .build(); // set id if it is not a generated name if (referenceBean.getId() != null && !referenceBean.getId().contains("#")) { diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/EmbeddedZooKeeper.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/EmbeddedZooKeeper.java index 009f371bb9..5b94d07f9b 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/EmbeddedZooKeeper.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/EmbeddedZooKeeper.java @@ -30,6 +30,7 @@ import java.util.Properties; import java.util.UUID; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_ZOOKEEPER_SERVER_ERROR; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_STOP_ZOOKEEPER; /** * from: https://github.com/spring-projects/spring-xd/blob/v1.3.1.RELEASE/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/zookeeper/ZooKeeperUtils.java @@ -38,7 +39,6 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_ZOOKE *

* NOTE: at least an external standalone server (if not an ensemble) are recommended, even for * {@link org.springframework.xd.dirt.server.singlenode.SingleNodeApplication} - * */ public class EmbeddedZooKeeper implements SmartLifecycle { @@ -187,7 +187,7 @@ public class EmbeddedZooKeeper implements SmartLifecycle { zkServerThread = null; } catch (InterruptedException e) { Thread.currentThread().interrupt(); - logger.warn("Interrupted while waiting for embedded ZooKeeper to exit"); + logger.warn(REGISTRY_FAILED_STOP_ZOOKEEPER, "", "", "Interrupted while waiting for embedded ZooKeeper to exit"); // abandoning zk thread zkServerThread = null; } @@ -223,7 +223,7 @@ public class EmbeddedZooKeeper implements SmartLifecycle { try { Properties properties = new Properties(); File file = new File(System.getProperty("java.io.tmpdir") - + File.separator + UUID.randomUUID()); + + File.separator + UUID.randomUUID()); file.deleteOnExit(); properties.setProperty("dataDir", file.getAbsolutePath()); properties.setProperty("clientPort", String.valueOf(clientPort)); diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/EmbeddedApolloJunit5.java b/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/EmbeddedApolloJunit5.java index 5b93b14971..852ed2ebe9 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/EmbeddedApolloJunit5.java +++ b/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/EmbeddedApolloJunit5.java @@ -17,6 +17,8 @@ package org.apache.dubbo.configcenter.support.apollo; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; +import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.JsonUtils; import com.ctrip.framework.apollo.build.ApolloInjector; @@ -33,8 +35,6 @@ import okhttp3.mockwebserver.RecordedRequest; import org.junit.jupiter.api.extension.AfterAllCallback; import org.junit.jupiter.api.extension.BeforeAllCallback; import org.junit.jupiter.api.extension.ExtensionContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.util.ArrayList; @@ -43,8 +43,10 @@ import java.util.Map; import java.util.Properties; import java.util.Set; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CLOSE_CONNECT_APOLLO; + public class EmbeddedApolloJunit5 implements BeforeAllCallback, AfterAllCallback { - private static final Logger logger = LoggerFactory.getLogger(EmbeddedApolloJunit5.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(EmbeddedApolloJunit5.class); private static Method CONFIG_SERVICE_LOCATOR_CLEAR; private static ConfigServiceLocator CONFIG_SERVICE_LOCATOR; @@ -154,7 +156,7 @@ public class EmbeddedApolloJunit5 implements BeforeAllCallback, AfterAllCallback clear(); server.close(); } catch (Exception e) { - logger.error("stop apollo server error", e); + logger.error(CONFIG_FAILED_CLOSE_CONNECT_APOLLO, "", "", "stop apollo server error", e); } } diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java index cd20375fa3..64ff639eda 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java @@ -36,6 +36,7 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; 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 ZookeeperDynamicConfiguration extends TreePathDynamicConfiguration { @@ -116,7 +117,7 @@ public class ZookeeperDynamicConfiguration extends TreePathDynamicConfiguration 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-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 70e624e758..a2f1d78f0a 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 @@ -93,7 +93,7 @@ public class NacosMetadataReport extends AbstractMetadataReport { configService = new NacosConfigServiceWrapper(NacosFactory.createConfigService(nacosProperties)); } catch (NacosException e) { if (logger.isErrorEnabled()) { - logger.error(e.getErrMsg(), e); + logger.error(REGISTRY_NACOS_EXCEPTION, "", "", e.getErrMsg(), e); } throw new IllegalStateException(e); } diff --git a/dubbo-metadata/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java b/dubbo-metadata/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java index c8c99fc173..a7b0b5d189 100644 --- a/dubbo-metadata/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java @@ -17,7 +17,7 @@ package org.apache.dubbo.metadata.store.redis; 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.metadata.report.identifier.BaseMetadataIdentifier; @@ -45,6 +45,7 @@ import java.util.Set; import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY; 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_RESPONSE; import static org.apache.dubbo.metadata.MetadataConstants.META_DATA_STORE_TAG; /** @@ -53,7 +54,7 @@ import static org.apache.dubbo.metadata.MetadataConstants.META_DATA_STORE_TAG; public class RedisMetadataReport extends AbstractMetadataReport { private static final String REDIS_DATABASE_KEY = "database"; - private static final Logger logger = LoggerFactory.getLogger(RedisMetadataReport.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RedisMetadataReport.class); // protected , for test protected JedisPool pool; @@ -133,8 +134,9 @@ public class RedisMetadataReport extends AbstractMetadataReport { try (JedisCluster jedisCluster = new JedisCluster(jedisClusterNodes, timeout, timeout, 2, password, new GenericObjectPoolConfig())) { jedisCluster.set(metadataIdentifier.getIdentifierKey() + META_DATA_STORE_TAG, v); } catch (Throwable e) { - logger.error("Failed to put " + metadataIdentifier + " to redis cluster " + v + ", cause: " + e.getMessage(), e); - throw new RpcException("Failed to put " + metadataIdentifier + " to redis cluster " + v + ", cause: " + e.getMessage(), e); + String msg = "Failed to put " + metadataIdentifier + " to redis cluster " + v + ", cause: " + e.getMessage(); + logger.error(TRANSPORT_FAILED_RESPONSE, "", "", msg, e); + throw new RpcException(msg, e); } } @@ -142,8 +144,9 @@ public class RedisMetadataReport extends AbstractMetadataReport { try (Jedis jedis = pool.getResource()) { jedis.set(metadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), v); } catch (Throwable e) { - logger.error("Failed to put " + metadataIdentifier + " to redis " + v + ", cause: " + e.getMessage(), e); - throw new RpcException("Failed to put " + metadataIdentifier + " to redis " + v + ", cause: " + e.getMessage(), e); + String msg = "Failed to put " + metadataIdentifier + " to redis " + v + ", cause: " + e.getMessage(); + logger.error(TRANSPORT_FAILED_RESPONSE, "", "", msg, e); + throw new RpcException(msg, e); } } @@ -159,8 +162,9 @@ public class RedisMetadataReport extends AbstractMetadataReport { try (JedisCluster jedisCluster = new JedisCluster(jedisClusterNodes, timeout, timeout, 2, password, new GenericObjectPoolConfig())) { jedisCluster.del(metadataIdentifier.getIdentifierKey() + META_DATA_STORE_TAG); } catch (Throwable e) { - logger.error("Failed to delete " + metadataIdentifier + " from redis cluster , cause: " + e.getMessage(), e); - throw new RpcException("Failed to delete " + metadataIdentifier + " from redis cluster , cause: " + e.getMessage(), e); + String msg = "Failed to delete " + metadataIdentifier + " from redis cluster , cause: " + e.getMessage(); + logger.error(TRANSPORT_FAILED_RESPONSE, "", "", msg, e); + throw new RpcException(msg, e); } } @@ -168,8 +172,9 @@ public class RedisMetadataReport extends AbstractMetadataReport { try (Jedis jedis = pool.getResource()) { jedis.del(metadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY)); } catch (Throwable e) { - logger.error("Failed to delete " + metadataIdentifier + " from redis , cause: " + e.getMessage(), e); - throw new RpcException("Failed to delete " + metadataIdentifier + " from redis , cause: " + e.getMessage(), e); + String msg = "Failed to delete " + metadataIdentifier + " from redis , cause: " + e.getMessage(); + logger.error(TRANSPORT_FAILED_RESPONSE, "", "", msg, e); + throw new RpcException(msg, e); } } @@ -185,8 +190,9 @@ public class RedisMetadataReport extends AbstractMetadataReport { try (JedisCluster jedisCluster = new JedisCluster(jedisClusterNodes, timeout, timeout, 2, password, new GenericObjectPoolConfig())) { return jedisCluster.get(metadataIdentifier.getIdentifierKey() + META_DATA_STORE_TAG); } catch (Throwable e) { - logger.error("Failed to get " + metadataIdentifier + " from redis cluster , cause: " + e.getMessage(), e); - throw new RpcException("Failed to get " + metadataIdentifier + " from redis cluster , cause: " + e.getMessage(), e); + String msg = "Failed to get " + metadataIdentifier + " from redis cluster , cause: " + e.getMessage(); + logger.error(TRANSPORT_FAILED_RESPONSE, "", "", msg, e); + throw new RpcException(msg, e); } } @@ -194,8 +200,9 @@ public class RedisMetadataReport extends AbstractMetadataReport { try (Jedis jedis = pool.getResource()) { return jedis.get(metadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY)); } catch (Throwable e) { - logger.error("Failed to get " + metadataIdentifier + " from redis , cause: " + e.getMessage(), e); - throw new RpcException("Failed to get " + metadataIdentifier + " from redis , cause: " + e.getMessage(), e); + String msg = "Failed to get " + metadataIdentifier + " from redis , cause: " + e.getMessage(); + logger.error(TRANSPORT_FAILED_RESPONSE, "", "", msg, e); + throw new RpcException(msg, e); } } diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java index 4edd4a3c98..f4d0d54e03 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java @@ -19,7 +19,7 @@ package org.apache.dubbo.monitor.dubbo; 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.utils.JsonUtils; @@ -61,6 +61,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION; import static org.apache.dubbo.monitor.Constants.DUBBO_CONSUMER; import static org.apache.dubbo.monitor.Constants.DUBBO_CONSUMER_METHOD; import static org.apache.dubbo.monitor.Constants.DUBBO_GROUP; @@ -75,7 +76,7 @@ import static org.apache.dubbo.monitor.Constants.SERVICE; @Deprecated public class MetricsFilter implements Filter, ExtensionAccessorAware, ScopeModelAware { - private static final Logger logger = LoggerFactory.getLogger(MetricsFilter.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MetricsFilter.class); protected static volatile AtomicBoolean exported = new AtomicBoolean(false); private Integer port; private String protocolName; @@ -106,7 +107,7 @@ public class MetricsFilter implements Filter, ExtensionAccessorAware, ScopeModel try { protocol.export(metricsInvoker); } catch (RuntimeException e) { - logger.error("Metrics Service need to be configured" + + logger.error(COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", "Metrics Service need to be configured" + " when multiple processes are running on a host" + e.getMessage()); } } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceRegistryTest.java index a4dca95b0c..fdf5d25ccb 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceRegistryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceRegistryTest.java @@ -18,25 +18,26 @@ package org.apache.dubbo.registry; 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.NetUtils; import org.junit.jupiter.api.Test; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_ARGUMENT; + /** * RegistryPerformanceTest - * */ -class PerformanceRegistryTest { +class PerformanceRegistryTest { - private static final Logger logger = LoggerFactory.getLogger(PerformanceRegistryTest.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PerformanceRegistryTest.class); @Test void testRegistry() { // read server info from property if (PerformanceUtils.getProperty("server", null) == null) { - logger.warn("Please set -Dserver=127.0.0.1:9090"); + logger.warn(CONFIG_UNDEFINED_ARGUMENT, "", "", "Please set -Dserver=127.0.0.1:9090"); return; } final int base = PerformanceUtils.getIntProperty("base", 0); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java index 723c03a2c9..e9ce85825c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.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.common.serialize.support.DefaultSerializationSelector; import org.apache.dubbo.remoting.exchange.ExchangeClient; @@ -27,15 +27,16 @@ import org.junit.jupiter.api.Test; 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.CONFIG_UNDEFINED_ARGUMENT; /** * ChanelHandlerTest *

* mvn clean test -Dtest=*PerformanceClientTest -Dserver=10.20.153.187:9911 */ -class ChanelHandlerTest { +class ChanelHandlerTest { - private static final Logger logger = LoggerFactory.getLogger(ChanelHandlerTest.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ChanelHandlerTest.class); public static ExchangeClient initClient(String url) { // Create client and build connection @@ -48,7 +49,7 @@ class ChanelHandlerTest { } catch (Throwable t) { if (t != null && t.getCause() != null && t.getCause().getClass() != null && (t.getCause().getClass() == java.net.ConnectException.class - || t.getCause().getClass() == java.net.ConnectException.class)) { + || t.getCause().getClass() == java.net.ConnectException.class)) { } else { t.printStackTrace(); @@ -77,7 +78,7 @@ class ChanelHandlerTest { void testClient() throws Throwable { // read server info from property if (PerformanceUtils.getProperty("server", null) == null) { - logger.warn("Please set -Dserver=127.0.0.1:9911"); + logger.warn(CONFIG_UNDEFINED_ARGUMENT, "", "", "Please set -Dserver=127.0.0.1:9911"); return; } final String server = System.getProperty("server", "127.0.0.1:9911"); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java index b15f773451..6b8006ac85 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.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.common.serialize.support.DefaultSerializationSelector; import org.apache.dubbo.remoting.exchange.ExchangeClient; @@ -28,20 +28,21 @@ import java.util.concurrent.atomic.AtomicInteger; 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.CONFIG_UNDEFINED_ARGUMENT; /** * ProformanceClient * The test class will report abnormal thread pool, because the judgment on the thread pool concurrency problems produced in DefaultChannelHandler (connected event has been executed asynchronously, judgment, then closed the thread pool, thread pool and execution error, this problem can be specified through the Constants.CHANNEL_HANDLER_KEY=connection.) */ -class PerformanceClientCloseTest { +class PerformanceClientCloseTest { - private static final Logger logger = LoggerFactory.getLogger(PerformanceClientCloseTest.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PerformanceClientCloseTest.class); @Test void testClient() throws Throwable { // read server info from property if (PerformanceUtils.getProperty("server", null) == null) { - logger.warn("Please set -Dserver=127.0.0.1:9911"); + logger.warn(CONFIG_UNDEFINED_ARGUMENT, "", "", "Please set -Dserver=127.0.0.1:9911"); return; } final String server = System.getProperty("server", "127.0.0.1:9911"); @@ -53,9 +54,9 @@ class PerformanceClientCloseTest { final String onerror = PerformanceUtils.getProperty("onerror", "continue"); final String url = "exchange://" + server + "?transporter=" + transporter - + "&serialization=" + serialization + + "&serialization=" + serialization // + "&"+Constants.CHANNEL_HANDLER_KEY+"=connection" - + "&timeout=" + timeout; + + "&timeout=" + timeout; final AtomicInteger count = new AtomicInteger(); final AtomicInteger error = new AtomicInteger(); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java index 2474d43dd4..a684d9c2d7 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.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.common.serialize.support.DefaultSerializationSelector; import org.apache.dubbo.remoting.exchange.ExchangeClient; @@ -29,17 +29,18 @@ import java.util.Random; 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.CONFIG_UNDEFINED_ARGUMENT; import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY; -class PerformanceClientFixedTest { +class PerformanceClientFixedTest { - private static final Logger logger = LoggerFactory.getLogger(PerformanceClientTest.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PerformanceClientTest.class); @Test void testClient() throws Exception { // read the parameters if (PerformanceUtils.getProperty("server", null) == null) { - logger.warn("Please set -Dserver=127.0.0.1:9911"); + logger.warn(CONFIG_UNDEFINED_ARGUMENT, "", "", "Please set -Dserver=127.0.0.1:9911"); return; } final String server = System.getProperty("server", "127.0.0.1:9911"); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java index 2a4579d262..152d6c5dd9 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.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.common.serialize.support.DefaultSerializationSelector; import org.apache.dubbo.remoting.exchange.ExchangeClient; @@ -35,6 +35,7 @@ import java.util.concurrent.atomic.AtomicLong; 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.CONFIG_UNDEFINED_ARGUMENT; import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY; /** @@ -42,16 +43,16 @@ import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY; *

* mvn clean test -Dtest=*PerformanceClientTest -Dserver=10.20.153.187:9911 */ -class PerformanceClientTest { +class PerformanceClientTest { - private static final Logger logger = LoggerFactory.getLogger(PerformanceClientTest.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PerformanceClientTest.class); @Test @SuppressWarnings("unchecked") public void testClient() throws Throwable { // read server info from property if (PerformanceUtils.getProperty("server", null) == null) { - logger.warn("Please set -Dserver=127.0.0.1:9911"); + logger.warn(CONFIG_UNDEFINED_ARGUMENT, "", "", "Please set -Dserver=127.0.0.1:9911"); return; } final String server = System.getProperty("server", "127.0.0.1:9911"); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java index 1ac1af317e..5298f449e1 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.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.common.serialize.support.DefaultSerializationSelector; import org.apache.dubbo.remoting.exchange.ExchangeChannel; @@ -36,6 +36,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_ARGUMENT; import static org.apache.dubbo.remoting.Constants.BUFFER_KEY; import static org.apache.dubbo.remoting.Constants.DEFAULT_BUFFER_SIZE; @@ -44,9 +45,9 @@ import static org.apache.dubbo.remoting.Constants.DEFAULT_BUFFER_SIZE; *

* mvn clean test -Dtest=*PerformanceServerTest -Dport=9911 */ -class PerformanceServerTest { +class PerformanceServerTest { - private static final Logger logger = LoggerFactory.getLogger(PerformanceServerTest.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PerformanceServerTest.class); private static ExchangeServer server = null; private static void restartServer(int times, int alive, int sleep) throws Exception { @@ -79,9 +80,9 @@ class PerformanceServerTest { // Start server ExchangeServer server = Exchangers.bind("exchange://0.0.0.0:" + port + "?transporter=" - + transporter + "&serialization=" - + serialization + "&threadpool=" + threadpool - + "&threads=" + threads + "&iothreads=" + iothreads + "&buffer=" + buffer + "&channel.handler=" + channelHandler, new ExchangeHandlerAdapter() { + + transporter + "&serialization=" + + serialization + "&threadpool=" + threadpool + + "&threads=" + threads + "&iothreads=" + iothreads + "&buffer=" + buffer + "&channel.handler=" + channelHandler, new ExchangeHandlerAdapter() { public String telnet(Channel channel, String message) throws RemotingException { return "echo: " + message + "\r\ntelnet> "; } @@ -151,7 +152,7 @@ class PerformanceServerTest { void testServer() throws Exception { // Read port from property if (PerformanceUtils.getProperty("port", null) == null) { - logger.warn("Please set -Dport=9911"); + logger.warn(CONFIG_UNDEFINED_ARGUMENT, "", "", "Please set -Dport=9911"); return; } final int port = PerformanceUtils.getIntProperty("port", 9911); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedExchangeCodec.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedExchangeCodec.java index 5b0425e9d6..9a8910708b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedExchangeCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedExchangeCodec.java @@ -21,7 +21,7 @@ import org.apache.dubbo.common.io.Bytes; import org.apache.dubbo.common.io.StreamUtils; import org.apache.dubbo.common.io.UnsafeByteArrayInputStream; import org.apache.dubbo.common.io.UnsafeByteArrayOutputStream; -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; @@ -39,6 +39,9 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RESPONSE; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_SKIP_UNUSED_STREAM; + final class DeprecatedExchangeCodec extends DeprecatedTelnetCodec implements Codec { // header length. @@ -52,7 +55,7 @@ final class DeprecatedExchangeCodec extends DeprecatedTelnetCodec implements Cod 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(DeprecatedExchangeCodec.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DeprecatedExchangeCodec.class); public Short getMagicCode() { return MAGIC; @@ -78,7 +81,7 @@ final class DeprecatedExchangeCodec extends DeprecatedTelnetCodec implements Cod protected Object decode(Channel channel, InputStream is, 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); @@ -118,11 +121,11 @@ final class DeprecatedExchangeCodec extends DeprecatedTelnetCodec implements Cod 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); } } } @@ -276,7 +279,7 @@ final class DeprecatedExchangeCodec extends DeprecatedTelnetCodec implements Cod if (!res.isEvent() && res.getStatus() != Response.BAD_RESPONSE) { try { // FIXME log error info in Codec and put all error handle logic in 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); Response r = new Response(res.getId(), res.getVersion()); r.setStatus(Response.BAD_RESPONSE); @@ -285,7 +288,7 @@ final class DeprecatedExchangeCodec extends DeprecatedTelnetCodec implements Cod 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); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedTelnetCodec.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedTelnetCodec.java index 7a82e64ddd..3f7ded3931 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedTelnetCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedTelnetCodec.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.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.serialize.ObjectOutput; import org.apache.dubbo.common.utils.NetUtils; @@ -39,11 +39,12 @@ import java.util.LinkedList; import java.util.List; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_EXCEED_PAYLOAD_LIMIT; import static org.apache.dubbo.remoting.Constants.CHARSET_KEY; public class DeprecatedTelnetCodec implements Codec { - private static final Logger logger = LoggerFactory.getLogger(DeprecatedTelnetCodec.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DeprecatedTelnetCodec.class); private static final String HISTORY_LIST_KEY = "telnet.history.list"; @@ -64,7 +65,7 @@ public class DeprecatedTelnetCodec implements Codec { } if (size > payload) { IOException e = new IOException("Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); - logger.error(e); + logger.error(TRANSPORT_EXCEED_PAYLOAD_LIMIT, "", "", e.getMessage(), e); throw e; } } @@ -124,7 +125,7 @@ public class DeprecatedTelnetCodec implements Codec { 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]; @@ -163,11 +164,11 @@ public class DeprecatedTelnetCodec implements Codec { InetSocketAddress address = channel.getRemoteAddress(); URL url = channel.getUrl(); boolean client = url.getPort() == address.getPort() - && NetUtils.filterLocalHost(url.getIp()).equals( - NetUtils.filterLocalHost(address.getAddress() - .getHostAddress())); + && NetUtils.filterLocalHost(url.getIp()).equals( + NetUtils.filterLocalHost(address.getAddress() + .getHostAddress())); channel.setAttribute(SIDE_KEY, client ? "client" - : "server"); + : "server"); return client; } } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleClientStream.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleClientStream.java index 41815f6fab..e102426580 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleClientStream.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleClientStream.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; @@ -52,6 +52,8 @@ import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.concurrent.Executor; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_REFLECT; + /** * ClientStream is an abstraction for bi-directional messaging. It maintains a {@link WriteQueue} to @@ -60,7 +62,7 @@ import java.util.concurrent.Executor; */ public class TripleClientStream extends AbstractStream implements ClientStream { - private static final Logger LOGGER = LoggerFactory.getLogger(TripleClientStream.class); + private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(TripleClientStream.class); public final ClientStream.Listener listener; private final WriteQueue writeQueue; @@ -69,9 +71,9 @@ public class TripleClientStream extends AbstractStream implements ClientStream { // for test TripleClientStream(FrameworkModel frameworkModel, - Executor executor, - WriteQueue writeQueue, - ClientStream.Listener listener) { + Executor executor, + WriteQueue writeQueue, + ClientStream.Listener listener) { super(executor, frameworkModel); this.parent = null; this.listener = listener; @@ -79,9 +81,9 @@ public class TripleClientStream extends AbstractStream implements ClientStream { } public TripleClientStream(FrameworkModel frameworkModel, - Executor executor, - Channel parent, - ClientStream.Listener listener) { + Executor executor, + Channel parent, + ClientStream.Listener listener) { super(executor, frameworkModel); this.parent = parent; this.listener = listener; @@ -213,7 +215,7 @@ public class TripleClientStream extends AbstractStream implements ClientStream { } }); } else { - LOGGER.error("Triple convertNoLowerCaseHeader error, obj is not String"); + LOGGER.error(COMMON_FAILED_REFLECT, "", "", "Triple convertNoLowerCaseHeader error, obj is not String"); } return attachments; }